ASP.Net JavaScript Print Div Content

To Print Div Content using JavaScript use below code

HTML Page

HTML Page Code


<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Print.aspx.cs" Inherits="Print" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">

<head>
<title>Javascript Print</title>
<!--BootStrap CSS Start-->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" type="text/css" />
<!--BootStrap CSS End-->
<!--JQuery Script Start-->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js" type="text/javascript"></script>
<!--JQuery Script End-->
<!--Bootstrap Script Start-->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" type="text/javascript"></script>
<!--Bootstrap Script End-->
<!--Print Div Script Start-->
<script type="text/javascript">
function PrintDiv() {
var disp_setting = "toolbar=yes,location=no,directories=yes,menubar=yes,";
disp_setting += "";
var content_vlue = document.getElementById("divContent").innerHTML;
var docprint = window.open("", "", disp_setting);
docprint.document.open();
docprint.document.write('<html><head><title>Print Page Name</title>');
docprint.document.write('</head><body onLoad="self.print()">');
docprint.document.write(content_vlue);
docprint.document.write('</body></html>');
docprint.document.close();
docprint.focus();
}
</script>
<!--Print Div Script End-->
</head>
<body>
<form id="form1" runat="server">
<div class="container" id="divContent">
<form class="form-inline">
<div class="form-group">
<h1>h1 Bootstrap heading (36px)</h1>
<h2>h2 Bootstrap heading (30px)</h2>
<h3>h3 Bootstrap heading (24px)</h3>
<h4>h4 Bootstrap heading (18px)</h4>
<h5>h5 Bootstrap heading (14px)</h5>
<h6>h6 Bootstrap heading (12px)</h6>
<table class="table">
<thead>
<tr>
<th>Firstname</th>
<th>Lastname</th>
<th>Email</th>
</tr>
</thead>
<tbody>
<tr>
<td>Default</td>
<td>Defaultson</td>
<td>def@somemail.com</td>
</tr>
<tr class="success">
<td>Success</td>
<td>Doe</td>
<td>john@example.com</td>
</tr>
<tr class="danger">
<td>Danger</td>
<td>Moe</td>
<td>mary@example.com</td>
</tr>
<tr class="info">
<td>Info</td>
<td>Dooley</td>
<td>july@example.com</td>
</tr>
<tr class="warning">
<td>Warning</td>
<td>Refs</td>
<td>bo@example.com</td>
</tr>
<tr class="active">
<td>Active</td>
<td>Activeson</td>
<td>act@example.com</td>
</tr>
</tbody>
</table>
</div>
</form>
</div>
<!--Print Button Start-->
<div class="form-group">
<label for="pwd">
<a href="#" class="btn btn-success btn-lg" onclick="PrintDiv()">
<span class="glyphicon glyphicon-print"></span>Print
</a>
</label>
</div>
<!--Print Button End-->
</form>
</body>
</html>

JavaScript function PrintDiv() will get content of divContent and will use its content to print.

Print Screen :

Scenario 1 : Simple Print Without Alignment

Scenario 2: Here I just Updated alignment of content and because of that print content comes in center of the page.

Print Output

 

 

 

ASP.Net Image Handler to retrieve Image from Database

While Creating and Saving Image in Database I was facing an issue of retrieving image from Database and then assign that  image into Gridview’s image control. To resolve this issue, I have implemented Image handler code.

I used below code to save image in database and then display it in Gridview using Http handler

