Thursday, September 26, 2013

Encrypt Or Decrypt QueryString at Asp.net gridview Hyperlink using .net 3.5

Encrypt Or Decrypt QueryString at Asp.net gridview Hyperlink using .net 3.5

1.Include the namespace
using System.Text;
using System.Globalization;
using System.Security;
using System.Security.Cryptography;
using System.IO;

2.Add Hyperlink in template field of gridveiw

<asp:TemplateField HeaderText="Reference No." SortExpression="fullref">
                <ItemTemplate>      
                <asp:hyperlink
                runat="server"
                id="hyperlink1"
             
                text='<%# Eval("fullref") %>'>
                </asp:hyperlink>
                </ItemTemplate>
            <HeaderStyle BackColor="#660066" ForeColor="White"></HeaderStyle>
                </asp:TemplateField>  

3. Add the menthod to encrypt

 private byte[] key = { };
    private byte[] IV = { 0x12, 0x34, 0x56, 0x78, 0x90, 0xab, 0xcd, 0xef };
 public string Encrypt(string stringToEncrypt, string SEncryptionKey)
    {
        try
        {
            key = System.Text.Encoding.UTF8.GetBytes(SEncryptionKey);
            DESCryptoServiceProvider des = new DESCryptoServiceProvider();
            byte[] inputByteArray = Encoding.UTF8.GetBytes(stringToEncrypt);
            MemoryStream ms = new MemoryStream();
            CryptoStream cs = new CryptoStream(ms,
              des.CreateEncryptor(key, IV), CryptoStreamMode.Write);
            cs.Write(inputByteArray, 0, inputByteArray.Length);
            cs.FlushFinalBlock();
            return Convert.ToBase64String(ms.ToArray());
        }
        catch (Exception e)
        {
            return e.Message;
        }
    }


4.Use the follwing menthod to bind encrypted querystring on rowdatabaound event of gridveiw


  protected void GDVClientView_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        try
        {
            if (e.Row.RowType != DataControlRowType.DataRow) return;

            if (e.Row.DataItem == null) return;

            HyperLink hlobj = (HyperLink)e.Row.FindControl("hyperlink1") ;

            hlobj.NavigateUrl = String.Format("warrantdetailclient.aspx?fullref={0}",
                                                       Server.UrlEncode(Encrypt(hlobj.Text, "r0b1nr0y")));
        }
        catch (Exception ex)
        {
            //
        }

    }


5.Now on next page use the decript method as:
 protected void Page_Load(object sender, EventArgs e)
    {
 if (Request.Params["fullref"] != null)
        {
            string decrpval = Decrypt(Request.Params["fullref"].ToString(), "r0b1nr0y");
}
}

     private byte[] key = { };
    private byte[] IV = { 0x12, 0x34, 0x56, 0x78, 0x90, 0xab, 0xcd, 0xef };
    public string Decrypt(string stringToDecrypt, string sEncryptionKey)
    {
        byte[] inputByteArray = new byte[stringToDecrypt.Length + 1];
        try
        {
            key = System.Text.Encoding.UTF8.GetBytes(sEncryptionKey);
            DESCryptoServiceProvider des = new DESCryptoServiceProvider();
            inputByteArray = Convert.FromBase64String(stringToDecrypt);
            MemoryStream ms = new MemoryStream();
            CryptoStream cs = new CryptoStream(ms,
              des.CreateDecryptor(key, IV), CryptoStreamMode.Write);
            cs.Write(inputByteArray, 0, inputByteArray.Length);
            cs.FlushFinalBlock();
            System.Text.Encoding encoding = System.Text.Encoding.UTF8;
            return encoding.GetString(ms.ToArray());
        }
        catch (Exception e)
        {
            return e.Message;
        }
    }

Wednesday, September 25, 2013

Cannot resolve the collation conflict In LINQ

Cannot resolve the collation conflict IN LINQ Can be resolved using AsEnumerable() with Table Like as mention below



 DataClassesDataContext tdc = new DataClassesDataContext();

        var  warid = (from id in tdc.SP_Cases.AsEnumerable()
                      join defe in tdc.Defendant_Masters.AsEnumerable() on id.WarrantID   equals defe.WarrantID
                      join defAd in tdc.Defendant_Addresses.AsEnumerable() on defe.CID equals defAd.Def_Id
                     where id.WarrantID == "SPC1080"
                     select new { id.WarrantID, id.JudgCost, id.EntryDate,defe.DefendantName,defAd.Add1 }).FirstOrDefault();

        if (warid != null)
        {
            Label1.Text = warid.WarrantID;
            Label2.Text = warid.JudgCost.ToString();
            Label3.Text = warid.DefendantName;
            Label4.Text = warid.Add1;
        }

