Thursday 14 November 2013

Create a chart using Chart Control of .NET

We need to create chart so many times in the project. I am using chart control of .NET.

Add the chart control from the toolbox just drag and drop in the aspx page it will create following code.

<asp:Chart ID="chtReport" runat="server" Height="500" Width="500">
 <Series>
  <asp:Series Name="Series1" XValueType="Auto" YValueType="Int32">
  </asp:Series>
 </Series>
 <ChartAreas>
  <asp:ChartArea Name="ChartArea1">
   <AxisX Interval="1">
   </AxisX>
  </asp:ChartArea>
 </ChartAreas>
</asp:Chart>


Now feed the data to chart control at the code behind in any event in which you like to bind

List<SPTopTenStudents_Result> ListStudents;
 ListStudents = dbContext.SPTopTenStudents().ToList();
 if (ListStudents != null && ListStudents.Count() > 0)
 {
  Series objseries = new Series();
  foreach (var item in ListStudents)
  {
   objseries.ChartType = SeriesChartType.Column;
   objseries.YValueType = ChartValueType.Int32;
   DataPoint objDS = new DataPoint();
   objDS.SetValueXY(item.Model, item.RequestCount);
   objseries.Points.Add(objDS);
  }
  chtReport.Series["Series1"] = objseries;
  chtReport.DataBind();
 }


when you add chart control it will also create chart handler at web.config file like following.

<appSettings>
<add key="ChartImageHandler" value="Storage=file;Timeout=20;Url=~/Images/;" />
</appSettings>

so create the Images folder if you don't have already in the project.

Export Gridview to PDF

Sometimes we need to export the gridview as pdf. I am using iTextShart to export the gridview to PDF.
Click Here to download iTextSharp.

First add attribute
EnableEventValidation="false"
 to your @Page directive in aspx page.


Second add the following method to your code behind page.

public override void VerifyRenderingInServerForm(Control control)
        {
            /* Verifies that the control is rendered */
        }


Third now add the following code on your Export button click.

                Response.ContentType = "application/pdf";
                Response.AddHeader("content-disposition", "attachment;filename=InstituteReport.pdf");
                Response.Cache.SetCacheability(HttpCacheability.NoCache);
                StringWriter sw = new StringWriter();
                HtmlTextWriter hw1 = new HtmlTextWriter(sw);
                Label lblHead = new Label();
                lblHead.Text = "<img src='" + Server.MapPath("~/images/logo.png") + "' height='25'
                width='75'></img>
                &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                lblHead.RenderControl(hw1);
                HtmlTextWriter hw2 = new HtmlTextWriter(sw);
                Label lblBr = new Label();
                lblBr.Text = "report";
                lblBr.ForeColor = System.Drawing.Color.White;
                lblBr.RenderControl(hw2);
                HtmlTextWriter hw = new HtmlTextWriter(sw);
                GvInstitute.AllowPaging = false;
                GvInstitute.AllowSorting = false;
                GvInstitute.GridLines = GridLines.Both;
                GvInstitute.HeaderRow.Style.Add("font-size", "10px");
                GvInstitute.Style.Add("text-decoration", "none");
                GvInstitute.Style.Add("font-family", "Arial, Helvetica, sans-serif;");
                GvInstitute.Style.Add("font-size", "8px");
                GvInstitute.Columns[0].ItemStyle.Width = Unit.Pixel(10);
                GvInstitute.Columns[0].HeaderStyle.Width = Unit.Pixel(10);
                BindInstitutes(); // To bind the data to Gridview
                GvInstitute.RenderControl(hw);
                StringReader sr = new StringReader(sw.ToString());
                Document pdfDoc = new Document(PageSize.A4, 7f, 7f, 7f, 0f);
                HTMLWorker htmlparser = new HTMLWorker(pdfDoc);
                PdfWriter.GetInstance(pdfDoc, Response.OutputStream);
                pdfDoc.Open();
                htmlparser.Parse(sr);
                pdfDoc.Close();
                Response.Write(pdfDoc);
                Response.End();


 

Export Data to Excel in ASP.NET C#

I am using third party tool to export data to excel. The third party tool is EPPlus. Click here to download the dll and add refference to your porject.

Now you can add the following code to your button click of Export to Excel.

List<Institutes> ExportData = new List<Institutes>();
  ExportData = objReport.GetInstitutesData();

  using (ExcelPackage pck = new ExcelPackage())
  {
   ExcelWorksheet ws = pck.Workbook.Worksheets.Add("Institute Report");
   ws.Cells["A2"].LoadFromCollection(ExportData, true);
   ws.Cells["A1"].Value = "Institute Report";
   Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
   Response.AddHeader("content-disposition", "attachment;  filename=InstituteReport.xlsx");
   Response.BinaryWrite(pck.GetAsByteArray());
   Response.End();
  }
 

Saturday 9 November 2013

Common Functions of C#

Common required functions of C#

To Convert Date to String and vice e versa.

