Showing posts with label C#. Show all posts
Showing posts with label C#. Show all posts

Saturday, August 4, 2012

DateTime.ParseExact - culturewise Date Comparision

Hello..

Whenever dealing with cultures, DateTime format is always a headache to handle.

to the date format  in Textbox sometimes does not meet the format of culture.
in that case DateTime.ParseExact is good option to handle.

convert the date into current culture format from display culture format using

public static DateTime ParseExact( string str, string Dateformat, IFormatProvider provider)


Parameters

str
Type: System.String
A string that contains a date and time to convert.
Dateformat 
Type: System.String
A format specifier that defines the required format of s.
provider 
Type: System.IFormatProvider
An object that supplies culture-specific format information about s.
example
DateTime sessionDate = DateTime.ParseExact(txtDate.Text, "M-d-yyyy", provider);
here provide is
CultureInfo provider = CultureInfo.InvariantCulture;
this will get txtDate.Text (Date) into culture wise date format to compare with database formatted datetime.

Hope this Helps

All the best.


Saturday, November 19, 2011

Create Excel File From DataTable

Hello Friends,
Many times we need to create Excel files in our application using existing Data.
I have figured out a class which will help to create excel file by just passing DataTable and preferred location to generate on server.
please download the cs file from here .. and use it :)

