Saturday 30 June 2012

Method To Create The PDF File From GridView In Asp.net


  protected void ExportToPDF(GridView gvuser, string fileName, bool isLastColVisible, bool isLogo)
        {
            if (gvuser == null)
                return;
            if (string.IsNullOrEmpty(fileName))
                fileName = "Bucco.pdf";
            gvuser = PrepareGridViewForExport(gvuser);
            Response.ContentType = "application/pdf";

            Response.AddHeader("content-disposition", "attachment;filename=" + fileName);
            Response.Cache.SetCacheability(HttpCacheability.NoCache);
            StringWriter sw = new StringWriter();
            HtmlTextWriter hw = new HtmlTextWriter(sw);
            HtmlForm frm = new HtmlForm();

            if (!isLastColVisible)
                gvuser.Columns[gvuser.Columns.Count - 1].Visible = false;

            //gvuser.RowStyle.Height = 20;
            //gvuser.HeaderRow.Style.Add("height", "20px");
            gvuser.GridLines = GridLines.Vertical;
            gvuser.HeaderStyle.BackColor = System.Drawing.Color.Green;
            gvuser.HeaderRow.Style.Add("background", "green");
            gvuser.HeaderRow.Style.Add("font-size", "8px");
            gvuser.Style.Add("text-decoration", "none");
            gvuser.Style.Add("font-family", "Arial, Helvetica, sans-serif;");
            gvuser.Style.Add("font-size", "6px");

            gvuser.Parent.Controls.Add(frm);
            frm.Attributes["runat"] = "server";
            frm.Controls.Add(gvuser);
            frm.RenderControl(hw);
            StringReader sr = new StringReader(sw.ToString());
            Document pdfDoc = new Document(PageSize.A4, 10f, 10f, 10f, 0f);
            HTMLWorker htmlparser = new HTMLWorker(pdfDoc);
            PdfWriter.GetInstance(pdfDoc, Response.OutputStream);
            pdfDoc.Open();


            if (isLogo)
            {
                iTextSharp.text.Image gif = iTextSharp.text.Image.GetInstance(Server.MapPath("~/App_Themes/buco/images/logo.jpg"));
                pdfDoc.Add(gif);
            }
            pdfDoc.Add(new Paragraph(fileName.Substring(0, fileName.IndexOf('.'))));
            pdfDoc.Add(new Paragraph(" "));

            htmlparser.Parse(sr);
            pdfDoc.Close();
            Response.Write(pdfDoc);
            Response.End();
        }

Read Data From Excel Sheet In ASP.net or create dataset from excel sheet

Here The Simple Method Which Make DataSet From Excel Sheet

Public dataset dataSetFromExcel(string filePath)
{

                string SheetName = GetExcelSheetNames( filePath );
                string constring = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" +  filePath + ";Extended           Properties='Excel 8.0;'";
                OleDbConnection con = new OleDbConnection(constring);
                string sql = "select * from [" + SheetName + "]";
                OleDbDataAdapter da = new OleDbDataAdapter(sql, con);
                da.TableMappings.Add("Table", SheetName);
                try
                {
                   
                    da.Fill(ds);
                    if (ds.Tables.Count > 0)
                    {
                        ViewState["data"] = ds;
                    }
                }
                catch (Exception ex)
                {
                    ex.ToString();
                }
                finally
                {
                    if (con != null)
                    {
                        con.Close();
                        con.Dispose();
                    }
                }
               

}




public static string GetExcelSheetNames(string excelFile)
        {
            OleDbConnection objConn = null;
            DataTable dt = null;
            try
            {
                String connString = "provider=Microsoft.Jet.OLEDB.4.0;Data Source='" + excelFile + "';Extended Properties=Excel 8.0;";
                objConn = new OleDbConnection(connString);
                objConn.Open();
                dt = objConn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
                if (dt == null)
                {
                    return null;
                }
                string SheetName = "";
                if (dt.Rows.Count > 0)
                {
                    SheetName = dt.Rows[0]["TABLE_NAME"].ToString();
                }
                return SheetName;
            }
            catch (Exception ex)
            {
                ex.ToString();
                return null;
            }
            finally
            {
                if (objConn != null)
                {
                    objConn.Close();
                    objConn.Dispose();
                }
                if (dt != null)
                {
                    dt.Dispose();
                }
            }
        }

Create Generic List From Reader In ASP.net


