Thursday, August 23, 2018

How to get IP Address of Visitors Machine in ASP.Net

How to get IP Address of Visitors Machine in ASP.Net


First the IP Address is determined for the Client machine’s which are behind Routers or Proxy Servers and hence the HTTP_X_FORWARDED_FOR server variable is checked.


NoteWhen the Client machine is behind a Proxy Server its IP Address of the Proxy Server is appended to the Client machine’s IP Address. If there are multiple Proxy Servers then the IP Addresses of all the Proxy Servers are appended to the client machine IP Address.
 
If the IP Address is not found in the HTTP_X_FORWARDED_FOR server variable, it means that it is not using any Proxy Server and hence the IP Address is now checked in the REMOTE_ADDR server variable.
NoteWhile running this application on your machine locally i.e. in Visual Studio, the IP Address will show as 127.0.0.1 or ::1. This happens because in such case the Client and Server both are the same machine. Thus no need to worry when you deploy it on a Server, you will see the results.
 

string ipaddress;
ipaddress = Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
if (ipaddress == "" || ipaddress == null)
    ipaddress = Request.ServerVariables["REMOTE_ADDR"];


if (ipaddress == "xxx.xxx.x.xxx") // Enter your IP
   {
      lblMsg.Text = "You are not authorized to login into the system.";
   }

Tuesday, June 19, 2018

Message send to Web Application to Desktop Application using SignalR

Sample Application

Let us build a sample chat application that broadcasts the messages to all connected clients or to particular groups. In this example consider the clients to be a Windows application and a web form client.

Creating an Asp.Net SignalR Hub

Open Visual Studio and create an empty Asp.net MVC application named MyChatApplicationServer. Now open the NuGet packages, search and include Microsoft ASP.NET SignalR and Microsoft.Owin.Cors.
Now right click on the project, add the SignalR Hub class and name it as MyChatHub.  Add the following code to the class.



The HUB class also provides the properties Clients, Groups, Context and events like OnConnected, etc.
Finally you should also add Owin startup class to map the available hubs as shown below.

Pushing Data to a Web Form Client

Now create a web form client project named WebClient and add a simple HTML file ChatWebClient.html with the following code. Add the references to the required script files.

There are two ways of implementing the client function one with proxy and other without. The above example is the one without a proxy.
In the connection start you may also mention which transport SignalR should use.

Pushing Data to a Windows Application Client

Let us add a windows app and subscribe to the SignalR host. Create a new windows application named WinFormClient and from the nugget packages install Microsoft ASP.NET SignalR .NET client package. In the Program.cs add the following code.

Once done go ahead and run both the web and Windows client. Enter the messages and look at how the message is getting pushed across both the clients though they are of a different nature. Fig 2.0 shows a sample screenshot.


Tuesday, May 30, 2017

Export rdlc file into PDF with Images

Export rdlc file into PDF with Images