here is full code

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Xml;


    public class ExcelHelper
    {
        private static readonly ExcelHelper _instance = new ExcelHelper();

        public static ExcelHelper Instance
        {
            get { return _instance; }
        }
        /// <summary>
        /// Create one Excel-XML-Document with SpreadsheetML from a DataTable
        /// </summary>
        /// <param name="dataSource">Datasource which would be exported in Excel</param>
        /// <param name="fileName">Name of exported file</param>
        public void Create(DataTable dtSource, string strFileName)
        {
            // Create XMLWriter
            using (XmlTextWriter xtwWriter = new XmlTextWriter(strFileName, Encoding.UTF8))
            {

                //Format the output file for reading easier
                xtwWriter.Formatting = Formatting.Indented;

                // <?xml version="1.0"?>
                xtwWriter.WriteStartDocument();

                // <?mso-application progid="Excel.Sheet"?>
                xtwWriter.WriteProcessingInstruction("mso-application", "progid=\"Excel.Sheet\"");

                // <Workbook xmlns="urn:schemas-microsoft-com:office:spreadsheet >"
                xtwWriter.WriteStartElement("Workbook", "urn:schemas-microsoft-com:office:spreadsheet");

                //Write definition of namespace
                xtwWriter.WriteAttributeString("xmlns", "o", null, "urn:schemas-microsoft-com:office:office");
                xtwWriter.WriteAttributeString("xmlns", "x", null, "urn:schemas-microsoft-com:office:excel");
                xtwWriter.WriteAttributeString("xmlns", "ss", null, "urn:schemas-microsoft-com:office:spreadsheet");
                xtwWriter.WriteAttributeString("xmlns", "html", null, "http://www.w3.org/TR/REC-html40");

                // <DocumentProperties xmlns="urn:schemas-microsoft-com:office:office">
                xtwWriter.WriteStartElement("DocumentProperties", "urn:schemas-microsoft-com:office:office");

                // Write document properties
                xtwWriter.WriteElementString("Author", "Sandeep Prajapati");
                xtwWriter.WriteElementString("LastAuthor", "Sandeep Prajapati");
                xtwWriter.WriteElementString("Created", DateTime.Now.ToString("u") + "Z");
                xtwWriter.WriteElementString("Company", "XXXXXXXXXX");
                xtwWriter.WriteElementString("Version", "12");

                // </DocumentProperties>
                xtwWriter.WriteEndElement();

                // <ExcelWorkbook xmlns="urn:schemas-microsoft-com:office:excel">
                xtwWriter.WriteStartElement("ExcelWorkbook", "urn:schemas-microsoft-com:office:excel");

                // Write settings of workbook
                xtwWriter.WriteElementString("WindowHeight", "8010");
                xtwWriter.WriteElementString("WindowWidth", "14805");
                xtwWriter.WriteElementString("WindowTopX", "240");
                xtwWriter.WriteElementString("WindowTopY", "105");
                xtwWriter.WriteElementString("ProtectStructure", "False");
                xtwWriter.WriteElementString("ProtectWindows", "False");

                // </ExcelWorkbook>
                xtwWriter.WriteEndElement();

                // <Styles>
                xtwWriter.WriteStartElement("Styles");

                // <Style ss:ID="Default" ss:Name="Normal">
                xtwWriter.WriteStartElement("Style");
                xtwWriter.WriteAttributeString("ss", "ID", null, "Default");
                xtwWriter.WriteAttributeString("ss", "Name", null, "Normal");

                // <Alignment ss:Vertical="Bottom"/>
                xtwWriter.WriteStartElement("Alignment");
                xtwWriter.WriteAttributeString("ss", "Vertical", null, "Bottom");
                xtwWriter.WriteEndElement();

                // Write null on the other properties
                xtwWriter.WriteElementString("Borders", null);
                xtwWriter.WriteElementString("Font", null);
                xtwWriter.WriteElementString("Interior", null);
                xtwWriter.WriteElementString("NumberFormat", null);
                xtwWriter.WriteElementString("Protection", null);


                // </Style>
                xtwWriter.WriteEndElement();

                //<Style ss:ID="s16">
                xtwWriter.WriteStartElement("Style");
                xtwWriter.WriteAttributeString("ss", "ID", null, "s16");
                xtwWriter.WriteStartElement("Font");
                xtwWriter.WriteAttributeString("ss", "Bold", null, "1");
                xtwWriter.WriteAttributeString("ss", "Size", null, "11");
                xtwWriter.WriteAttributeString("ss", "Underline", null, "Single");
                xtwWriter.WriteEndElement();

                // </Style>
                xtwWriter.WriteEndElement();


                // </Styles>
                xtwWriter.WriteEndElement();

                // <Worksheet ss:Name="xxx">
                xtwWriter.WriteStartElement("Worksheet");
                xtwWriter.WriteAttributeString("ss", "Name", null, dtSource.TableName);

                // <Table ss:ExpandedColumnCount="2" ss:ExpandedRowCount="3" x:FullColumns="1" x:FullRows="1" ss:DefaultColumnWidth="60">
                xtwWriter.WriteStartElement("Table");
                xtwWriter.WriteAttributeString("ss", "ExpandedColumnCount", null, dtSource.Columns.Count.ToString());
                xtwWriter.WriteAttributeString("ss", "ExpandedRowCount", null, (dtSource.Rows.Count + 1).ToString());
                xtwWriter.WriteAttributeString("x", "FullColumns", null, "1");
                xtwWriter.WriteAttributeString("x", "FullRows", null, "1");
                //xtwWriter.WriteAttributeString("ss", "DefaultColumnWidth", null, "60");

                // Run through all rows of data source


                // <Row>
                xtwWriter.WriteStartElement("Row");
                foreach (DataColumn Header in dtSource.Columns)
                {
                    // <Cell>
                    xtwWriter.WriteStartElement("Cell");
                    xtwWriter.WriteAttributeString("ss", "StyleID", null, "s16");

                    // <Data ss:Type="String">xxx</Data>
                    xtwWriter.WriteStartElement("Data");
                    xtwWriter.WriteAttributeString("ss", "Type", null, "String");
                    // Write content of cell
                    xtwWriter.WriteValue(Header.ColumnName);

                    // </Data>
                    xtwWriter.WriteEndElement();

                    // </Cell>
                    xtwWriter.WriteEndElement();
                }

                xtwWriter.WriteEndElement();


                foreach (DataRow row in dtSource.Rows)
                {
                    // <Row>
                    xtwWriter.WriteStartElement("Row");

                    // Run through all cell of current rows
                    foreach (object cellValue in row.ItemArray)
                    {
                        // <Cell>
                        xtwWriter.WriteStartElement("Cell");
                        //if (cnt == 0)
                        //    xtwWriter.WriteAttributeString("ss", "StyleID", null, "s16");

                        // <Data ss:Type="String">xxx</Data>
                        xtwWriter.WriteStartElement("Data");
                        xtwWriter.WriteAttributeString("ss", "Type", null, "String");
                        // Write content of cell
                        string strcellValue = (cellValue == System.DBNull.Value ? string.Empty : (string)cellValue);
                        xtwWriter.WriteValue(strcellValue);

                        // </Data>
                        xtwWriter.WriteEndElement();

                        // </Cell>
                        xtwWriter.WriteEndElement();
                    }
                    // </Row>
                    xtwWriter.WriteEndElement();
                }
                // </Table>
                xtwWriter.WriteEndElement();

                // <WorksheetOptions xmlns="urn:schemas-microsoft-com:office:excel">
                xtwWriter.WriteStartElement("WorksheetOptions", "urn:schemas-microsoft-com:office:excel");

                // Write settings of page
                xtwWriter.WriteStartElement("PageSetup");
                xtwWriter.WriteStartElement("Header");
                xtwWriter.WriteAttributeString("x", "Margin", null, "0.4921259845");
                xtwWriter.WriteEndElement();
                xtwWriter.WriteStartElement("Footer");
                xtwWriter.WriteAttributeString("x", "Margin", null, "0.4921259845");
                xtwWriter.WriteEndElement();
                xtwWriter.WriteStartElement("PageMargins");
                xtwWriter.WriteAttributeString("x", "Bottom", null, "0.984251969");
                xtwWriter.WriteAttributeString("x", "Left", null, "0.78740157499999996");
                xtwWriter.WriteAttributeString("x", "Right", null, "0.78740157499999996");
                xtwWriter.WriteAttributeString("x", "Top", null, "0.984251969");
                xtwWriter.WriteEndElement();
                xtwWriter.WriteEndElement();

                // <Selected/>
                xtwWriter.WriteElementString("Selected", null);

                // <Panes>
                xtwWriter.WriteStartElement("Panes");

                // <Pane>
                xtwWriter.WriteStartElement("Pane");

                // Write settings of active field
                xtwWriter.WriteElementString("Number", "1");
                xtwWriter.WriteElementString("ActiveRow", "1");
                xtwWriter.WriteElementString("ActiveCol", "1");

                // </Pane>
                xtwWriter.WriteEndElement();

                // </Panes>
                xtwWriter.WriteEndElement();

                // <ProtectObjects>False</ProtectObjects>
                xtwWriter.WriteElementString("ProtectObjects", "False");

                // <ProtectScenarios>False</ProtectScenarios>
                xtwWriter.WriteElementString("ProtectScenarios", "False");

                // </WorksheetOptions>
                xtwWriter.WriteEndElement();

                // </Worksheet>
                xtwWriter.WriteEndElement();

                // </Workbook>
                xtwWriter.WriteEndElement();

                // Write file on hard disk
                xtwWriter.Flush();
                xtwWriter.Close();
            }
        }
    }