public static string ToDate2String(DateTime dt)
    {
        string DateFormat = "MM/dd/yyyy";
        return dt.ToString(DateFormat);
    }
public static DateTime ToString2Date(string dt)
    {
        string DateFormat = "MM/dd/yyyy";
        return DateTime.ParseExact(dt, DateFormat, CultureInfo.InvariantCulture);
    }



To Convert List to DataTable

public static DataTable ListToDataTable<T>(IEnumerable<T> list)
    {
        DataTable table = new DataTable();
        if (list != null)
        {
            PropertyDescriptorCollection properties =
                TypeDescriptor.GetProperties(typeof(T));
            foreach (PropertyDescriptor prop in properties)
                table.Columns.Add(
                    prop.Name,
                    (prop.PropertyType.IsGenericType &&
                     prop.PropertyType.GetGenericTypeDefinition() == typeof(Nullable<>))
                        ? Nullable.GetUnderlyingType(prop.PropertyType)
                        : prop.PropertyType
                    );
            foreach (T item in list)
            {
                DataRow row = table.NewRow();
                foreach (PropertyDescriptor prop in properties)
                    row[prop.Name] = prop.GetValue(item) ?? DBNull.Value;
                table.Rows.Add(row);
            }
        }
        return table;
    }



To Write the Error of the Project.

    public static void WriteError(Exception ex)
    {
        string err = null;
        try
        {
            string path = "~/ErrorLogs/" + DateTime.Today.ToString("dd-MMM-yy") + ".txt";
            if (!File.Exists(HttpContext.Current.Server.MapPath(path)))
                File.Create(HttpContext.Current.Server.MapPath(path)).Close();
            using (StreamWriter w = File.AppendText(HttpContext.Current.Server.MapPath(path)))
            {
                System.Diagnostics.StackTrace trace = new System.Diagnostics.StackTrace(ex, true);
                w.WriteLine("\r\nLog Entry : ");
                w.WriteLine("{0}", DateTime.Now.ToString(CultureInfo.InvariantCulture));
                err = "Error in: " + HttpContext.Current.Request.Url.ToString() + Environment.NewLine +
                           "File Name : " + trace.GetFrame(0).GetFileName() + Environment.NewLine +
                           "Line : " + trace.GetFrame(0).GetFileLineNumber() + Environment.NewLine +
                           "Column: " + trace.GetFrame(0).GetFileColumnNumber() + Environment.NewLine +
                           "Error Message:" + ex.Message + Environment.NewLine +
                           "TargetSite:" + ex.TargetSite.ToString();
                w.WriteLine(err);
                w.WriteLine("__________________________");
                w.Flush();
                w.Close();
            }
        }
        catch (Exception exc)
        {
            WriteError(exc);
        }
    }

CCS Server API (To Get, Post, Put & Delete the data on the server)

To access api you need to create get, post, put or delete requests so we can create requests like the following codes.

 <appSettings>
    <add key="CCSAPIURL" value="https://265.105.115.68:9303/" />
    <add key="CCSAPIUsername" value="admin" />
    <add key="CCSAPIPassword" value="admin" />
 </appSettings>

protected void lnkbtnSave_Click(object sender, EventArgs e)
        {
   ServerOperations serverapi = new ServerOperations();
            string LoginID = txtLoginID.Text;
            string Password = txtLoginPassword.Text;
            string Email = txtEmail.Text;
 
   string Data = "groupName=bluevoip.com&userName=" + LoginID + "&password=" + Password + "&profileName=mobile_sip";
            serverapi.PostUserDetails(Data, "ccs/user");
            string data = "userName=" + LoginID + "&attributeName=account.notification._userEmailAddress&attributeValue=" + Email;
            serverapi.PostUserDetails(data, "ccs/user/attribute");  
  }