Save Button Code (Save Image in Database)

 protected void btnSave_Click(object sender, EventArgs e)
    {
        try
        {
            
            Byte[] bytes = null;

            // Read the file and convert it to Byte Array
            string filePath = FileUpload1.PostedFile.FileName;
            string filename = Path.GetFileName(filePath);
            string ext = Path.GetExtension(filename);
            string contenttype = String.Empty;

            //Set the contenttype based on File Extension
            switch (ext)
            {                
                case ".jpg":
                    contenttype = "image/jpg";
                    break;
                case ".jpeg":
                    contenttype = "image/jpeg";
                    break;
                case ".png":
                    contenttype = "image/png";
                    break;
                case ".gif":
                    contenttype = "image/gif";
                    break;               
            }
            if (contenttype != String.Empty)
            {
                Stream fs = FileUpload1.PostedFile.InputStream;
                BinaryReader br = new BinaryReader(fs);
                bytes = br.ReadBytes((Int32)fs.Length);
            }
            else
            {
                lblMessage.ForeColor = System.Drawing.Color.Red;
                lblMessage.Text = "File format not recognised.Please Upload Valid File.";
            }

            //Database Connection 
            SqlConnection sqlserverconnection = new SqlConnection(strDBConnection);

            //SQL Database Connection Open
            sqlserverconnection.Open();

            string strQuery;

            strQuery = "sp_InsertEmployee";
			 
            SqlCommand command = new SqlCommand(strQuery, sqlserverconnection);

            command.CommandType = System.Data.CommandType.StoredProcedure;

            command.Parameters.AddWithValue("@EmployeeType", ddlEmployeeType.SelectedItem.Text.ToString());
            command.Parameters.AddWithValue("@FullName", txtFullName.Text.ToString());
            command.Parameters.AddWithValue("@Designation", txtDesignation.Text.ToString());
            command.Parameters.AddWithValue("@Department", ddlDepatment.SelectedItem.Value.ToString());
            command.Parameters.AddWithValue("@ContactNo", txtContactNo.Text.ToString());
            command.Parameters.AddWithValue("@Email", txtEmail.Text.ToString());
            string dob = String.Format("{0}", Request.Form["txtDOB"]);
            command.Parameters.AddWithValue("@DOB", dob);
            command.Parameters.AddWithValue("@Education", txtEducation.Text.ToString());
            command.Parameters.AddWithValue("@Address", txtAddress.Text.ToString());
            command.Parameters.AddWithValue("@ExpInYears", txtEXP.Text.ToString());
            command.Parameters.AddWithValue("@Username", txtUserName.Text.ToString());
            command.Parameters.AddWithValue("@Password", txtPassword.Text.ToString());
		    command.Parameters.AddWithValue("@Photo", bytes);

            command.ExecuteNonQuery();

            //SQL Connection Close
            sqlserverconnection.Close();

            lblMessage.Text = "Employee Information Added Successfully";
            lblMessage.ForeColor = System.Drawing.Color.Green;
            lblMessage.Font.Bold = true;

            ClearControl();

        }
        catch (Exception ex)
        {
            throw ex;
        }
    }

ViewEmployee Page is going to get all employee Detail and bind all information into Gridview.
Gridview contain Image tag which displays Employee Image.
GridView Image control Code:

<asp:Image ID="Image1" runat="server" ImageUrl='<%# "ImageHandler.ashx?id="+ Eval("EmployeeID") %>' Height="80px" Width="80px" />

Here ImageHandler.ashx is custom HTTP handler which is responsible to return employee Image as per EmployeeID
To add HTTP Handler right click project > Add New Item > Generic Handler > ImageHandler.ashx.
Code For ImageHandler.ashx

&lt;%@ WebHandler Language="C#" Class="ImageHandler" %&gt;

using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public class ImageHandler : IHttpHandler
{

    public void ProcessRequest(HttpContext ctx)
    {
        string id = ctx.Request.QueryString["id"];

        String strDBConnection = ConfigurationManager.AppSettings["DatabaseConnection"];

        SqlConnection sqlserverconnection = new SqlConnection(strDBConnection);
        SqlConnection con = new SqlConnection(strDBConnection);
        SqlCommand cmd = new SqlCommand("Select Photo From EmployeeMaster Where EmployeeID = @EmpID", con);
        cmd.CommandType = CommandType.Text;

        cmd.Parameters.AddWithValue("@EmpID", id);

        con.Open();
        byte[] pict = (byte[])cmd.ExecuteScalar();
        con.Close();

        ctx.Response.BinaryWrite(pict);
    }

    public bool IsReusable
    {
        get
        {
            return false;
        }
    }

}

 

 

Asp.net How to check Internet Connection’s availability using C# Code?

To check internet connection is available or not using C# Code use below code

		WebClient client = new WebClient();	
        byte[] datasize = null;
        try
        {
            datasize = client.DownloadData("http://www.google.com");
        }
        catch (Exception ex)
        {
        }
        if (datasize != null && datasize.Length > 0)
        {
            ClientScript.RegisterStartupScript(GetType(), "alert", "alert('Internet Connection Not Available.');", true);
        }
        else
        { 
            ClientScript.RegisterStartupScript(GetType(), "alert", "alert('.Internet Connection Not Available.');", true);
        }