private void CreatePDF(int ApplicantId)
    {

        //MyDataSetTableAdapters.YourTableAdapterHere ds = new MyDataSetTableAdapters.YourTableAdapterHere();
        Applicant objApp = new Applicant();
        DataSet dsApplicant = objApp.GetApplicantByID(ApplicantId);
        // Create Report DataSource
        ReportDataSource rds = new ReportDataSource("DataSet1", dsApplicant.Tables[0]);

        // Variables
        Warning[] warnings;
        string[] streamIds;
        string mimeType = string.Empty;
        string encoding = string.Empty;
        string extension = string.Empty;

        // Setup the report viewer object and get the array of bytes
        ReportViewer viewer = new ReportViewer();
        viewer.ProcessingMode = ProcessingMode.Local;
        viewer.LocalReport.ReportPath = Server.MapPath("") + @"\Report\EmployeeW4.rdlc";

        viewer.LocalReport.EnableExternalImages = true;

        string imagePath = new Uri(Server.MapPath("") + @"\Temp\" + dsApplicant.Tables[0].Rows[0]["SignatureImage"].ToString() + ".png").AbsoluteUri;
        ReportParameter parameter = new ReportParameter("Path", imagePath);
        viewer.LocalReport.SetParameters(parameter);
        viewer.LocalReport.Refresh();

        viewer.LocalReport.DataSources.Add(rds); // Add datasource here

        byte[] bytes = viewer.LocalReport.Render("PDF", null, out mimeType, out encoding, out extension, out streamIds, out warnings);
        string fileName = "";
        if (dsApplicant.Tables[0].Rows.Count > 0)
            fileName = dsApplicant.Tables[0].Rows[0]["FirstName"].ToString() + "_" + ApplicantId;
        //Now that you have all the bytes representing the PDF report, buffer it and send it to the client.

        string path = Server.MapPath("") + (@"\W4Form\" + DateTime.Now.ToString("yyyy-MMM-dd"));
        if (!Directory.Exists(path))
        {
            DirectoryInfo di = Directory.CreateDirectory(path);

        }
        using (FileStream stream = new FileStream((path + "/" + fileName + ".pdf"), FileMode.Create))
        {
            stream.Write(bytes, 0, bytes.Length);
        }
    }



Download folder file into Zip 

 string path = Server.MapPath("") + @"\W4Form\" + DateTime.Now.ToString("yyyy-MMM-dd") + @"\";//Location for inside Test Folder
        string[] Filenames = Directory.GetFiles(path);
        using (ZipFile zip = new ZipFile())
        {
            zip.AddFiles(Filenames, "Project");//Zip file inside filename
            //zip.Save(@"D:\Projectzip.zip");//location and name for creating zip file
            Response.Clear();
            Response.BufferOutput = false;
            string zipName = String.Format("Zip_{0}.zip", DateTime.Now.ToString("yyyy-MMM-dd-HHmmss"));
            Response.ContentType = "application/zip";
            Response.AddHeader("content-disposition", "attachment; filename=" + zipName);
            zip.Save(Response.OutputStream);
            Response.End();
        }
        System.Web.UI.ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "AlertBox", "alert('File has been download successfully.')", true);

How to show Checkbox in RDLC report

How to show Checkbox in RDLC report

It is very simple. following these step

Step 1 
(change the textbox’s font to Wingdings2)

Step 2
Put the condition on Textbox expression - 

=IIf( Fields!MyBooleanField.Value, Chr(82), Chr(163))



Tuesday, January 24, 2017

How to export crystal report into pdf file without using CrystalReportViewer

Step 1 : Create a crystal report























Step 2 : Create a new empty web site 
Step 3 : Create a new page

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" Theme="Silver" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
  </head>
<body>
    <form id="form1" runat="server">
        <br />
        <div class="content-center">
            <table>
                <tr>
                    <td>EmployeeID :</td>
                    <td>
                        <asp:TextBox ID="txtEmployeeID" runat="server"></asp:TextBox>
                    </td>
                </tr>
                <tr>
                    <td>Year :
                    </td>
                    <td>
                        <asp:DropDownList ID="ddlYear" runat="server">
                            <asp:ListItem Value="0" Text="2017"></asp:ListItem>
                            <asp:ListItem Value="1" Text="2016"></asp:ListItem>
                        </asp:DropDownList>
                    </td>
                </tr>
                <tr>
                    <td></td>
                    <td>
                        <asp:Button ID="btnSearch" runat="server" Style="background-color: gray;" Text="Search" OnClick="btnSearch_Click" />
                    </td>
                </tr>
            </table>

        </div>
        <div class="gridbox">

            <asp:GridView ID="grd1" runat="server" AutoGenerateColumns="false">
                <EmptyDataTemplate>
                    <div class="Warning" style="text-align: center;">
                        No Records found.
                    </div>
                </EmptyDataTemplate>
                <Columns>
                    <asp:TemplateField HeaderText="View">
                        <ItemTemplate>
                            <asp:LinkButton ID="lblbtnView" runat="server" Text="View" OnClick="lblbtnView_Click" CommandArgument='<%#Eval("clock") %>'></asp:LinkButton>
                            <asp:HiddenField ID="hdnTrans" runat="server" Value='<%# Eval("Trans") %>' />
                            <asp:HiddenField ID="hdncheckDate" runat="server" Value='<%# Eval("checkDate") %>' />
                            <asp:HiddenField ID="hdnCompanyId" runat="server" Value='<%# Eval("co") %>' />
                        </ItemTemplate>
                    </asp:TemplateField>
                    <asp:TemplateField HeaderText="Download">
                        <ItemTemplate>
                            <asp:LinkButton ID="lblbtnDownload" runat="server" Text="Download" OnClick="lblbtnDownload_Click"  CommandArgument='<%#Eval("clock") %>'></asp:LinkButton>
                        </ItemTemplate>
                    </asp:TemplateField>
                    <asp:BoundField HeaderText="Check Date" DataField="checkDate" DataFormatString="{0:MM/dd/yyyy}" />
                    <asp:BoundField HeaderText="Pay Type" DataField="checkAttributes" />
                    <asp:BoundField HeaderText="Hours" DataField="hours" />
                    <asp:BoundField HeaderText="Gross" DataField="gross" />
                    <asp:BoundField HeaderText="Dir Dep" DataField="dirDepAmount" />
                    <asp:BoundField HeaderText="Net Pay" DataField="netCheck" />
                    <asp:BoundField HeaderText="Check / Voucher #" DataField="Check/Voucher" />
                </Columns>
            </asp:GridView>

        </div>
    </form>
</body>
</html>

Step 4 : Write this code on page .cs file

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using CrystalDecisions.CrystalReports.Engine;

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

    }

    public DataTable GetData(string EmployeeID, string CompanyID, int year)
    {
        SQL objSQL = new SQL();
        objSQL.AddParameter("@Clock", DbType.String, ParameterDirection.Input, 0, EmployeeID);
        //objSQL.AddParameter("@Co", DbType.String, ParameterDirection.Input, 0, CompanyID);
        objSQL.AddParameter("@year", DbType.Int32, ParameterDirection.Input, 0, year);
        return objSQL.ExecuteDataSet("p_GetDataByClock").Tables[0];
    }

    protected void btnSearch_Click(object sender, EventArgs e)
    {
        grd1.DataSource = GetData(txtEmployeeID.Text, "", Convert.ToInt32(ddlYear.SelectedItem.Text));//GetData("999269", "16504",2016);
        grd1.DataBind();
    }
    protected void lblbtnView_Click(object sender, EventArgs e)
    {
        int empid = Convert.ToInt32(((LinkButton)(sender)).CommandArgument);
        HiddenField hdnTrans = (HiddenField)(((LinkButton)(sender)).FindControl("hdnTrans"));
        HiddenField hdncheckDate = (HiddenField)(((LinkButton)(sender)).FindControl("hdncheckDate"));
        HiddenField hdnCompanyId = (HiddenField)(((LinkButton)(sender)).FindControl("hdnCompanyId"));
        Response.Redirect("report.aspx?EmpId=" + empid + "&Trans=" + hdnTrans.Value + "&CheckDate=" + hdncheckDate.Value + "&ComId=" + hdnCompanyId.Value);
    }
    //ReportDocument rprt;
    protected void lblbtnDownload_Click(object sender, EventArgs e)
    {
        //CrystalReport1 objReport = new CrystalReport1();
        int empid = Convert.ToInt32(((LinkButton)(sender)).CommandArgument);
        HiddenField hdnTrans = (HiddenField)(((LinkButton)(sender)).FindControl("hdnTrans"));
        HiddenField hdncheckDate = (HiddenField)(((LinkButton)(sender)).FindControl("hdncheckDate"));
        HiddenField hdnCompanyId = (HiddenField)(((LinkButton)(sender)).FindControl("hdnCompanyId"));

        ReportDocument rprt = new ReportDocument();
        rprt.Load(Server.MapPath("~/CP_PS_Custom_Stock.rpt"));
        rprt.SetDatabaseLogon("sa", "$QL$erver1");
        rprt.SetParameterValue("ClockNo", empid.ToString());
        rprt.SetParameterValue("CheckDate", hdncheckDate.Value);
        rprt.SetParameterValue("TransactionNo", hdnTrans.Value);
        rprt.SetParameterValue("Company", hdnCompanyId.Value);
        
        Response.Buffer = false;
        Response.ClearContent();
        Response.ClearHeaders();
        rprt.ExportToHttpResponse(ExportFormatType.PortableDocFormat, Response, true, "EmployeeInformation");
        Response.End();  

    }
}