Here The Code By Using Which We Can Create a list from reader in C# ASP.net


 public List<T> SelectAll(string constr, string table, object val)
        {
            List<T> list = new List<T>();

            try
            {
                SqlConnection conn = Tools.GetConnection(constr);
                IDbCommand command = Tools.GetSelectCommand(table, conn, "id", val);
                IDataReader reader = command.ExecuteReader();

                list = Cbo.FillCollection<T>(reader);
                constr.cloase();
            }
            catch (Exception)
            {

                throw;
            }

            return list;
        }



 public static List<T> FillCollection<T>(IDataReader dr)
        {
            List<T> objFillCollection = new List<T>();
            T objFillObject;

            while (dr.Read())
            {
                //  fill business object
                objFillObject = CreateObject<T>(dr);
                //  add to collection
                objFillCollection.Add(objFillObject);
            }

            if (!(dr == null))
            {
                dr.Close();
            }

            return objFillCollection;

        }



 private static T CreateObject<T>(IDataReader dr)
        {
            Type objType = null;

            T obj = Activator.CreateInstance<T>();

            List<PropertyInfo> properties = Helper.GetPropertyInfo(typeof(T));

            int i;
            for (i = 0; i < dr.FieldCount; i++)
            {
                string columnName = dr.GetName(i);
                //now find matching property
                PropertyInfo propMatch = properties.Find(delegate(PropertyInfo p)
                {
                    Type t = typeof(T);
                    PropertyInfo pi = t.GetProperty(p.Name);
                    Column[] atrb = pi.GetCustomAttributes(typeof(Column), false) as Column[];
                    if (atrb != null)
                    {
                        if (atrb.Length > 0)
                        {
                            foreach (Column at in atrb)
                                if (at != null && !string.IsNullOrEmpty(at.Name))
                                {
                                    return at.Name.ToLower() == columnName.ToLower();
                                }
                        }
                    }
                   
                   
                    return p.Name.ToLower() == columnName.ToLower();
                   
                });
                if (propMatch != null)
                {
                    //we have found a matching property. fill it in

                    if (Convert.IsDBNull(dr.GetValue(i)))
                    {
                        propMatch.SetValue(obj, Null.GetNull(propMatch), null);
                    }
                    else
                    {
                        try
                        {
                            //  try implicit conversion first
                            propMatch.SetValue(obj, dr.GetValue(i), null);
                        }
                        catch
                        {
                            try
                            {
                                objType = propMatch.PropertyType;
                                // need to handle enumeration conversions differently than other base types
                                if (objType.BaseType.Equals(typeof(System.Enum)))
                                {
                                    if (Helper.IsNumeric(dr.GetValue(i)))
                                    {
                                        propMatch.SetValue(obj, System.Enum.ToObject(objType, Convert.ToInt32(dr.GetValue(i))), null);
                                    }
                                    else
                                    {
                                        propMatch.SetValue(obj, System.Enum.ToObject(objType, dr.GetValue(i)), null);
                                    }
                                }
                                else
                                {
                                    propMatch.SetValue(obj, Convert.ChangeType(dr.GetValue(i), objType), null);
                                }
                            }
                            catch
                            {
                                propMatch.SetValue(obj, Convert.ChangeType(dr.GetValue(i), objType), null);
                            }
                        }

                    }


                }
                else
                {
                    Console.WriteLine("property not found {0}", typeof(T).Name);
                }
            }

            return obj;
        }


FireFox Descriptions

For Debugging  of  FireFox  FireBug

For Coloring System    rainbow

for screenshots    AweSome Screen Shot for firefox

Thursday 21 June 2012

Converting DataReader To generic List Using C#...


First make one class having similar attribute as you database table for eg:
        public class Student
        {
            public int ID { get; set; }
            public string Name { get; set; }
            public DateTime DateOfBirth { get; set; }

        }
after that
            List<Student> student = new List<Student>();
            SqlConnection conn = new SqlConnection(@"Data Source=.\SQLEXPRESS;AttachDbFilename=D:\Prac\TestAssembly\ForumsProjectCSharp\App_Data\Studetnt.mdf;Integrated Security=True;User Instance=True");
            SqlCommand cmd = new SqlCommand("select * from Student", conn);
            SqlDataReader dr;
            try
            {
                conn.Open();
                dr = cmd.ExecuteReader();
                while (dr.Read())
                {
                    student.Add(new Student()
                    {
                        ID = dr.GetInt32(dr.GetOrdinal("ID")),
                        Name = dr.GetString(dr.GetOrdinal("Name")),
                        DateOfBirth = dr.GetDateTime(dr.GetOrdinal("DateOfBirth"))
                    });
                    
                }
                dr.Close();
            }
            catch (Exception exp)
            {

                throw;
            }
            finally
            {
                
                conn.Close();
            }

Wednesday 13 June 2012

new features added to sql server 2008