public class ServerOperations
    {
        string URL = Convert.ToString(ConfigurationManager.AppSettings["CCSAPIURL"]);
        string UserName = Convert.ToString(ConfigurationManager.AppSettings["CCSAPIUsername"]);
        string Password = Convert.ToString(ConfigurationManager.AppSettings["CCSAPIPassword"]);
        /// <summary>
        /// For Secure server certify
        /// </summary>
        public static void InitiateSSLTrust()
        {
            try
            {
                //Change SSL checks so that all checks pass
                ServicePointManager.ServerCertificateValidationCallback =
                    new RemoteCertificateValidationCallback(
                        delegate
                        { return true; }
                    );
            }
            catch (Exception)
            {
            }
        }
        /// <summary>
        /// Get the User Details from the CCS
        /// </summary>
        public void GetUserDetails()
        {
            try
            {
                InitiateSSLTrust();               
                string url = "https://265.105.115.68:9303/ccs/user?userName=test@test.com";
                WebRequest myReq = WebRequest.Create(url);
                string username = "developer1";
                string password = "D3v3l0p3r";
                string usernamePassword = username + ":" + password;
                CredentialCache mycache = new CredentialCache();
                mycache.Add(new Uri(url), "Digest", new NetworkCredential(username, password));
                myReq.Credentials = mycache;
                myReq.Headers.Add("Authorization", "Digest " + Convert.ToBase64String(new ASCIIEncoding().GetBytes(usernamePassword)));
                WebResponse wr = myReq.GetResponse();
                Stream receiveStream = wr.GetResponseStream();
                StreamReader reader = new StreamReader(receiveStream, Encoding.UTF8);
                string content = reader.ReadToEnd();
                //txtResponse.Text = "Response : " + content;
            }
            catch (WebException ex)
            {
            }
        }
        /// <summary>
        /// Post Userdata to the server
        /// </summary>
        /// <param name="Data"></param>
        /// <param name="AppendURL"></param>
        public void PostUserDetails(string Data, string AppendURL)
        {
            try
            {              
                InitiateSSLTrust();
                string url = URL + AppendURL;
                string data = Data;
                WebRequest myReq = WebRequest.Create(url);
                myReq.Method = "POST";
                byte[] bytes = Encoding.UTF8.GetBytes(data);
                myReq.ContentLength = bytes.Length;
                myReq.ContentType = "application/x-www-form-urlencoded";
                string username = UserName;
                string password = Password;
                string usernamePassword = username + ":" + password;
                CredentialCache mycache = new CredentialCache();
                mycache.Add(new Uri(url), "Digest", new NetworkCredential(username, password));
                myReq.Credentials = mycache;
                myReq.Headers.Add("Authorization", "Digest " + Convert.ToBase64String(new ASCIIEncoding().GetBytes(usernamePassword)));
                using (var requestStream = myReq.GetRequestStream())
                {
                    requestStream.Write(bytes, 0, bytes.Length);
                    requestStream.Close();
                }
                WebResponse wr = myReq.GetResponse();
                Stream receiveStream = wr.GetResponseStream();
                StreamReader reader = new StreamReader(receiveStream, Encoding.UTF8);
                string content = reader.ReadToEnd();
            }
            catch (WebException ex)
            {               
            }
        }
        /// <summary>
        /// Modify Userdate on the server
        /// </summary>
        /// <param name="data"></param>
        /// <param name="AppendURL"></param>
        public void PUTUserDetails(string data, string AppendURL)
        {
            try
            {
                InitiateSSLTrust();
                string url = URL + AppendURL;
                WebRequest myReq = WebRequest.Create(url);               
                myReq.Method = "PUT";
                byte[] bytes = Encoding.UTF8.GetBytes(data);
                myReq.ContentLength = bytes.Length;
                myReq.ContentType = "application/x-www-form-urlencoded";
                string username = "developer1";
                string password = "D3v3l0p3r";
                string usernamePassword = username + ":" + password;
                CredentialCache mycache = new CredentialCache();
                mycache.Add(new Uri(url), "Digest", new NetworkCredential(username, password));
                myReq.Credentials = mycache;
                myReq.Headers.Add("Authorization", "Digest " + Convert.ToBase64String(new ASCIIEncoding().GetBytes(usernamePassword)));
                using (var requestStream = myReq.GetRequestStream())
                {
                    requestStream.Write(bytes, 0, bytes.Length);
                    requestStream.Close();
                }
                WebResponse wr = myReq.GetResponse();
                Stream receiveStream = wr.GetResponseStream();
                StreamReader reader = new StreamReader(receiveStream, Encoding.UTF8);
                string content = reader.ReadToEnd();               
            }
            catch (WebException ex)
            {               
            }
        }
        /// <summary>
        /// Delete the user from the server
        /// </summary>
        /// <param name="Data"></param>
        /// <param name="AppendURL"></param>
        public void DeleteUserDetails(string Data, string AppendURL)
        {
            try
            {
                InitiateSSLTrust();
                string url = URL + AppendURL;
                string data = Data;
                WebRequest myReq = WebRequest.Create(url);
                myReq.Method = "DELETE";
                byte[] bytes = Encoding.UTF8.GetBytes(data);
                myReq.ContentLength = bytes.Length;
                myReq.ContentType = "application/x-www-form-urlencoded";
                string username = UserName;
                string password = Password;
                string usernamePassword = username + ":" + password;
                CredentialCache mycache = new CredentialCache();
                mycache.Add(new Uri(url), "Digest", new NetworkCredential(username, password));
                myReq.Credentials = mycache;
                myReq.Headers.Add("Authorization", "Digest " + Convert.ToBase64String(new ASCIIEncoding().GetBytes(usernamePassword)));
                using (var requestStream = myReq.GetRequestStream())
                {
                    requestStream.Write(bytes, 0, bytes.Length);
                    requestStream.Close();
                }
                WebResponse wr = myReq.GetResponse();
                Stream receiveStream = wr.GetResponseStream();
                StreamReader reader = new StreamReader(receiveStream, Encoding.UTF8);
                string content = reader.ReadToEnd();
            }
            catch (WebException ex)
            {
            }
        }       
    }