Bootstrap Date Picker control with ASP.Net TextBox

To implement Bootstrap date picker control in Asp.Net sever side control implement below code


<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <!-- Boostrap CSS -->
    <link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.0.2/css/bootstrap.min.css" />
    <!-- Optional theme -->
    <link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.0.2/css/bootstrap-theme.min.css" />
    <!-- Jquery JS  -->
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.js"></script>
    <!-- Boostrap JS -->
    <script src="//netdna.bootstrapcdn.com/bootstrap/3.0.2/js/bootstrap.min.js"></script>
    <!-- Boostrap DatePicket CSS -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.6.4/css/bootstrap-datepicker.css" type="text/css" />
    <!-- Boostrap DatePciker JS  -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.6.4/js/bootstrap-datepicker.js" type="text/javascript"></script>
</head>
<body>
    <form id="form1" runat="server">
        <div>
            <asp:TextBox ID="txtStartDate" ClientIDMode="Static" runat="server" CssClass="m-wrap span12 date form_datetime"></asp:TextBox>
        </div>
    </form>
    <script type="text/javascript">
        $(document).ready(function () {
            var dp = $('#<%=txtStartDate.ClientID%>');
            dp.datepicker({
                changeMonth: true,
                changeYear: true,
                format: "dd.mm.yyyy",
                language: "tr"
            }).on('changeDate', function (ev) {
                $(this).blur();
                $(this).datepicker('hide');
            });
        });
    </script>
</body>
</html>

Output :

ASP.Net GridView/Repeater Date Format

To Format Date in GridView or Repeater ItemTemplate in dd-MM-yyyy or any other preferred format use below code

	<asp:Repeater runat="server" ID="rptContractType" OnItemCommand="rptContractType_ItemCommand">
                                    <ItemTemplate>
                                        <tr>
                                            <td style="text-align: center">                                           
                                                <asp:Label ID="lblNewsDate" runat="server"  Text='<%# Convert.ToDateTime(Eval("NewsDate")).ToString("dd-MM-yyyy") %>'></asp:Label>												
											</td>
										 </tr>
                                   </ItemTemplate>
                             </asp:Repeater>

Calling C# Function From JQuery

Sample Code to call C# function from JQuery

ASPX Page Code

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Login</title>
    
    <%--CSS & Script Start--%>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
    <%--CSS & Script End--%>

    <%--Jquery Call Start--%>
    <script type="text/javascript">

        function UserLogin() {

            var user = $('#username').val();
            var pass = $('#password').val();

            $.ajax({
                type: "POST",
                url: "Default.aspx/UserLogin",
                data: JSON.stringify({ username: user, password: pass }),
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: onSuccess,
                failure: function (AjaxResponse) {
                    alert("Failed: " + AjaxResponse.d);
                }
            });
            function onSuccess(AjaxResponse) {
                $("#Result").html("Output Result: " + AjaxResponse.d);
                alert(AjaxResponse.d);                
            }

            return false;

        }
    </script>
    <%--Jquery Call End--%>
</head>
<body>
    <%--Sample HTML Form Start--%>
    <h2>Login form</h2>
    <form id="form1" runat="server">
        <div>
            <div class="form-group">
                <label for="username">Username:</label>
                <input class="form-control" id="username" placeholder="Enter Username">
            </div>
            <div class="form-group">
                <label for="pwd">Password:</label>
                <input type="password" class="form-control" id="password" placeholder="Enter password">
            </div>
          
            <button type="submit" class="btn btn-default" onclick="return UserLogin()">Submit</button>
        </div>
        <%--Sample HTML Form End--%>
        <%--Result Div Start --%>
        <div id="Result" style="background-color:antiquewhite">
        </div>
        <%--Result Div End --%>
    </form>
</body> 
</html>

C# Code behind File

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    [System.Web.Services.WebMethod]
    public static string UserLogin(string username,string password)
    {
        return "You enter Username : " + username + "& Password :" + password;

    }
}

WCF Call Error : Access-Control-Allow-Origin Error and Cross Domain Header Issue