Note : Add two reference in you project 
1. CrystalDecisions.CrystalReports.Engine
2. CrystalDecisions.Shared

Output:











click on download link





















How to passed multiple parameters into crystal report in ASP.net

Step 1 : Create a crystal report with parametes
Step 2: Create a new page with CrystalReportViewer

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="report.aspx.cs" Inherits="report" %>
<%@ Register Assembly="CrystalDecisions.Web, Version=10.5.3700.0, Culture=neutral, PublicKeyToken=692fbea5521e1304" Namespace="CrystalDecisions.Web" TagPrefix="CR" %>
<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <CR:CrystalReportViewer ID="CrystalReportViewer1" runat="server" AutoDataBind="True" Height="1039px" Width="901px" />
    </div>
    </form>
</body>
</html>

step 3 : write this code

using CrystalDecisions.CrystalReports.Engine;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class report : System.Web.UI.Page
{
    ReportDocument rprt = new ReportDocument();
    protected void Page_Load(object sender, EventArgs e)
    {
        rprt.Load(Server.MapPath("~/CP_PS_Custom_Stock.rpt"));
        rprt.SetDatabaseLogon("sa", "$QL$erver1");
        rprt.SetParameterValue("ClockNo", Request.QueryString["EmpId"].ToString());
        rprt.SetParameterValue("CheckDate", Request.QueryString["CheckDate"].ToString());
        rprt.SetParameterValue("TransactionNo", Request.QueryString["Trans"].ToString());
        rprt.SetParameterValue("Company", Request.QueryString["ComId"].ToString());
        //rprt.SetDataSource(GetData("999269", "16504", 2017));
        CrystalReportViewer1.ReportSource = rprt;
    }
 
}