• Database mirroring. Microsoft first introduced this feature
in SQL Server 2005 and enhanced it in SQL Server 2008.
Database mirroring provides data administrators a low-cost
disaster recovery solution.
• Service Broker. SQL Server Service Broker provides an
integrated infrastructure on which developers can create
asynchronous messaging applications.
• Policy-based management. SQL Server 2008 lets you
automatically enforce and monitor policies for database
operations. You can also push these policies to your servers.
• Resource Governor. The Resource Governor lets you limit
the resource consumption of incoming requests by
classifying incoming connections as specific workload types
and defining limits for those types. You can also redefine the
limits in real time.
• Backup compression. SQL Server 2008 can automatically
compress database backups, a feature previously available
only via the purchase of third-party software products.
• Performance data collection. SQL Server 2008 lets you
store performance data in a centralized database. It also
provides enhanced tools for analyzing and reporting on such
performance data.
• New data types. The new SQL Server 2008 FILESTREAM
data type allows you to store large binary data, such as
documents or images, directly in an NTFS file system. Other
new data types include support for spatial data and the time
date type.
• “Hot add” hardware. First introduced in SQL Server 2005,
hot add memory helps system administrators decrease
downtime when important memory upgrades are necessary.
On supported hardware platforms, SQL Server 2008 also lets
you add one or more CPUs while the program is running.

What's Difference Between SQL Server 2005 And SQL Server 2008..


In sql server 2005,There is no option to compress backup files, but in sql server 2008,there you find it.

storing backup file takes 5 minutes without compression in sqlserver 2005,but it takes only 3 minutes in sql server 2008 for storing backup files with compression.

CPU is used to compress the data before it is written to disk,so less data is written to disk.


There are many new features, so it depends on what you need. If you store large files in SQL Server, migrated from Oracle and want to use date and time data types, need to encrypt your databases, etc you will definitely want to look at 2008. The nice thing is that it upgrading should be much easier from 2005 to 2008 than it was from 2000 to 2005.


Server 2008 also added CMS which is Central Management Server. It only works with Windows Authentication but it allows you to management multiple SQL Servers at once. If SQL Server systems are popping up like weeds it will appear in the CMS provided that they point to the CMS via SSMS. Its a really cool feature.

PBM Policy-Based Management is another added feature introduced with SQL Server 2008. PBM allows you to define and enforce policies for configuring and managing SQL Server across your enterprise. It goes hand-in-hand with CMS.


One of my favorite is that fact that Reporting Services no longer requires IIS as it makes direct calls to HTTP.SYS.

SQL2008 has support for additional datatypes:
date
time
geospatial
timestamp with internal timezone

Tuesday 5 June 2012

How I Make Excel Sheet From Genric List In Asp.net??

This Is The Complete Method To export List Item Into Excel