To Resolve JSON based WCF REST Service which gives below error and please follow below steps.

Add in Global.aspx

		protected void Application_BeginRequest()
        {
            if (Request.Headers.AllKeys.Contains("Origin") && Request.HttpMethod == "OPTIONS")
            {
                Response.Flush();
            }
        }

Add in Web.Config

  <httpProtocol>
      <customHeaders>
        <add name="Access-Control-Allow-Origin" value="*" />
        <add name="Access-Control-Allow-Headers" value="Origin, X-Requested-With, Content-Type, Accept,Authorization" />
        <add name="Access-Control-Allow-Methods" value="GET, POST, PUT, DELETE, OPTIONS" />
      </customHeaders>
    </httpProtocol>  

Ajax Call Function

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>

<script type="text/javascript">

        $(document).ready(function () {
            $.ajax({
                type: "POST",
                url: "http://localhost:1214/FB.svc/GetFaceBookPost",
                contentType: "application/json;charset=utf-8",
                dataType: "json",
                success: function (data) {
                    alert(data)
                },
                error: function (xhr) {
                    alert(xhr.responseText);
                }
            });
        });

</script>

How to Create WCF Application which accepts parameter in JSON format.

Below example and code shows How we can use WCF Service which accepts JSON as parameter inputs and performs insert operation with ADO.Net Entity Framework

In this sample example I am trying to add entry in StateMaster Table. For Insert operation StateMaster table required two parameters which is StateName and StateCode.

Below WCF Operation shows step by step process to create WCF Service and Databse insert operation.

Let’s begin with WCF Creation:

1.Create WCF Application from Visual Studio

I have created Application Named: WcfService

Visual Studio WCG Application

2. Now Create Method AddState in WCF interface

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;
using System.Web.Script.Services;

namespace WcfService
{
    // NOTE: You can use the "Rename" command on the "Refactor" menu to change the interface name "IMasterSVC" in both code and config file together.
    [ServiceContract]
    public interface IMasterSVC
    {      
        [WebInvoke(Method = "POST", RequestFormat = WebMessageFormat.Json, UriTemplate = "AddState", BodyStyle = WebMessageBodyStyle.Wrapped)]
        [OperationContract]
        bool AddState(Stream strInput);
    }
}

[WebInvoke(Method = “POST”, RequestFormat = WebMessageFormat.Json, UriTemplate = “AddState”, BodyStyle = WebMessageBodyStyle.Wrapped)]

Here We can see that this Method is using POST and UriTemplate = “AddState”

3. Create Method in WCF Class file

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Json;
using System.ServiceModel;
using System.Text;
using System.Web.Script.Serialization;

namespace WcfService
{
    // NOTE: You can use the "Rename" command on the "Refactor" menu to change the class name "MasterSVC" in code, svc and config file together.
    // NOTE: In order to launch WCF Test Client for testing this service, please select MasterSVC.svc or MasterSVC.svc.cs at the Solution Explorer and start debugging.
    public class MasterSVC : IMasterSVC
    {

        public bool AddState(Stream str)
        {
            bool result = false;

            try
            {
                if(str != null)
                {
                    //Get Parameter Key Value from JSON Formatted String 
                    string strJsonFormatString=  GetJSONPatameter(str);                                                            
                    
                    //Extract Paramter Value 
                    if (!string.IsNullOrEmpty(strJsonFormatString))
                    {
                        //Deseiralize JSON Format String Paramter from String
                        Dictionary<string, object> objJson = GetJSONObj(strJsonFormatString);

                        if (objJson != null)
                        {
                            string StateName = objJson["StateName"].ToString();
                            string StateCode = objJson["StateCode"].ToString();

                            BAL.ProjectEntitiesSQLConnStr context = new BAL.ProjectEntitiesSQLConnStr();

                            BAL.StateMaster objState = new BAL.StateMaster();

                            objState.StateCode = StateCode;
                            objState.StateName = StateName;

                            context.StateMasters.Add(objState);

                            context.SaveChanges();
                        }
                    }
                    result = true;
                }
            }
            catch (Exception ex)
            {
                result = false;

                throw ex;               
            }

            return result;
        }

