Thursday, May 24, 2012

How to strore Image from Image Control into folder Not from using File Upload Control


Some days back i came across this problem where i have to store Image into folder from Image control where Image are coming from some external link.so I would Like to share with you which might help you any day....

string filepath = Server.MapPath(img1.ImageUrl);
using (WebClient client = new WebClient())
{
         client.DownloadFile(filepath, Server.MapPath("Specify the path where you want to  store Image+imagename"));
         //For Example client.DownloadFile(filepath, Server.MapPath("~/Image/apple.jpg"));
}

What is Local Resource File and Global Resource File?


You can use any combination of global and local resource files in the Web application. Generally, you add resources to a global resource file when you want to share the resources between pages. Resources in global resource files are also strongly typed for when you want to access the files programmatically.

However, global resource files can become large, if you store all localized resources in them. Global resource files can also be more difficult to manage, if more than one developer is working on different pages but in a single resource file.

Local resource files make it easier to manage resources for a single ASP.NET Web page. But you cannot share resources between pages. Additionally, you might create lots of local resource files, if you have many pages that must be localized into many languages. If sites are large with many folders and languages, local resources can quickly expand the number of assemblies in the application domain.

When you make a change to a default resource file, either local or global, ASP.NET recompiles the resources and restarts the ASP.NET application. This can affect the overall performance of your site. If you add satellite resource files, it does not cause a recompilation of resources, but the ASP.NET application will restart.

Global Resource Files

You create a global resource file by putting it in the reserved folder App_GlobalResources at the root of the application. Any .resx file that is in the App_GlobalResources folder has global scope. Additionally, ASP.NET generates a strongly typed object that gives you a simple way to programmatically access global resources.

Local Resource Files

A local resources file is one that applies to only one ASP.NET page or user control (an ASP.NET file that has a file-name extension of .aspx, .ascx, or .master). You put local resource files in folders that have the reserved name App_LocalResources. Unlike the root App_GlobalResources folder, App_LocalResources folders can be in any folder in the application. You associate a set of resources files with a specific Web page by using the name of the resource file.

For example, if you have a page named Default.aspx in the App_LocalResources folder, you might create the following files:

Default.aspx.resx. This is the default local resource file (the fallback resource file) if no language match is found.

Default.aspx.es.resx. This is the resource file for Spanish, without culture information.

Default.aspx.es-mx.resx. This is the resource file for Spanish (Mexico) specifically.

Default.aspx.fr.resx. This is the resource file for French, without culture information.

The base name of the file matches the page file name, followed by a language and culture name, and ending with the extension .resx. For a list of culture names, see CultureInfo.


To use implicit localization

Open the page for which you want to create resource files.

Switch to Design View.

In the Tools menu, click Generate Local Resource.

Visual Web Developer creates the App_LocalResources folder if it does not already exist. Visual Web Developer then creates the base resource file for the current page, which includes a key/name pair for every localizable control of every ASP.NET Web server control on the page. Finally, Visual Web Developer adds a meta attribute to each ASP.NET Web server control to configure the control to use implicit localization.

Wednesday, May 23, 2012

How to Create a Webservice and How can we use it in .aspx Page?


What are Web Services?
Web services are small units of code
Web services are designed to handle a limited set of tasks
Web services use XML based communicating protocols(HTTP,XML,SOAP,WSDL,UDDI)
Web services are independent of operating systems
Web services are independent of programming languages
Web services connect people, systems and devices

Benefits of Web Services
Easier to communicate between applications
Easier to reuse existing services
Easier to distribute information to more consumers
Rapid development