Write me if help full
Happy Coding..

Friday, April 29, 2011

Protect image from being copied

Hello Friends,

Many times I am asked to protect some copyrighted images over web,
so finally I have found a better way to protect from being copied.
There are some cases by which we can copy the image
Here I have taken care of following cases
  • Right click on image and Save the Image
  • Save the Entire page and all images displayed on page will be downloaded to its Data Folder
  • in mozila Firefox, We can save the media files by following steps
    1. Right click on Page, select “View Page Info”
    2. ViewSourceSandeep
    3. It will open a window, Select “Media” tab, here a list of all files will be available
    4. select particular file and click on “Save As” button to save the media
    5. SavemediaSandeep


Now Let’s Start our main topic,that is protect image from being copied
There is a concept called Data URI scheme.
Generally to display any image on page, we use Relative_URL and if we display image using this, the images can be easily copied.
Here we will save image in database and retrieve the same
To Create table
CREATE TABLE [dbo].[Images](
 [ImageID] [int] IDENTITY(1,1) NOT NULL,
 [ImageName] [varchar](50) NULL,
 [Image] [image] NULL,
 [ext] [varchar](50) NULL,
 CONSTRAINT [PK_Images] PRIMARY KEY CLUSTERED 
(
 [ImageID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]

Now,

the aspx page will be very simple like


Sunday, August 29, 2010

Access ViewState From ClassFile

teHello Friends

Manytime we need to use ViewState while working 3-tier Architecture but its difficult to use it.
here i have made a sample to use Viewstate from Classfile

ViewState:
Viewstate is an object of Class StateBag

 Here is sample of Viewstate in Class file
in this example we will add names from Textbox to gridview using Viewstate.
so
in code behind

<div>
                Name :
                <asp:TextBox ID="txtName" runat="server"></asp:TextBox><asp:Button ID="btnAdd" runat="server" Text="Add" />
            </div>
            <div>
                <asp:GridView ID="grvNames" runat="server" AutoGenerateColumns="False" CellPadding="4" ForeColor="#333333" GridLines="None">
                    <RowStyle BackColor="#F7F6F3" ForeColor="#333333" />
                    <Columns>
                        <asp:BoundField DataField="ID" HeaderText="No" />
                        <asp:BoundField DataField="SName" HeaderText="Name" />
                    </Columns>
                    <FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
                    <PagerStyle BackColor="#284775" ForeColor="White" HorizontalAlign="Center" />
                    <SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" />
                    <HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
                    <EditRowStyle BackColor="#999999" />
                    <AlternatingRowStyle BackColor="White" ForeColor="#284775" />
                </asp:GridView>
            </div>


and in aspx.cs 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)
    {
        Controller_Default objController = new Controller_Default(this.ViewState);
        btnAdd.Click += new EventHandler(objController.btnAdd_Click);
    }
}


 Now Create a Controller file named Controller_Default.cs in a Folder named Controller