        #region "JSON Related Methods"
        private string GetJSONPatameter(Stream str)
        {
            StreamReader strReader = new StreamReader(str);

            string strJsonFormatString = strReader.ReadToEnd();

            int startIndex = strJsonFormatString.IndexOf("[");
            int endIndex = strJsonFormatString.IndexOf("]");
            int length = endIndex - (startIndex + 1);

            if (startIndex > 0)
            {
                strJsonFormatString = strJsonFormatString.Substring(startIndex + 1, length);
            }

            return strJsonFormatString;
        }

        public static Dictionary<string, object> GetJSONObj(string jsonString)
        {
            Dictionary<string, object> userArr = new Dictionary<string, object>();
            try
            {
                JavaScriptSerializer objJS = new JavaScriptSerializer();
                object objStr = objJS.DeserializeObject(jsonString);

                userArr = (System.Collections.Generic.Dictionary<string, object>)objStr;

            }
            catch (Exception ex) { throw ex; }
            return userArr;
        }
         #endregion
     
    }
}

4. After Method Creation Lets add WCF Configuration values in web.config File

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <configSections>
    <!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
    <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
    <!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
  </configSections>
  <connectionStrings>
    <add name="ProjectEntitiesSQLConnStr" connectionString="metadata=res://*/ProjectEntities.csdl|res://*/ProjectEntities.ssdl|res://*/ProjectEntities.msl;provider=System.Data.SqlClient;provider connection string=&quot;data source=.;initial catalog=Project;user id=sa;password=admin@123;MultipleActiveResultSets=True;App=EntityFramework&quot;" providerName="System.Data.EntityClient" />
  </connectionStrings>
  <appSettings>
    <add key="aspnet:UseTaskFriendlySynchronizationContext" value="true" />
  </appSettings>
  <system.web>
    <compilation debug="true" targetFramework="4.6" />
    <httpRuntime targetFramework="4.6" />
  </system.web>
  <!-- Required Configuration For WCF JSON Start  -->
  <system.serviceModel>
    <behaviors>
      <endpointBehaviors>
        <behavior name="NonSoapInspector">
          <webHttp />
        </behavior>
      </endpointBehaviors>
      <serviceBehaviors>
        <behavior>
          <!-- To avoid disclosing metadata information, set the values below to false before deployment -->
          <serviceMetadata httpGetEnabled="true" httpsGetEnabled="true" />
          <!-- To receive exception details in faults for debugging purposes, set the value below to true.  Set to false before deployment to avoid disclosing exception information -->
          <serviceDebug includeExceptionDetailInFaults="false" />
        </behavior>
      </serviceBehaviors>
    </behaviors>
    <services>
      <service name="WcfService.MasterSVC">
        <endpoint address="" binding="webHttpBinding" contract="WcfService.IMasterSVC" behaviorConfiguration="NonSoapInspector" name="RESTEndpoint" />
      </service>
    </services>
    <protocolMapping>
      <add binding="basicHttpsBinding" scheme="https" />
    </protocolMapping>
    <serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" />
  </system.serviceModel>
  <!-- Required Configuration For WCF JSON END  -->
  <system.webServer>
    <modules runAllManagedModulesForAllRequests="true" />
    <!-- To browse web app root directory during debugging, set the value below to true. Set to false before deployment to avoid disclosing web app folder information. -->
    <directoryBrowse enabled="true" />
  </system.webServer>
  <!-- Required Configuration For WCF JSON End  -->
  <entityFramework>
    <defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
      <parameters>
        <parameter value="mssqllocaldb" />
      </parameters>
    </defaultConnectionFactory>
    <providers>
      <provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
    </providers>
  </entityFramework>
</configuration>

Please note that I am using reference of another project to use ADO.Net entity Framework

5. Now WCF is ready to take JSON Parameter Values

IE WCF Functionality

6. To check functionality I am using POSTER plugin in Firefox
7. First we need to prepare Parameter values for the Method: AddState
Sample JSON string

{
  "AddState": [
    {
      "StateName": "Gujarat",
      "StateCode": "GJ"
    }
  ]
}

8. Now we can upload our parameter values in POSTER add on

FireFox Addon Poster for WCF

9. Poster will return following response from Method

Poster Response

10. We can see that method has inserted new record in Database Table

Databse Record