Steps to Create a Web Service.

      Here I am going to show you demo of how to Retrive data using web services and display it on to the aspx Page.
  •  Create a Project called SampleWebSevice
  • Go to Solution Explorer right click on Project and Click on Add - > New Item.Under Web Option you find Web Service Select it and name it Service1.asmx and add it into the Project.
  • Now Create a Table Name Office with following Field.
         
  • Now Add the Method in Service1.asmx.cs Page
  • [WebMethod]

        public XmlElement GetUserDetails(string officename)
        {
            SqlConnection con = new SqlConnection(@"Data Source=kartikpatel\SQLEXPRESS;Initial Catalog=master;Integrated Security=True");
            con.Open();
            string s = "select * from Office where OfficeName like '%" + officename + "%'";
            SqlDataAdapter da = new SqlDataAdapter(s, con);
            DataSet ds = new DataSet();
            da.Fill(ds);
            con.Close();
            XmlDataDocument xmldata = new XmlDataDocument(ds);
            XmlElement xmlElement = xmldata.DocumentElement;
            return xmlElement;
        }

  • Now Build solution and Host this service on your PC in iis.and name the virtual directory WebService  for this service.Now browse it and test this service.
  • Download WebService Sample from here......
    Download
  • Now Create a New Project Name SampleWebService  to use the Webservice that is created before.
  • Now Right Click On Project in solution explorer. and Click on Add Web Reference you will shown the below screen and then add Url in that which we configure in iis.(http://localhost/WebService/Service1.asmx).
         
  • Add Web Reference Name OfficeList and Click On Add Reference.
  • Now Add the aspx page by right click on project in solution explorer.
  • Now Add the GridView in Default.aspx Page.

 <table>
            <tr>
                <td>
                    <b>Enter OfficeName:</b>
                </td>
                <td>
                    <asp:TextBox ID="txtOfficeName" runat="server"></asp:TextBox>
                </td>
                <td>
                    <asp:Button ID="btnSubmit" runat="server" Text="Submit" OnClick="btnSubmit_Click" />
                </td>
            </tr>
        </table>
    </div>
    <div>
        <asp:GridView ID="gvUserDetails" runat="server" EmptyDataText="No Record Found">
            <RowStyle BackColor="#EFF3FB" />
            <FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
            <PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Center" />
            <HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
            <AlternatingRowStyle BackColor="White" />
        </asp:GridView>

Now Add code in aspx.cs page.
using System.Xml;
using System.Data;

 protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                BindUserDetails("");
            }
        }
        protected void BindUserDetails(string userName)
        {
            OfficeList.Service1 objofficeDetails = new OfficeList.Service1();

            DataSet dsresult = new DataSet();
            XmlElement exelement = objofficeDetails.GetUserDetails(userName);
            if (exelement != null)
            {
                XmlNodeReader nodereader = new XmlNodeReader(exelement);
                dsresult.ReadXml(nodereader, XmlReadMode.Auto);
                gvUserDetails.DataSource = dsresult;
                gvUserDetails.DataBind();
            }
            else
            {
                gvUserDetails.DataSource = null;
                gvUserDetails.DataBind();
            }
        }
        protected void btnSubmit_Click(object sender, EventArgs e)
        {
            BindUserDetails(txtOfficeName.Text);
        }
  • Now run this Page.
  • Here i have use the XmlElement as the Return Type of Method in web service.Thats why i have to take the data from xmlelement to dataset in code.

Feel free if you have any confusion.

Download Code from here......
Download


Common Linq To SQL operation sheet.


Hello Friends.I dont know the real source of this useful Point.but i got it from somewhere.I found this useful opertaion sheet.so i want to share with you which might help you any day.

I also attach a File for this useful sheet which contains all the operation for Linq to SQL with example in both C# and VB



Download Sheet from here......
Download

Tuesday, May 22, 2012

How to save Image From ImageControl without FileUpload Contol..

First Get the Url of Image and then using webclient you can save file in folder.



string filepath = img1.ImageUrl;           
using (WebClient client = new WebClient())
{
 client.DownloadFile(filepath,Server.MapPath("~/Image/apple.jpg"));
}
This will save image in Image Folder with ImageName apple...

Saturday, May 19, 2012

Delete Duplicate Rows From Table....


In this Article I will explain you about how to delete Duplicate rows from Table

Our Table does not contain any primary key column because of that it contains duplicate records that would be like this

Now just Run this Querry 

WITH tempTable as
(
select ROW_NUMBER() Over(partition by Name,Class order by Name) As RowNumber,* from ClassData
)
select * from temptable

OutPut Of this Querry will be 
If you observe above table I added another column RowNumber this column is used to know which record contains duplicate values based on rows with RowNumber greater than 1.  

Now we want to get the records which contains unique value from datatable for that we need to write the query like this


WITH tempTable as
(
select ROW_NUMBER() Over(partition by Name,Class order by Name) As RowNumber,* from ClassData
)
delete from temptable where RowNumber>1
select * from ClassData;