The Code in the Controller Class will go like this

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

public class Controller_Default
{
    #region Variables & contructors

    IDictionary _ViewState;
    public Controller_Default() { }

    public Controller_Default(IDictionary objStageBag)
    {
        _ViewState = objStageBag;
    }
    #endregion

    #region Events
    /// 
    /// Button Event to Add Name 
    /// 
    ///     ///     public void btnAdd_Click(object sender, EventArgs e)
    {
        Button btn = (Button)sender;
        try
        {
            DataTable dt = new DataTable();
            ViewStateClass objViewState = new ViewStateClass(_ViewState);
            if (objViewState.GetViewStateTable("TblNames") != null)
                dt = objViewState.GetViewStateTable("TblNames");
            else
                dt = CreateNewTable();

            DataRow dr = dt.NewRow();
            dr["ID"] = dt.Rows.Count + 1;
            dr["SName"] = ((TextBox)btn.Parent.FindControl("txtName")).Text.ToString();
            dt.Rows.Add(dr);

            objViewState.SetViewState("TblNames", dt);
            GridView grv = (GridView)btn.Parent.FindControl("grvNames");
            grv.DataSource = dt;
            grv.DataBind();

            ((TextBox)btn.Parent.FindControl("txtName")).Text = string.Empty;
            ((TextBox)btn.Parent.FindControl("txtName")).Focus();
        }
        catch (Exception Ex) { }
    }
    #endregion

    #region Methods
    /// 
    /// Method to Create New Table
    /// 
    /// 
    private DataTable CreateNewTable()
    {
        DataTable dt = new DataTable();
        dt.Columns.Add("ID");
        dt.Columns.Add("SName");
        return dt;
    }
    #endregion
}



in this code we have created and object Named objViewState of class ViewStateClass.

The Syntex objViewState.GetViewStateTable("TblNames") is used to get DataTable from ViewState
Same way  objViewState.SetViewState("TblNames", dt); Saves the DataTable in ViewState.
  
 Now here is the class ViewStateClass , you can download it from here
 in this class we have many methods to save different types like String,Int, Array and so on ... you can create same whichever you require.
you can download the source from Here

All The Best