public void ExportToExcel<T>(List<T> list)
        {
            int columnCount = 0;
            DateTime StartTime = DateTime.Now;
            StringBuilder rowData = new StringBuilder();
            PropertyInfo[] properties = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance);
            rowData.Append("<Row ss:StyleID=\"s62\">");
            foreach (PropertyInfo p in properties)
            {
                if (p.PropertyType.Name != "EntityCollection`1" && p.PropertyType.Name != "EntityReference`1" && p.PropertyType.Name != p.Name)
                {
                    columnCount++;
                    rowData.Append("<Cell ss:StyleID=\"s62\"><Data ss:Type=\"String\">" + p.Name + "</Data></Cell>");
                }
                else
                    break;
            }
            rowData.Append("</Row>");
            foreach (T item in list)
            {

                rowData.Append("<Row>");
                for (int x = 0; x < columnCount; x++) //each (PropertyInfo p in properties)
                {
                    object o = properties[x].GetValue(item, null);
                    string value = o == null ? "" : o.ToString();
                    rowData.Append("<Cell ><Data ss:Type=\"String\">" + value + "</Data></Cell>");
                }
                rowData.Append("</Row>");

            }
            var sheet = @"<?xml version=""1.0""?>
            <?mso-application progid=""Excel.Sheet""?>                    
            <Workbook xmlns=""urn:schemas-microsoft-com:office:spreadsheet""                        
            xmlns:o=""urn:schemas-microsoft-com:office:office""                        
            xmlns:x=""urn:schemas-microsoft-com:office:excel""                        
            xmlns:ss=""urn:schemas-microsoft-com:office:spreadsheet""                        
            xmlns:html=""http://www.w3.org/TR/REC-html40"">                        
            <DocumentProperties xmlns=""urn:schemas-microsoft-com:office:office"">
            <Author>MSADMIN</Author>                            
            <LastAuthor>MSADMIN</LastAuthor>                            
            <Created>2011-07-12T23:40:11Z</Created>                            
            <Company>Microsoft</Company>                            
            <Version>12.00</Version>                        
            </DocumentProperties>                        
            <ExcelWorkbook xmlns=""urn:schemas-microsoft-com:office:excel"">                            
            <WindowHeight>6600</WindowHeight>                            
            <WindowWidth>12255</WindowWidth>                            
            <WindowTopX>0</WindowTopX>                            
            <WindowTopY>60</WindowTopY>                            
            <ProtectStructure>False</ProtectStructure>                            
            <ProtectWindows>False</ProtectWindows>                        
            </ExcelWorkbook>                        
            <Styles>                            
            <Style ss:ID=""Default"" ss:Name=""Normal"">                                
            <Alignment ss:Vertical=""Bottom""/>                                
            <Borders/>                                
            <Font ss:FontName=""Calibri"" x:Family=""Swiss"" ss:Size=""11"" ss:Color=""#000000""/>
            <Interior/>                              
            <NumberFormat/>                                
            <Protection/>                            
            </Style>
                           
            <Style ss:ID=""s62"">                                
            <Font ss:FontName=""Calibri"" x:Family=""Swiss"" ss:Size=""11"" ss:Color=""#000000""  ss:Bold=""1""/>
            </Style>                        
            </Styles>                        
            <Worksheet ss:Name=""Sheet1"">                            
            <Table ss:ExpandedColumnCount=""" + (properties.Count() + 1) + @""" ss:ExpandedRowCount=""" + (list.Count() + 1) + @""" x:FullColumns=""1"" x:FullRows=""1"" ss:DefaultRowHeight=""15"">
            " + rowData.ToString() + @"                            
            </Table>                            
            <WorksheetOptions xmlns=""urn:schemas-microsoft-com:office:excel"">
            <PageSetup>                                    
            <Header x:Margin=""0.3""/>                                    
            <Footer x:Margin=""0.3""/>                                    
            <PageMargins x:Bottom=""0.75"" x:Left=""0.7"" x:Right=""0.7"" x:Top=""0.75""/>
            </PageSetup>                                
            <Print>                                    
            <ValidPrinterInfo/>                                    
            <HorizontalResolution>300</HorizontalResolution>                                    
            <VerticalResolution>300</VerticalResolution>                                
            </Print>                                
            <Selected/>                                
            <Panes>                                    
            <Pane>                                        
            <Number>3</Number>                                        
            <ActiveCol>2</ActiveCol>                                    
            </Pane>                                
            </Panes>                                
            <ProtectObjects>False</ProtectObjects>                                
            <ProtectScenarios>False</ProtectScenarios>                            
            </WorksheetOptions>                        
            </Worksheet>                        
            <Worksheet ss:Name=""Sheet2"">                            
            <Table ss:ExpandedColumnCount=""1"" ss:ExpandedRowCount=""1"" x:FullColumns=""1"" x:FullRows=""1"" ss:DefaultRowHeight=""15"">
            </Table>                            
            <WorksheetOptions xmlns=""urn:schemas-microsoft-com:office:excel"">
            <PageSetup>                                    
            <Header x:Margin=""0.3""/>                                    
            <Footer x:Margin=""0.3""/>                                    
            <PageMargins x:Bottom=""0.75"" x:Left=""0.7"" x:Right=""0.7"" x:Top=""0.75""/>
            </PageSetup>                                
            <ProtectObjects>False</ProtectObjects>                                
            <ProtectScenarios>False</ProtectScenarios>                            
            </WorksheetOptions>                        
            </Worksheet>                        
            <Worksheet ss:Name=""Sheet3"">                            
            <Table ss:ExpandedColumnCount=""1"" ss:ExpandedRowCount=""1"" x:FullColumns=""1"" x:FullRows=""1"" ss:DefaultRowHeight=""15"">
            </Table>                            
            <WorksheetOptions xmlns=""urn:schemas-microsoft-com:office:excel"">
            <PageSetup>                                    
            <Header x:Margin=""0.3""/>                                    
            <Footer x:Margin=""0.3""/>                                    
            <PageMargins x:Bottom=""0.75"" x:Left=""0.7"" x:Right=""0.7"" x:Top=""0.75""/>
            </PageSetup>                                
            <ProtectObjects>False</ProtectObjects>                                
            <ProtectScenarios>False</ProtectScenarios>                            
            </WorksheetOptions>                        
            </Worksheet>                    
            </Workbook>";
            System.Diagnostics.Debug.Print(StartTime.ToString() + " - " + DateTime.Now);
            System.Diagnostics.Debug.Print((DateTime.Now - StartTime).ToString());
            string attachment = "attachment; filename=Report.xls";
            HttpContext.Current.Response.ClearContent();
            HttpContext.Current.Response.AddHeader("content-disposition", attachment);
            HttpContext.Current.Response.Write(sheet);
            HttpContext.Current.Response.ContentType = "application/ms-excel";
            HttpContext.Current.Response.End();
        }