When you Run this Querry OutPut will be like this......


How to Get List of Columns Name,Data types of Table


Here I am explained you how to get the List of Columns and their datatypes from particular Table using SQL.

For Example i have a Table Office.write a querry


USE master
GO
SELECT column_name 'Column Name',
data_type 'Data Type',
character_maximum_length 'Maximum Length'
FROM information_schema.columns
WHERE table_name = 'Office'

where master=Database Name ,'Office' is a Table Name

After run this Querry you will get


Wednesday, May 9, 2012

Read/write appsettings from web config.file in c#.


Introduction: 

In this Post I will explain how to read or write appsettings in web.config file using asp.net.

Description: 

Now I will explain how to write appsettings in web.config file and how to read appsettings from web.config file using asp.net. 


To add appsettings first create new website open web.config file and search for “appSettings” and add new item in appSettings section.The section is like this.

<appSettings>
<add key="yourappsettingsstringName" value=" yourappsettingsvalue" />
</appSettings>

The main purpose used for appsettings is for declaring the connection string.because if we have a too many pages in application then it will not require to write connection string on every page.However we can define any key which are used in many pages.

Example of declaring 
appSettings in web.config file like this.

<appSettings>
<add key="dbconnectionstring" value="Data SOurce=KartikPatel;Initial Catalog=MysampleDB; Integrated Security=true"/>
</appSettings>


The good advantage of writing the appsettings in web config is we can manage it easily.means if we want to change its value then we can change it only in appsetting.we dont need to write and change it in every pages.This is the biggest advantage of it.

Lets take an Example.and test it.


<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Read or Write appsetting values from web.config file in asp.net</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Label ID="lblText" runat="server"/>
</div>
</form>
</body>
</html>

After that add following namespace in codebehind file

using System;
using System.Configuration;

 The namespace using System.Configuration; is used to get configuration section details from web.config file.

After add namespaces write the following code in code behind

protected void Page_Load(object sender, EventArgs e)
{
//Get appsettings string value from web.config file
string strcon = System.Configuration.ConfigurationManager.AppSettings["dbconnectionstring"];
//Bind appsettings string value to label
lblText.Text = strcon;
}

Above Example shows how to read the appsettings from web config.

Tuesday, May 8, 2012

Generate PDF by Reading HTML File by Replacing Data.


Add itextsharp.dll
Create a Table called PersonalData with following column



Add Employment.htm file in project and create a HTML File

  <div id="divPersonalDataContainer">
    <table>
        <tr>
            <td bgcolor="#0066ff" colspan = "6" >
               <span style ="color:White">Personal Data</span>
            </td>
        </tr>
    </table>
        <div id="tablContainer">
            <table class="tableclass">
                <tr>
                    <td>
                        <b>Salutation</b>
                    </td>
                    <td class="LableValue">
                        {Salutation}
                    </td>
                    <td class="LableText">
                        <b>First Name</b>
                    </td>
                    <td class="LableValue">
                        {First Name}
                    </td>
                    <td class="LableText">
                        <b>Middle Name</b>
                    </td>
                    <td class="LableValue">
                        {Middle Name}
                    </td>
                </tr>
                <tr>
                    <td class="LableText">
                        <b>Last Name</b>
                    </td>
                    <td class="LableValue">
                        {Last Name}
                    </td>
                    <td class="LableText">
                        <b>Nick Name</b>
                    </td>
                    <td class="LableValue">
                        {Nick Name}
                    </td>
                    <td class="LableText">
                    </td>
                    <td class="LableValue">
                    </td>
                </tr>
                <tr>
                    <td class="LableText">
                        <b>Present Address</b>
                    </td>
                    <td class="LableValue" colspan="5">
                        {Present Address}
                    </td>
                </tr>
                <tr>
                    <td class="LableText">
                        <b>City</b>
                    </td>
                    <td class="LableValue">
                        {City}
                    </td>
                    <td class="LableText">
                        <b>State</b>
                    </td>
                    <td class="LableValue">
                        {State}
                    </td>
                    <td class="LableText">
                        <b>Country</b>
                    </td>
                    <td class="LableValue">
                        {Country}
                    </td>
                </tr>
                <tr>
                    <td class="LableText">
                        <b>Zip Code</b>
                    </td>
                    <td class="LableValue">
                        {Zip Code}
                    </td>
                    <td class="LableText">
                        <b>Home Phone</b>
                    </td>
                    <td class="LableValue">
                        {Home Phone}
                    </td>
                    <td class="LableText">
                        <b>Email</b>
                    </td>
                    <td class="LableValue">
                        {Email}
                    </td>
                </tr>
            
                <tr>
                    <td colspan="6">
                    </td>
                </tr>
            </table>
        </div>
   </div>