Tuesday, September 24, 2013

Error executing child request for ChartImg.axd

While working working with MS Chart control in .net 3.5,i am getting following error :
"Error executing child request for ChartImg.axd " and it is solved by following steps:

Add in webconfig 

1.Add chart image saving folder name as
<appSettings>
 <add key="ChartImageHandler" value="storage=file;timeout=20;dir=C:\TempImageFiles\;" /></appSettings>

2. add http handler as:

<httpHandlers>
  <add path="ChartImg.axd" verb="GET,HEAD" type="System.Web.UI.DataVisualization.Charting.ChartHttpHandler, System.Web.DataVisualization, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" validate="false" />
</httpHandlers>

3.Add Handler as

<handlers>
  <add name="ChartImageHandler" preCondition="integratedMode" verb="GET,HEAD,POST" path="ChartImg.axd" type="System.Web.UI.DataVisualization.Charting.ChartHttpHandler, System.Web.DataVisualization, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />
</handlers>


4.Make sure you need to add Chart Image save location(ImageLocation) tag in Chart control as:

 <asp:Chart ID="Chart2" runat="server"  Height="536px" Width="680px" ImageStorageMode="UseImageLocation" ImageLocation="TempImageFiles/ChartPic_#SEQ(300,3)" EnableViewState="true">
                        <Titles>
                        <asp:Title Name="Title1" Text="Enforceble Pie" 
                        Alignment="TopCenter" Font="Verdana, 12pt, style=Bold" ForeColor="Purple">
                        </asp:Title>
                        </Titles>
                        <Series>
                        <asp:Series Name="Series1" ChartType="Pie" CustomProperties="PieLabelStyle=outside, CollectedThresholdUsePercent=False, PieLineColor=Purple" Legend="Legend1"   >
                        </asp:Series>

                        </Series>
                        <Legends>
                        <asp:Legend Name="Legend1" BackImageAlignment="Bottom" Docking="Bottom" 
                                Font="Verdana, 7.25pt" IsTextAutoFit="False"  >
                        </asp:Legend>

                        </Legends>
                        <ChartAreas>
                        <asp:ChartArea Name="ChartArea1" >
                        </asp:ChartArea>
                        </ChartAreas>
                        </asp:Chart>
            












Thursday, September 19, 2013

How to pass logon information to reportdocument object to export in pdf from crystal report in sqlsever2005/2008 and Sql Aure



 logon information to reportdocument object in sqlsever2005/2008




ReportDocument repDoc = new ReportDocument();
   repDoc.Load(repFilePath);

// This is for  logon information to reportdocument object in sqlsever2005/2008
 repDoc.SetDataSource(getCustomerData(clientid));
  repDoc.SetDatabaseLogon("userid", "Password", "Sever Name", "Database name");
  repDoc.SetParameterValue(0, clientid);

//  logon information to reportdocument object in Sql Azure

repDoc.SetDataSource(getCustomerData(clientid));
  repDoc.DataSourceConnections[0].SetConnection("ServerName", "database Name", "User ID", "Password");
   repDoc.DataSourceConnections[0].SetLogon("User id", "Password");
                 
   repDoc.SetParameterValue(0, clientid);


 // Stop buffering the response
                    Console.Clear();
                 
                    ExportOptions CrExportOptions;

                    DiskFileDestinationOptions CrDiskFileDestinationOptions = new DiskFileDestinationOptions();
                    PdfRtfWordFormatOptions CrFormatTypeOptions = new PdfRtfWordFormatOptions();
                    CrDiskFileDestinationOptions.DiskFileName =  filePathName + ".pdf";
                    CrExportOptions = repDoc.ExportOptions;
                    {
                        CrExportOptions.ExportDestinationType = ExportDestinationType.DiskFile;
                        CrExportOptions.ExportFormatType = ExportFormatType.PortableDocFormat;
                        CrExportOptions.DestinationOptions = CrDiskFileDestinationOptions;
                        CrExportOptions.FormatOptions = CrFormatTypeOptions;

                    }
                    repDoc.Export();



        // Business layer class to get the data from database
        private DataSet getCustomerData(string clientid)
        {

            SqlConnection con = new SqlConnection(ConfigurationSettings.AppSettings["SherpaSQLConnString"].ToString());
            SqlCommand cmd = new SqlCommand("ClientMIPage1", con);
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.Parameters.Add(new SqlParameter("@cclientid", SqlDbType.VarChar, 36));
            cmd.Parameters[0].Value = clientid;
            DataSet ds = new DataSet();
            SqlDataAdapter da = new SqlDataAdapter();
            da.SelectCommand = cmd;
            da.Fill(ds);
            return ds;

        }