Create a TestForm.aspx and in code behind write

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using System.Data;
using System.Data.SqlClient;
using iTextSharp.text;
using iTextSharp.text.html;
using iTextSharp.text.html.simpleparser;
using iTextSharp.text.pdf;


public partial class TestForm : System.Web.UI.Page
{
  
    protected void Page_Load(object sender, EventArgs e)
    {
            //Just For Demo we have Retriving detail for EmployeId=1
            int Id = 1;
            SetControl(Id);
      

    }
    public void SetControl(int EmpID)
    {
        try
        {
            SqlConnection con = new SqlConnection(@"Your database connectionstring.");
            con.Open();
            string s = "select * from PersonalData where EmployeeID=" + EmpID + "";
            SqlCommand cmd = new SqlCommand(s, con);
            SqlDataReader dr = cmd.ExecuteReader();
            string fileContents;

            string FilePath = Server.MapPath("EmploymentForm.htm");
            StreamReader mstrFileStreamReader = new StreamReader(FilePath);
            try
            {
                fileContents = mstrFileStreamReader.ReadToEnd();
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                mstrFileStreamReader.Close();
            }
            while (dr.Read())
            {
                if (dr != null)
                {
                    if (!String.IsNullOrEmpty(dr[0].ToString()))
                    {
                        fileContents = fileContents.Replace("{Salutation}", dr["Suffix"].ToString());
                    }
                    else
                    {
                        fileContents = fileContents.Replace("{Salutation}", "");
                    }
                    if (!String.IsNullOrEmpty(dr["LastName"].ToString()))
                    {
                        fileContents = fileContents.Replace("{Last Name}", dr["LastName"].ToString());
                    }
                    else { fileContents = fileContents.Replace("{Last Name}", ""); }
                    if (!String.IsNullOrEmpty(dr["FirstName"].ToString()))
                    {
                        fileContents = fileContents.Replace("{First Name}", dr["FirstName"].ToString());
                    }
                    else
                    {
                        fileContents = fileContents.Replace("{First Name}", "");

                    }
                    if (!String.IsNullOrEmpty(dr["MiddleName"].ToString()))
                    {
                        fileContents = fileContents.Replace("{Middle Name}", dr["MiddleName"].ToString());
                    }
                    else
                    {
                        fileContents = fileContents.Replace("{Middle Name}", "");
                    }
                    if (!String.IsNullOrEmpty(dr["NickName"].ToString()))
                    {
                        fileContents = fileContents.Replace("{Nick Name}", dr["NickName"].ToString());
                    }
                    else
                    {
                        fileContents = fileContents.Replace("{Nick Name}", "");
                    }
                    if (!String.IsNullOrEmpty(dr["PresentAddress"].ToString()))
                    {
                        fileContents = fileContents.Replace("{Present Address}", dr["PresentAddress"].ToString());
                    }
                    else
                    {
                        fileContents = fileContents.Replace("{Present Address}", "");
                    }
                    if (!String.IsNullOrEmpty(dr["City"].ToString()))
                    {
                        fileContents = fileContents.Replace("{City}", dr["City"].ToString());
                    }
                    else
                    {
                        fileContents = fileContents.Replace("{City}", "");
                    }
                    if (!String.IsNullOrEmpty(dr["State"].ToString()))
                    {
                        fileContents = fileContents.Replace("{State}", dr["State"].ToString());
                    }
                    else
                    {
                        fileContents = fileContents.Replace("{State}", "");
                    }
                    if (!String.IsNullOrEmpty(dr["Country"].ToString()))
                    {
                        fileContents = fileContents.Replace("{Country}", dr["Country"].ToString());
                    }
                    else
                    {
                        fileContents = fileContents.Replace("{Country}", "");
                    }
                    if (!String.IsNullOrEmpty(dr["ZipCode"].ToString()))
                    {
                        fileContents = fileContents.Replace("{Zip Code}", dr["ZipCode"].ToString());
                    }
                    else
                    {
                        fileContents = fileContents.Replace("{Zip Code}", "");
                    }
                    if (!String.IsNullOrEmpty(dr["HomePhone"].ToString()))
                    {
                        fileContents = fileContents.Replace("{Home Phone}", dr["HomePhone"].ToString());
                    }
                    else { fileContents = fileContents.Replace("{Home Phone}", ""); }

                    if (!String.IsNullOrEmpty(dr["EmailAddress"].ToString()))
                    {
                        fileContents = fileContents.Replace("{Email}", dr["EmailAddress"].ToString());
                    }
                    else
                    {
                        fileContents = fileContents.Replace("{Email}", "");
                    }

                }
                else
                {
                    fileContents = fileContents.Replace("{Salutation}", "");
                    fileContents = fileContents.Replace("{Last Name}", "");
                    fileContents = fileContents.Replace("{First Name}", "");
                    fileContents = fileContents.Replace("{Middle Name}", "");
                    fileContents = fileContents.Replace("{Nick Name}", "");
                    fileContents = fileContents.Replace("{Present Address}", "");
                    fileContents = fileContents.Replace("{City}", "");
                    fileContents = fileContents.Replace("{State}", "");
                    fileContents = fileContents.Replace("{Country}", "");
                    fileContents = fileContents.Replace("{Zip Code}", "");
                    fileContents = fileContents.Replace("{Home Phone}", "");

                    fileContents = fileContents.Replace("{Email}", "");

                }
            
              
                byte[] result = createPDF(fileContents.ToString()).GetBuffer();

                Response.Clear();
                Response.AddHeader("Content-Length", result.Length.ToString());
                Response.ContentType = "application/pdf";
                Response.AddHeader("Accept-Ranges", "bytes");
                Response.Buffer = true;
                Response.AddHeader("Expires", "0");
                Response.AddHeader("Cache-Control", "must-revalidate, post-check=0, pre-check=0");
                Response.AddHeader("Pragma", "public");
                Response.AddHeader("content-Transfer-Encoding", "binary");
                string filename = dr["FirstName"].ToString()+"-"+dr["LastName"].ToString();//set Name Of PDF file
              
                Response.AddHeader("Content-Disposition", "attachment; filename=" + filename);
                Response.BinaryWrite(result);
                Response.Flush();
                Response.End();


              

            }
            dr.Close();
            con.Close();
        }
        catch (Exception ex)
        {
            Response.Write(ex.ToString());
        }
  
    }
    private MemoryStream createPDF(string html)
    {
        MemoryStream msOutput = new MemoryStream();
        TextReader reader = new StringReader(html);
        // step 1: creation of a document-object    
        Document document = new Document(PageSize.A4, 0, 0, 50, 50);
      
        // step 2:        // we create a writer that listens to the document
        // and directs a XML-stream to a file  
        PdfWriter writer = PdfWriter.GetInstance(document, msOutput);

       iTextSharp.text.html.simpleparser.StyleSheet styles = new iTextSharp.text.html.simpleparser.StyleSheet();

       styles.LoadStyle("headerdiv", "height", "30px");
       styles.LoadStyle("headerdiv", "font-weight", "bold");
       styles.LoadStyle("headerdiv", "font-size", "20px");
       styles.LoadStyle("headerdiv", "background-color", "Blue");
       styles.LoadStyle("headerdiv", "color", "Blue");
       styles.LoadStyle("headerdiv", "padding-left", "5px");
       styles.LoadStyle("tableclass", "font-family", "Calibri");
       //styles.LoadStyle("tableclass", "font-size", "5px");
       styles.LoadStyle("LableText", "font-weight", "bold");
       //styles.LoadStyle("LableValue", "font-weight", "normal");
       styles.LoadTagStyle("td", "padding", "0 5px 0 5px");
    


       HTMLWorker worker = new HTMLWorker(document);
       worker.SetStyleSheet(styles);


       // step 4: we open document and start the worker on the document
       document.Open();
       worker.StartDocument();
       // step 5: parse the html into the document    
       worker.Parse(reader);
       // step 6: close the document and the worker  
       worker.EndDocument();
       worker.Close();
       document.Close();

        return msOutput;
    }

}

Download sample from here......
Download