Trick for
* disabling anyone to copy screen content
* disabling drag
* disabling select (selection of content)
body ondragstart='return false' onselectstart='return false'>
Monday, June 20, 2011
Export Datagrid Data To Excel ASP.net
private void btnExportToExcel_Click(object sender,
System.EventArgs e)
{
ExportToExcel("Report.xls",DataGrid1);
}
private void ExportToExcel(string strFileName,DataGrid dg)
{ Response.Clear();
Response.Buffer = true;
Response.ContentType = "application/vnd.ms-excel";
Response.AddHeader("content-disposition",
"attachment;filename=" + strFileName);
Response.Charset = "";
this.EnableViewState = false;
System.IO.StringWriter sw = new StringWriter();
System.Web.UI.HtmlTextWriter htw = new HtmlTextWriter(sw);
dg.RenderControl(htw);
Response.Write(sw.ToString());
Response.End();
}
Source: http://dotnetguts.blogspot.com
System.EventArgs e)
{
ExportToExcel("Report.xls",DataGrid1);
}
private void ExportToExcel(string strFileName,DataGrid dg)
{ Response.Clear();
Response.Buffer = true;
Response.ContentType = "application/vnd.ms-excel";
Response.AddHeader("content-disposition",
"attachment;filename=" + strFileName);
Response.Charset = "";
this.EnableViewState = false;
System.IO.StringWriter sw = new StringWriter();
System.Web.UI.HtmlTextWriter htw = new HtmlTextWriter(sw);
dg.RenderControl(htw);
Response.Write(sw.ToString());
Response.End();
}
Source: http://dotnetguts.blogspot.com
Import Excel To Datagrid ASP.net
Working Effectively with Legacy Code
Learn how to find and create seams in your application, no matter "Legacy" it may be, and over time improve application's design. Read more...
private void btnImportExcelToGrid_Click(object sender,
System.EventArgs e)
{
String strConn = "Provider=Microsoft.Jet.OLEDB.4.0;" +
"Data Source=C:\\Book2.xls;" +
"Extended Properties=Excel 8.0;";
DataSet ds = new DataSet();
//You must use the $ after the object
//you reference in the spreadsheet
OleDbDataAdapter da = new OleDbDataAdapter
("SELECT * FROM [Sheet1$]", strConn);
//da.TableMappings.Add("Table", "ExcelTest");
da.Fill(ds);
DataGrid2.DataSource = ds.Tables[0].DefaultView;
DataGrid2.DataBind();
}
Note: If you want to give client upload facility, than first upload the file to the server. Next call the excel file from the following server location.
Source: http://dotnetguts.blogspot.com
Learn how to find and create seams in your application, no matter "Legacy" it may be, and over time improve application's design. Read more...
private void btnImportExcelToGrid_Click(object sender,
System.EventArgs e)
{
String strConn = "Provider=Microsoft.Jet.OLEDB.4.0;" +
"Data Source=C:\\Book2.xls;" +
"Extended Properties=Excel 8.0;";
DataSet ds = new DataSet();
//You must use the $ after the object
//you reference in the spreadsheet
OleDbDataAdapter da = new OleDbDataAdapter
("SELECT * FROM [Sheet1$]", strConn);
//da.TableMappings.Add("Table", "ExcelTest");
da.Fill(ds);
DataGrid2.DataSource = ds.Tables[0].DefaultView;
DataGrid2.DataBind();
}
Note: If you want to give client upload facility, than first upload the file to the server. Next call the excel file from the following server location.
Source: http://dotnetguts.blogspot.com
Basics of Web Services in .net
What is Web Service?
* Web Service is an application that is designed to interact directly with other applications over the internet. In simple sense, Web Services are means for interacting with objects over the Internet.
* Web Service is
o Language Independent
o Protocol Independent
o Platform Independent
o It assumes a stateless service architecture.
* We will discuss more on web service as the article proceed. Before that lets understand bit on how web service comes into picture.
History of Web Service or How Web Service comes into existence?
* As i have mention before that Web Service is nothing but means for Interacting with objects over the Internet.
* 1. Initially Object - Oriented Language comes which allow us to interact with two object within same application.
* 2. Than comes Component Object Model (COM) which allows to interact two objects on the same computer, but in different applications.
* 3. Than comes Distributed Component Object Model (DCOM) which allows to interact two objects on different computers, but within same local network.
* 4. And finally the web services, which allows two object to interact internet. That is it allows to interact between two object on different computers and even not within same local network.
Example of Web Service
* Weather Reporting: You can use Weather Reporting web service to display weather information in your personal website.
* Stock Quote: You can display latest update of Share market with Stock Quote on your web site.
* News Headline: You can display latest news update by using News Headline Web Service in your website.
* In summary you can any use any web service which is available to use. You can make your own web service and let others use it. Example you can make Free SMS Sending Service with footer with your companies advertisement, so whosoever use this service indirectly advertise your company... You can apply your ideas in N no. of ways to take advantage of it.
Web Service Communication
Web Services communicate by using standard web protocols and data formats, such as
* HTTP
* XML
* SOAP
Advantages of Web Service Communication
Web Service messages are formatted as XML, a standard way for communication between two incompatible system. And this message is sent via HTTP, so that they can reach to any machine on the internet without being blocked by firewall.
Terms which are frequently used with web services
* What is SOAP?
o SOAP are remote function calls that invokes method and execute them on Remote machine and translate the object communication into XML format. In short, SOAP are way by which method calls are translate into XML format and sent via HTTP.
* What is WSDL?
o WSDL stands for Web Service Description Language, a standard by which a web service can tell clients what messages it accepts and which results it will return.
o WSDL contains every details regarding using web service
+ Method and Properties provided by web service
+ URLs from which those method can be accessed.
+ Data Types used.
+ Communication Protocol used.
* What is UDDI?
o UDDI allows you to find web services by connecting to a directory.
* What is Discovery or .Disco Files?
o Discovery files are used to group common services together on a web server.
o Discovery files .Disco and .VsDisco are XML based files that contains link in the form of URLs to resources that provides discovery information for a web service.
o .Disco File (static)
+ .Disco File contains
# URL for the WSDL
# URL for the documentation
# URL to which SOAP messages should be sent.
+ A static discovery file is an XML document that contains links to other resources that describe web services.
o .VsDisco File (dynamic)
+ A dynamic discovery files are dynamic discovery document that are automatically generated by VS.Net during the development phase of a web service.
* What is difference between Disco and UDDI?
o Disco is Microsoft's Standard format for discovery documents which contains information about Web Services, while UDDI is a multi-vendor standard for discovery documents which contains information about Web Services.
* What is Web Service Discovery Tool (disco.exe) ?
o The Web Services Discovery Tool (disco.exe) can retrieve discovery information from a server that exposes a web service.
* What is Proxy Class?
o A proxy class is code that looks exactly like the class it meant to represent; however the proxy class doesn't contain any of the application logic. Instead, the proxy class contains marshalling and transport logic.
o A proxy class object allows a client to access a web service as if it were a local COM object.
o The Proxy must be on the computer that has the web application.
* What is Web Service Description Language Tool (wsdl.exe)?
o This tool can take a WSDL file and generate a corresponding proxy class that you can use to invoke the web service.
o Alternate of generating Proxy class through WSDL.exe is you can use web reference. Web Reference automatically generate a proxy classes for a web service by setting a web reference to point to the web service.
o Advantage of using Web Reference as compare to using WSDL.exe Tool is you can update changes done in web service class easily by updating web reference, which is more tedious task with WSDL.exe tool.
* Testing a Web Service?
o You can test web service without building an entire client application.
+ With Asp.net you can simply run the application and test the method by entering valid input paramters.
+ You can also use .Net Web Service Studio Tool comes from Microsoft.
Example of Creating Web Service in .Net
This Web Service will retrieve CustomerList Country Wise and return as dataset to client application for display.
Step1: Create a Web Service Application by File > New > Web Site > Asp.net Web Services
Named the web service, for example here i have choosen name "WSGetCustomerCountryWise"
Step2: Rename the default Service.asmx file to proper name, you also need to switch design view and change the class name with the same name you use to rename the service.asmx.
For example, "WSGetCustomerCountryWise.asmx" and switch to design view and change the class="Service" to class="WSGetCustomerCountryWise"
Step3: Rename the Service.CS File to proper name, you need to change the class name and constructor name too.
For example, "WSGetCustomerCountryWise.CS" and switch to code view and change the class and constructor name to "WSGetCustomerCountryWise"
Step4: Create a Logic for Web Service
* Create a Method "GetCustomerCountryWise"
* Note: You need to specify [WebMethod] before method definition, if you want it to be accessible public, otherwise the method would not be accessible remotely.
* Specify proper argument and return type for method in web service.
* It is also good practise to specify the use "Description" attribute to tell what method is meant for.
For example, here i need to access data of northwind customers and want to return customer list country wise, so add namespace for
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
[WebMethod(Description="It will generate Customer List, Country Wise")] public System.Xml.XmlElement GetCustomerCountryWise(string sCountry)
{
string sConn = ConfigurationManager.ConnectionStrings["connStr"].ToString();
string sSQL = "select CustomerId, CompanyName, ContactTitle, City " +
" from Customers where country = '" + sCountry + "'";
SqlConnection connCustomer = new SqlConnection(sConn);
DataSet dsCustomer = new DataSet();
SqlDataAdapter daCustomer = new SqlDataAdapter(sSQL, sConn);
daCustomer.Fill(dsCustomer,"Customers");
//Known bug while return "DataSet" is "Data source is an invalid type.
It must be either an IListSource, IEnumerable, or IDataSource."
//For more details on Error: http://support.microsoft.com/kb/317340
//So to access data we need to make use of XmlElement.
// Return the DataSet as an XmlElement.
System.Xml.XmlDataDocument xdd = new System.Xml.XmlDataDocument(dsCustomer);
System.Xml.XmlElement docElem = xdd.DocumentElement;
return docElem;
}
Step5: Build Web Service and Run the Web Service for testing by pressing F5 function key.
By pressing "Invoke" button will generate XML File.
So you are done creating web service application.
Example of Testing Web Service in .Net
This Web Service will display the information which had been retrieved from Remote computer by accessing public method "GetCustomerCountryWise".
Step1: Create a Test Web Site by File > New > Web Site > Asp.net Web Site
Named the web site, for example here i have choosen name "TestGetCustomerCountryWise"
Step2: Displaying data in gridview, so drag the gridview on to the form.
Step3: Right Click Solution Explorer and Choose "Add Web Reference"
Step4: Choose the option Web Service on the local machine or you can enter the .WSDL File address directly in URL space and press Go button.
Step5: Press "Add Reference button"
Step6: Writing Code for Displaying data in GridView
Here note: I have Pass "USA" as parameter in Country Field.
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
//Create object of WSGetCustomerCountryWise Object
localhost.WSGetCustomerCountryWise objGetCustomerCountryWise
= new localhost.WSGetCustomerCountryWise();
DataSet dsCustomer = new DataSet();
// Get the data from Webservice.
XmlElement elem = objGetCustomerCountryWise.GetCustomerCountryWise("USA");
// Load the XML to the Typed DataSet that you want.
XmlNodeReader nodeReader = new XmlNodeReader(elem);
dsCustomer.ReadXml(nodeReader, XmlReadMode.Auto);
GridView1.DataSource = dsCustomer;
GridView1.DataBind();
}
}
Few Facts about Web Service in .Net
* Each Response from web service is a new object, with a new state.
* Web Service are asynchronous because the request object from the client application and the response object from the web service are unique SOAP envelopes that do not require shared connection.
* This allow client application and the web service to continue processing while the interaction is ongoing.
* Instead of a user interface, it provides a standard defined interface called a contract.
Source: http://dotnetguts.blogspot.com
* Web Service is an application that is designed to interact directly with other applications over the internet. In simple sense, Web Services are means for interacting with objects over the Internet.
* Web Service is
o Language Independent
o Protocol Independent
o Platform Independent
o It assumes a stateless service architecture.
* We will discuss more on web service as the article proceed. Before that lets understand bit on how web service comes into picture.
History of Web Service or How Web Service comes into existence?
* As i have mention before that Web Service is nothing but means for Interacting with objects over the Internet.
* 1. Initially Object - Oriented Language comes which allow us to interact with two object within same application.
* 2. Than comes Component Object Model (COM) which allows to interact two objects on the same computer, but in different applications.
* 3. Than comes Distributed Component Object Model (DCOM) which allows to interact two objects on different computers, but within same local network.
* 4. And finally the web services, which allows two object to interact internet. That is it allows to interact between two object on different computers and even not within same local network.
Example of Web Service
* Weather Reporting: You can use Weather Reporting web service to display weather information in your personal website.
* Stock Quote: You can display latest update of Share market with Stock Quote on your web site.
* News Headline: You can display latest news update by using News Headline Web Service in your website.
* In summary you can any use any web service which is available to use. You can make your own web service and let others use it. Example you can make Free SMS Sending Service with footer with your companies advertisement, so whosoever use this service indirectly advertise your company... You can apply your ideas in N no. of ways to take advantage of it.
Web Service Communication
Web Services communicate by using standard web protocols and data formats, such as
* HTTP
* XML
* SOAP
Advantages of Web Service Communication
Web Service messages are formatted as XML, a standard way for communication between two incompatible system. And this message is sent via HTTP, so that they can reach to any machine on the internet without being blocked by firewall.
Terms which are frequently used with web services
* What is SOAP?
o SOAP are remote function calls that invokes method and execute them on Remote machine and translate the object communication into XML format. In short, SOAP are way by which method calls are translate into XML format and sent via HTTP.
* What is WSDL?
o WSDL stands for Web Service Description Language, a standard by which a web service can tell clients what messages it accepts and which results it will return.
o WSDL contains every details regarding using web service
+ Method and Properties provided by web service
+ URLs from which those method can be accessed.
+ Data Types used.
+ Communication Protocol used.
* What is UDDI?
o UDDI allows you to find web services by connecting to a directory.
* What is Discovery or .Disco Files?
o Discovery files are used to group common services together on a web server.
o Discovery files .Disco and .VsDisco are XML based files that contains link in the form of URLs to resources that provides discovery information for a web service.
o .Disco File (static)
+ .Disco File contains
# URL for the WSDL
# URL for the documentation
# URL to which SOAP messages should be sent.
+ A static discovery file is an XML document that contains links to other resources that describe web services.
o .VsDisco File (dynamic)
+ A dynamic discovery files are dynamic discovery document that are automatically generated by VS.Net during the development phase of a web service.
* What is difference between Disco and UDDI?
o Disco is Microsoft's Standard format for discovery documents which contains information about Web Services, while UDDI is a multi-vendor standard for discovery documents which contains information about Web Services.
* What is Web Service Discovery Tool (disco.exe) ?
o The Web Services Discovery Tool (disco.exe) can retrieve discovery information from a server that exposes a web service.
* What is Proxy Class?
o A proxy class is code that looks exactly like the class it meant to represent; however the proxy class doesn't contain any of the application logic. Instead, the proxy class contains marshalling and transport logic.
o A proxy class object allows a client to access a web service as if it were a local COM object.
o The Proxy must be on the computer that has the web application.
* What is Web Service Description Language Tool (wsdl.exe)?
o This tool can take a WSDL file and generate a corresponding proxy class that you can use to invoke the web service.
o Alternate of generating Proxy class through WSDL.exe is you can use web reference. Web Reference automatically generate a proxy classes for a web service by setting a web reference to point to the web service.
o Advantage of using Web Reference as compare to using WSDL.exe Tool is you can update changes done in web service class easily by updating web reference, which is more tedious task with WSDL.exe tool.
* Testing a Web Service?
o You can test web service without building an entire client application.
+ With Asp.net you can simply run the application and test the method by entering valid input paramters.
+ You can also use .Net Web Service Studio Tool comes from Microsoft.
Example of Creating Web Service in .Net
This Web Service will retrieve CustomerList Country Wise and return as dataset to client application for display.
Step1: Create a Web Service Application by File > New > Web Site > Asp.net Web Services
Named the web service, for example here i have choosen name "WSGetCustomerCountryWise"
Step2: Rename the default Service.asmx file to proper name, you also need to switch design view and change the class name with the same name you use to rename the service.asmx.
For example, "WSGetCustomerCountryWise.asmx" and switch to design view and change the class="Service" to class="WSGetCustomerCountryWise"
Step3: Rename the Service.CS File to proper name, you need to change the class name and constructor name too.
For example, "WSGetCustomerCountryWise.CS" and switch to code view and change the class and constructor name to "WSGetCustomerCountryWise"
Step4: Create a Logic for Web Service
* Create a Method "GetCustomerCountryWise"
* Note: You need to specify [WebMethod] before method definition, if you want it to be accessible public, otherwise the method would not be accessible remotely.
* Specify proper argument and return type for method in web service.
* It is also good practise to specify the use "Description" attribute to tell what method is meant for.
For example, here i need to access data of northwind customers and want to return customer list country wise, so add namespace for
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
[WebMethod(Description="It will generate Customer List, Country Wise")] public System.Xml.XmlElement GetCustomerCountryWise(string sCountry)
{
string sConn = ConfigurationManager.ConnectionStrings["connStr"].ToString();
string sSQL = "select CustomerId, CompanyName, ContactTitle, City " +
" from Customers where country = '" + sCountry + "'";
SqlConnection connCustomer = new SqlConnection(sConn);
DataSet dsCustomer = new DataSet();
SqlDataAdapter daCustomer = new SqlDataAdapter(sSQL, sConn);
daCustomer.Fill(dsCustomer,"Customers");
//Known bug while return "DataSet" is "Data source is an invalid type.
It must be either an IListSource, IEnumerable, or IDataSource."
//For more details on Error: http://support.microsoft.com/kb/317340
//So to access data we need to make use of XmlElement.
// Return the DataSet as an XmlElement.
System.Xml.XmlDataDocument xdd = new System.Xml.XmlDataDocument(dsCustomer);
System.Xml.XmlElement docElem = xdd.DocumentElement;
return docElem;
}
Step5: Build Web Service and Run the Web Service for testing by pressing F5 function key.
By pressing "Invoke" button will generate XML File.
So you are done creating web service application.
Example of Testing Web Service in .Net
This Web Service will display the information which had been retrieved from Remote computer by accessing public method "GetCustomerCountryWise".
Step1: Create a Test Web Site by File > New > Web Site > Asp.net Web Site
Named the web site, for example here i have choosen name "TestGetCustomerCountryWise"
Step2: Displaying data in gridview, so drag the gridview on to the form.
Step3: Right Click Solution Explorer and Choose "Add Web Reference"
Step4: Choose the option Web Service on the local machine or you can enter the .WSDL File address directly in URL space and press Go button.
Step5: Press "Add Reference button"
Step6: Writing Code for Displaying data in GridView
Here note: I have Pass "USA" as parameter in Country Field.
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
//Create object of WSGetCustomerCountryWise Object
localhost.WSGetCustomerCountryWise objGetCustomerCountryWise
= new localhost.WSGetCustomerCountryWise();
DataSet dsCustomer = new DataSet();
// Get the data from Webservice.
XmlElement elem = objGetCustomerCountryWise.GetCustomerCountryWise("USA");
// Load the XML to the Typed DataSet that you want.
XmlNodeReader nodeReader = new XmlNodeReader(elem);
dsCustomer.ReadXml(nodeReader, XmlReadMode.Auto);
GridView1.DataSource = dsCustomer;
GridView1.DataBind();
}
}
Few Facts about Web Service in .Net
* Each Response from web service is a new object, with a new state.
* Web Service are asynchronous because the request object from the client application and the response object from the web service are unique SOAP envelopes that do not require shared connection.
* This allow client application and the web service to continue processing while the interaction is ongoing.
* Instead of a user interface, it provides a standard defined interface called a contract.
Source: http://dotnetguts.blogspot.com
Understanding DateTime and TimeSpan in .Net
//Creating Two Instance of DateTime
DateTime dt1 = new DateTime();
DateTime dt2 = new DateTime();
//Initializing DateTime Object
dt1 = DateTime.Now.Date; //Initializing with Current Date
Response.Write(dt1.ToString() + "
");
//Output: 22-06-2007 00:00:00
//Examples for DateTime Manipulation in .Net
//Example 1 : Adding Minutes to Current Date.
dt1 = dt1.AddMinutes(5.0);
Response.Write(dt1.ToString() + "
");
//Output: 22-06-2007 00:05:00
//Example 2 : Adding Seconds to DateTime Object., similarly you can add milliseconds
dt1 = dt1.AddSeconds(30.0);
Response.Write(dt1.ToString() + "
");
//Output: 22-06-2007 00:05:30
//Example 3 : Adding Hours to DateTime Object in .Net.
dt1 = dt1.AddHours(5.0);
Response.Write(dt1.ToString() + "
");
//Output: 22-06-2007 05:05:30
//Example 4 : Adding Time to DateTime Object.
//You can replace Example 1,2 and 3 by simply adding TimeSpan with your desired
//TimeSpan value.
//Here we are adding 5 Hours, 5 Minutes and 30 Seconds.
dt1 = dt1.Add(new TimeSpan(5,5,30));
Response.Write(dt1.ToString() + "
");
//Output: 22-06-2007 10:11:00
//Example 5 : Adding Days to DateTime Object in .Net
dt2 = dt1.AddDays(7.0); //Initializing dt2 object with 7 days ahead from
//dt1 DateTime value.
Response.Write(dt2.ToString() + "
");
//Output: 29-06-2007 10:11:00
//Example 6 : Adding Month to DateTime Object
dt2 = dt2.AddMonths(1);
Response.Write(dt2.ToString() + "
");
//Output: 29-07-2007 10:11:00
//Example 7 : Adding Year to DateTime Object
dt2 = dt2.AddYears(1);
Response.Write(dt2.ToString() + "
");
//Output: 29-07-2008 10:11:00
//Examples of Retrieving DateTime object value.
//Example 1 : Get Day value.
int intDay = dt1.Day;
Response.Write(intDay.ToString() + "
");
//Output: 22
//Example 2 : Get Day of Week.
DayOfWeek dow = dt1.DayOfWeek;
Response.Write(dow.ToString() + "
");
//Output: Friday
//How to find whether day of week is sunday or saturday?
if(dow == DayOfWeek.Sunday dow == DayOfWeek.Saturday)
{
//Hurray its weekend.
}
//Example 3 : Get the Day of Year
int intYear = dt1.DayOfYear; //Similarly you can get Year value.
Response.Write(intYear.ToString() + "
");
//Output: 173
//Similarly you can get Hours, Minutes, Seconds, Milliseconds value.
//Conversion of String to DateTime
//Make use of Parse Method of DateTime to "Convert String to DateTime in .Net"
DateTime dt4 = DateTime.Parse("08/06/2007");
DateTime dt5 = DateTime.Parse("10/06/2007");
//Comparing Date
//How to Find whether both dates are equal or Not?
//How to compare two dates in .Net?
if (DateTime.Compare(dt4, dt5) == 0)
{
Response.Write("Both Dates are Equal" + "
");
}
else if (DateTime.Compare(dt4, dt5) < 0) { Response.Write(dt4.ToString() + " is Less than " + dt5.ToString() + "
");
}
else
{
Response.Write(dt4.ToString() + " is Greater than "
+ dt5.ToString() + "
");
}
//Output: 08-06-2007 00:00:00 is Less than 10-06-2007 00:00:00
/*Note: You may recieve error: "String was not recognized as a valid
DateTime." This may be occur as in India the DateTime format is followed
as "dd/mm/yyyy" But let say if you are in USA than it follow "mm/dd/yyyy" so here
there is crash situation and so you might recieve above error, so to avoid such
error make sure that user input valid date before you Parse date. */
//Difference between Date
//How to Find difference between two dates in .Net?
//How to Find days difference between two dates in .Net?
//How to subtract one date from another?
TimeSpan tsDiff = dt5.Subtract(dt4); //Note: Always subtract smaller date
//value from greater date
Response.Write("Difference between " + dt4.ToString() + " and " +
dt5.ToString() + " is " + tsDiff.Days.ToString() + " days." + "
");
//Output: Difference between 08-06-2007 00:00:00 and 10-06-2007 00:00:00 is 2 days.
//Similarly you can also find:
//How many hour difference between two dates
//How many seconds difference between two dates
//And so on... by changing tsDiff property value to hours, seconds....
//instead of tsDiff.Days.
//Compare Time
//How to Find whether both Time are equal or Not?
//How to compare Time in .Net?
dt4 = DateTime.Parse("4:30 AM");
dt5 = DateTime.Parse("7:30 PM");
if (DateTime.Compare(dt4, dt5) == 0)
{
Response.Write("Both Times are Equal" + "
");
}
else if (DateTime.Compare(dt4, dt5) < 0) { Response.Write(dt4.ToShortTimeString() + " is Less than " + dt5.ToShortTimeString() + "
");
}
else
{
Response.Write(dt4.ToShortTimeString() + " is Greater than "
+ dt5.ToShortTimeString() + "
");
}
//Output: 04:30:00 is Less than 19:30:00
//Difference between Time
//How to Find difference between two Time value in .Net?
//How to Find Hours difference between two Time in .Net?
//How to subtract one Time from another?
//How to find elapsed Time between Two Time value in .Net?
tsDiff = dt5.Subtract(dt4); //Note: Always subtract smaller date
//value from greater date
Response.Write("Difference between " + dt4.ToString() + " and " + dt5.ToString() + " is " + tsDiff.Hours.ToString() + " Hours." + "
");
//Output: Difference between 22-06-2007 04:30:00 and 22-06-2007 19:30:00 is 15 Hours.
//More on DateTime
//How many days in a given month in .Net?
int intDaysInMonth = DateTime.DaysInMonth(2007, 6); //Pass valid year, and month
Response.Write(intDaysInMonth.ToString() + "
");
//Output: 30
//How to find whether given year is Leap year or not in .Net?
Response.Write( DateTime.IsLeapYear(2007)); //Pass valid year
//Output: False
//How to find current date and time?
Response.Write("Current Date and Time: " + DateTime.Now + "
");
//Output: Current Date and Time: 22-06-2007 11:31:04
//How to find current date?
Response.Write("Current Date: " + DateTime.Today + "
");
//Output: Current Date: 22-06-2007 00:00:00
Source: http://dotnetguts.blogspot.com
DateTime dt1 = new DateTime();
DateTime dt2 = new DateTime();
//Initializing DateTime Object
dt1 = DateTime.Now.Date; //Initializing with Current Date
Response.Write(dt1.ToString() + "
");
//Output: 22-06-2007 00:00:00
//Examples for DateTime Manipulation in .Net
//Example 1 : Adding Minutes to Current Date.
dt1 = dt1.AddMinutes(5.0);
Response.Write(dt1.ToString() + "
");
//Output: 22-06-2007 00:05:00
//Example 2 : Adding Seconds to DateTime Object., similarly you can add milliseconds
dt1 = dt1.AddSeconds(30.0);
Response.Write(dt1.ToString() + "
");
//Output: 22-06-2007 00:05:30
//Example 3 : Adding Hours to DateTime Object in .Net.
dt1 = dt1.AddHours(5.0);
Response.Write(dt1.ToString() + "
");
//Output: 22-06-2007 05:05:30
//Example 4 : Adding Time to DateTime Object.
//You can replace Example 1,2 and 3 by simply adding TimeSpan with your desired
//TimeSpan value.
//Here we are adding 5 Hours, 5 Minutes and 30 Seconds.
dt1 = dt1.Add(new TimeSpan(5,5,30));
Response.Write(dt1.ToString() + "
");
//Output: 22-06-2007 10:11:00
//Example 5 : Adding Days to DateTime Object in .Net
dt2 = dt1.AddDays(7.0); //Initializing dt2 object with 7 days ahead from
//dt1 DateTime value.
Response.Write(dt2.ToString() + "
");
//Output: 29-06-2007 10:11:00
//Example 6 : Adding Month to DateTime Object
dt2 = dt2.AddMonths(1);
Response.Write(dt2.ToString() + "
");
//Output: 29-07-2007 10:11:00
//Example 7 : Adding Year to DateTime Object
dt2 = dt2.AddYears(1);
Response.Write(dt2.ToString() + "
");
//Output: 29-07-2008 10:11:00
//Examples of Retrieving DateTime object value.
//Example 1 : Get Day value.
int intDay = dt1.Day;
Response.Write(intDay.ToString() + "
");
//Output: 22
//Example 2 : Get Day of Week.
DayOfWeek dow = dt1.DayOfWeek;
Response.Write(dow.ToString() + "
");
//Output: Friday
//How to find whether day of week is sunday or saturday?
if(dow == DayOfWeek.Sunday dow == DayOfWeek.Saturday)
{
//Hurray its weekend.
}
//Example 3 : Get the Day of Year
int intYear = dt1.DayOfYear; //Similarly you can get Year value.
Response.Write(intYear.ToString() + "
");
//Output: 173
//Similarly you can get Hours, Minutes, Seconds, Milliseconds value.
//Conversion of String to DateTime
//Make use of Parse Method of DateTime to "Convert String to DateTime in .Net"
DateTime dt4 = DateTime.Parse("08/06/2007");
DateTime dt5 = DateTime.Parse("10/06/2007");
//Comparing Date
//How to Find whether both dates are equal or Not?
//How to compare two dates in .Net?
if (DateTime.Compare(dt4, dt5) == 0)
{
Response.Write("Both Dates are Equal" + "
");
}
else if (DateTime.Compare(dt4, dt5) < 0) { Response.Write(dt4.ToString() + " is Less than " + dt5.ToString() + "
");
}
else
{
Response.Write(dt4.ToString() + " is Greater than "
+ dt5.ToString() + "
");
}
//Output: 08-06-2007 00:00:00 is Less than 10-06-2007 00:00:00
/*Note: You may recieve error: "String was not recognized as a valid
DateTime." This may be occur as in India the DateTime format is followed
as "dd/mm/yyyy" But let say if you are in USA than it follow "mm/dd/yyyy" so here
there is crash situation and so you might recieve above error, so to avoid such
error make sure that user input valid date before you Parse date. */
//Difference between Date
//How to Find difference between two dates in .Net?
//How to Find days difference between two dates in .Net?
//How to subtract one date from another?
TimeSpan tsDiff = dt5.Subtract(dt4); //Note: Always subtract smaller date
//value from greater date
Response.Write("Difference between " + dt4.ToString() + " and " +
dt5.ToString() + " is " + tsDiff.Days.ToString() + " days." + "
");
//Output: Difference between 08-06-2007 00:00:00 and 10-06-2007 00:00:00 is 2 days.
//Similarly you can also find:
//How many hour difference between two dates
//How many seconds difference between two dates
//And so on... by changing tsDiff property value to hours, seconds....
//instead of tsDiff.Days.
//Compare Time
//How to Find whether both Time are equal or Not?
//How to compare Time in .Net?
dt4 = DateTime.Parse("4:30 AM");
dt5 = DateTime.Parse("7:30 PM");
if (DateTime.Compare(dt4, dt5) == 0)
{
Response.Write("Both Times are Equal" + "
");
}
else if (DateTime.Compare(dt4, dt5) < 0) { Response.Write(dt4.ToShortTimeString() + " is Less than " + dt5.ToShortTimeString() + "
");
}
else
{
Response.Write(dt4.ToShortTimeString() + " is Greater than "
+ dt5.ToShortTimeString() + "
");
}
//Output: 04:30:00 is Less than 19:30:00
//Difference between Time
//How to Find difference between two Time value in .Net?
//How to Find Hours difference between two Time in .Net?
//How to subtract one Time from another?
//How to find elapsed Time between Two Time value in .Net?
tsDiff = dt5.Subtract(dt4); //Note: Always subtract smaller date
//value from greater date
Response.Write("Difference between " + dt4.ToString() + " and " + dt5.ToString() + " is " + tsDiff.Hours.ToString() + " Hours." + "
");
//Output: Difference between 22-06-2007 04:30:00 and 22-06-2007 19:30:00 is 15 Hours.
//More on DateTime
//How many days in a given month in .Net?
int intDaysInMonth = DateTime.DaysInMonth(2007, 6); //Pass valid year, and month
Response.Write(intDaysInMonth.ToString() + "
");
//Output: 30
//How to find whether given year is Leap year or not in .Net?
Response.Write( DateTime.IsLeapYear(2007)); //Pass valid year
//Output: False
//How to find current date and time?
Response.Write("Current Date and Time: " + DateTime.Now + "
");
//Output: Current Date and Time: 22-06-2007 11:31:04
//How to find current date?
Response.Write("Current Date: " + DateTime.Today + "
");
//Output: Current Date: 22-06-2007 00:00:00
Source: http://dotnetguts.blogspot.com
What is WPF
WPF is Windows Presentation Foundation Framework that shipped as part of the .NET Framework 3.0 . First it has shipped with Windows Vista OS in built, and is re-distributable for Windows XP or Windows Server 2008.
WPF is Object Oriented , XAML based.
* It Uses DirectX Engine for rendering GUI
* It do not use GDI 32 programming at all as opposed to Win32 applications
* It do not require more time or cost for graphics, drawing or animation programming
* It is Easy to change resolution unlike win32 application
* It is XAML Friendly.
* It has .NET API that has integrated to XAML (Xtensible Application Markup Language)
* Easily select the Controls unlike Win32 Controls.
* It has the ability to create 3D graphics in windows apps
* It contains Separate API for graphics and animation
* Most powerful Windows UI Framework
It is used for the
* For the better User Interface & the Design
* Customization of Controls
* Integrating Flash, Direct, Win32, Windows Forms
* For Generic consistency professional look (Using Styles like CSS in Web)
WPF Provides an unified Model for producing high end GUI easily using normal XML syntax to render output on graphics devices than using GDI components.
Source: http://beyondrelational.com
WPF is Object Oriented , XAML based.
* It Uses DirectX Engine for rendering GUI
* It do not use GDI 32 programming at all as opposed to Win32 applications
* It do not require more time or cost for graphics, drawing or animation programming
* It is Easy to change resolution unlike win32 application
* It is XAML Friendly.
* It has .NET API that has integrated to XAML (Xtensible Application Markup Language)
* Easily select the Controls unlike Win32 Controls.
* It has the ability to create 3D graphics in windows apps
* It contains Separate API for graphics and animation
* Most powerful Windows UI Framework
It is used for the
* For the better User Interface & the Design
* Customization of Controls
* Integrating Flash, Direct, Win32, Windows Forms
* For Generic consistency professional look (Using Styles like CSS in Web)
WPF Provides an unified Model for producing high end GUI easily using normal XML syntax to render output on graphics devices than using GDI components.
Source: http://beyondrelational.com
disable double Click on Web Page
Some time we face a problem like when we click on the server side button twice or more time ,it call a button event more then one time for single calling .some time it makes problem in our logic .so we need a solution code which hold the page till the server respond the single request .
Here i am placing a code which is useful in this case.
script type="text/javascript">
function pageLoad(sender, args) {
var rm = Sys.WebForms.PageRequestManager.getInstance();
rm.add_initializeRequest(initializeRequest);
rm.add_endRequest(endRequest);
}
function initializeRequest(sender, args) {
//Disable button to prevent double submit
var btn = $get(args._postBackElement.id);
if (btn) {
btn.disabled = true;
if (btn.className == 'button')
btn.className = 'buttonDisabled';
}
}
function endRequest(sender, args) {
//Re-enable button
var btn = $get(sender._postBackSettings.sourceElement.id);
if (btn) {
btn.disabled = false;
if (btn.className == 'buttonDisabled')
btn.className = 'button';
}
}
/script>
Source: http://itneeds4u.blogspot.com/
Here i am placing a code which is useful in this case.
script type="text/javascript">
function pageLoad(sender, args) {
var rm = Sys.WebForms.PageRequestManager.getInstance();
rm.add_initializeRequest(initializeRequest);
rm.add_endRequest(endRequest);
}
function initializeRequest(sender, args) {
//Disable button to prevent double submit
var btn = $get(args._postBackElement.id);
if (btn) {
btn.disabled = true;
if (btn.className == 'button')
btn.className = 'buttonDisabled';
}
}
function endRequest(sender, args) {
//Re-enable button
var btn = $get(sender._postBackSettings.sourceElement.id);
if (btn) {
btn.disabled = false;
if (btn.className == 'buttonDisabled')
btn.className = 'button';
}
}
/script>
Source: http://itneeds4u.blogspot.com/
Connection Pooling in ADO.NET
Why go for Connection Pooling?
Establishing connection to a database is cumbersome and resource burning, most important job in the applications, sometimes it might be slow. Most of the applications need to execute any query on the database server, a connection need to be established. Knowing about the Connection Pooling concepts and tips will definitely improves the performance while connecting to the database and the same time solves the requirement.
Connection Pooling at a glance?
Connection Pooling is the ability to reuse the database connection for more than one user. That connection might be SQL, OLEDB, ORACLE or whatever. This way of organizing connections in a smarter manner improves performance as the applications do not need to open and close the connection multiple times.
All of us know that we declare the connection string in web.config as follows in .NET Application and make use of this in code behind while connecting to databases.
view source
print?
1.
2.
5.
When the connection is closed or disposed in ADO.NET, it is returned to the connection pool and remains idle for until a request for a new connection comes in. If none comes in within this period, the connection to the backend is closed and the connection instance is removed from the Connection Pool. If all the connections are in the pool are busy then new connection waits in the queue for the existing connections to be released .We can set max connections, connection Pool size, Connection Time out etc settings in the web.config.
The following key value pairs explain the connection pooling settings.
* Connection Lifetime - The time of Connection Creation will be compared to the current time. If this period exceeds the Connection Lifetime value that is set, then object pooler destroys the connection. The default value is 0; this will give the maximum timeout for connection.
* Connection Reset - To reset the connection after it was take out from the Connection pool. The default value is true.
* Max pool size - Maximum number of connections allowed within the Connection pool. The value is 100 by default.
* Min pool size - Minimum number of connections allowed within the Connection pool. The value is 0 by default.
* Pooling - To set the connection Pooling if it is true, the connection is drawn from the pool or created if no connection available from the pool. The value is true by default.
* Connection Timeout - Maximum Time (in secs) to wait for a free connection from the pool. The value is 15 by default.
* Incr Pool Size - Controls the number of connections which are established, when all the connections are used. The value is 5 by default
* Decr Pool Size - Controls the number of connections which are closed when most of the established connections are unused. The value is 1 by default
Points to Ponder
* Disabling the connection pooling, infers that the connection object that is created by the user will not be re-used to any other user.
* A Connection pool will be created when Open() method of connection object is called. If the same application is using multiple Connection Strings (say more than one) then multiple connection pools will be created corresponding to each connection string.
* Connection Pooling is applied in ADO.Net by default.
* Connections that are not explicitly closed are not added or returned to the pool. Hence The Close() or Dispose() method of Connection need to be called to close the connection.
* A Connection Pool is freed from the memory when the last connection to the database is closed.
* Connection Pool’s life time is ended as soon as the application domain is unloaded. For example at any time when IISRESET runs the Connection Pool gets destroyed
* Connection Pools cannot be shared across application domains.
The best practice Code
The below code is the best practice that is recommended to use.
view source
print?
01.Try
02.{
03. SqlConnection _sqlConnection = new SqlConnection();
04. _sqlConnection.ConnectionString = ConfigurationManager.ConnectionStrings["sqlConnectionString"].ToString();
05.
06. if (_sqlConnection.State = ConnectionState.Closed)
07. _sqlConnection.Open();
08.
09. /*Do some Operations … */
10.}
11.catch (Exception ex)
12.{
13. /*Do something */
14.}
15.finally
16.{
17. if (_sqlConnection.State != ConnectionState.Closed)
18. _sqlConnection.Close();
19.}
Connection Pooling improves the performance of the data driven B2B applications as we save some time in reusing the existing active database connections. I will be explaining it in more detail in my next article.
Source: http://beyondrelational.com
Establishing connection to a database is cumbersome and resource burning, most important job in the applications, sometimes it might be slow. Most of the applications need to execute any query on the database server, a connection need to be established. Knowing about the Connection Pooling concepts and tips will definitely improves the performance while connecting to the database and the same time solves the requirement.
Connection Pooling at a glance?
Connection Pooling is the ability to reuse the database connection for more than one user. That connection might be SQL, OLEDB, ORACLE or whatever. This way of organizing connections in a smarter manner improves performance as the applications do not need to open and close the connection multiple times.
All of us know that we declare the connection string in web.config as follows in .NET Application and make use of this in code behind while connecting to databases.
view source
print?
1.
2.
5.
When the connection is closed or disposed in ADO.NET, it is returned to the connection pool and remains idle for until a request for a new connection comes in. If none comes in within this period, the connection to the backend is closed and the connection instance is removed from the Connection Pool. If all the connections are in the pool are busy then new connection waits in the queue for the existing connections to be released .We can set max connections, connection Pool size, Connection Time out etc settings in the web.config.
The following key value pairs explain the connection pooling settings.
* Connection Lifetime - The time of Connection Creation will be compared to the current time. If this period exceeds the Connection Lifetime value that is set, then object pooler destroys the connection. The default value is 0; this will give the maximum timeout for connection.
* Connection Reset - To reset the connection after it was take out from the Connection pool. The default value is true.
* Max pool size - Maximum number of connections allowed within the Connection pool. The value is 100 by default.
* Min pool size - Minimum number of connections allowed within the Connection pool. The value is 0 by default.
* Pooling - To set the connection Pooling if it is true, the connection is drawn from the pool or created if no connection available from the pool. The value is true by default.
* Connection Timeout - Maximum Time (in secs) to wait for a free connection from the pool. The value is 15 by default.
* Incr Pool Size - Controls the number of connections which are established, when all the connections are used. The value is 5 by default
* Decr Pool Size - Controls the number of connections which are closed when most of the established connections are unused. The value is 1 by default
Points to Ponder
* Disabling the connection pooling, infers that the connection object that is created by the user will not be re-used to any other user.
* A Connection pool will be created when Open() method of connection object is called. If the same application is using multiple Connection Strings (say more than one) then multiple connection pools will be created corresponding to each connection string.
* Connection Pooling is applied in ADO.Net by default.
* Connections that are not explicitly closed are not added or returned to the pool. Hence The Close() or Dispose() method of Connection need to be called to close the connection.
* A Connection Pool is freed from the memory when the last connection to the database is closed.
* Connection Pool’s life time is ended as soon as the application domain is unloaded. For example at any time when IISRESET runs the Connection Pool gets destroyed
* Connection Pools cannot be shared across application domains.
The best practice Code
The below code is the best practice that is recommended to use.
view source
print?
01.Try
02.{
03. SqlConnection _sqlConnection = new SqlConnection();
04. _sqlConnection.ConnectionString = ConfigurationManager.ConnectionStrings["sqlConnectionString"].ToString();
05.
06. if (_sqlConnection.State = ConnectionState.Closed)
07. _sqlConnection.Open();
08.
09. /*Do some Operations … */
10.}
11.catch (Exception ex)
12.{
13. /*Do something */
14.}
15.finally
16.{
17. if (_sqlConnection.State != ConnectionState.Closed)
18. _sqlConnection.Close();
19.}
Connection Pooling improves the performance of the data driven B2B applications as we save some time in reusing the existing active database connections. I will be explaining it in more detail in my next article.
Source: http://beyondrelational.com
All about Generics in C#
Introduction
Generics in C# are an extension to C# Programming using Generic Types and Methods. I see most of the developers still get confused about generics and do not know to use them in real time projects. That made me to write this article to help understand and refer how to use them?
Basic concept is similar to Templates in C++ with better extensibility and usability. The C++ Templates are compile time Feature whereas Generics is a feature of runtime.
These are a type of data structure that contains code, remains the same. The data type of the parameters will change for each use. We can also call them parameterized types or parametric polymorphism. Generics allow classes, structs, interfaces, delegates, and methods to be parameterized by the types of data they store.
The usage within the data structure adapts to the different data type of the passed variables. This Allows defining type-safe data structures need less committing to actual data types. We reuse data processing algorithms without duplicating type-specific code.
System.Collections.Generic
The System.Collections.Generic namespace contains several generic collection classes based on generics and it is recommended that we should use these collection classes in place of the earlier non-generic ones for better performance of our applications.
The namespace contains a lot of generic classes, structures, and interfaces like
* Dictionary
* List
* Queue
* SortedDictionary
* Stack
Examples
view source
print?
public class Gen
{
T t;
public T Val
{
get;
set;
}
}
The class name " Gencontaining the Type. This Type "T" is used to show that if we need to refer to the actual Type that is going to be used when we write this class".
T t; Creates member of the type T
The generic Type that we will specify during construction of the class will get inserted by the Common Language Runtime (CLR). The final item in the class is the public property. Again, notice that we are using the Type placeholder "T" to represent that generic type for the type of that property. Also notice that we can freely use the private variable "t" within the class.
In order to use this class to hold any Type, we simply need to create a new instance of our new Type, providing the name of the Type within the "<>" brackets and then use that class in a Type-safe manner as shown below.
view source
print?
static void Main(string[] args)
{
//create a string version of our generic class
Gen str = new Gen();
//set the value for the string type
str.Val = "Beyond Relational";
//output the type and value
System.Console.WriteLine(str.Val);
System.Console.WriteLine(str.Val.GetType());
//create another instance of our generic class, using a different type
Gen flt = new Gen();
flt.Val = 12.34;
System.Console.WriteLine(flt.Val);
//output
System.Console.WriteLine(flt.Val.GetType());
Console.ReadLine();
}
}
Generic Collections
view source
print?
public class MessageElement
{
//some functionality
}
public class MessageSearchCriteria
{
// some functioanlity
}
public List ListMessageElement
{
get
{
return lstMsgElemet;
}
set
{
lstMsgElemet = value;
}
}
MessageSearchCriteria objMsgSearch = new MessageSearchCriteria();
//usage of generics
objMsgSearch.ListMessageElement = new List();
Advantages
* Help to make the code in the software components much more reusable.
* High Quality Code and Code Maintainability
* No runtime Casting No Boxing hence Allows Performance Efficiency
* Creates Type safe at compile time as generics specify type at runtime
* Programmer has stronger and flexible control over the code
* The stronger type checking associated with generics helps in finding errors easily at compile time only.
* No code Duplication
Generics refer to classes and methods that work consistently on values of different types
Generics in C# are an extension to C# Programming using Generic Types and Methods. I see most of the developers still get confused about generics and do not know to use them in real time projects. That made me to write this article to help understand and refer how to use them?
Basic concept is similar to Templates in C++ with better extensibility and usability. The C++ Templates are compile time Feature whereas Generics is a feature of runtime.
These are a type of data structure that contains code, remains the same. The data type of the parameters will change for each use. We can also call them parameterized types or parametric polymorphism. Generics allow classes, structs, interfaces, delegates, and methods to be parameterized by the types of data they store.
The usage within the data structure adapts to the different data type of the passed variables. This Allows defining type-safe data structures need less committing to actual data types. We reuse data processing algorithms without duplicating type-specific code.
System.Collections.Generic
The System.Collections.Generic namespace contains several generic collection classes based on generics and it is recommended that we should use these collection classes in place of the earlier non-generic ones for better performance of our applications.
The namespace contains a lot of generic classes, structures, and interfaces like
* Dictionary
* List
* Queue
* SortedDictionary
* Stack
Examples
view source
print?
public class Gen
{
T t;
public T Val
{
get;
set;
}
}
The class name " Gen
T t; Creates member of the type T
The generic Type that we will specify during construction of the class will get inserted by the Common Language Runtime (CLR). The final item in the class is the public property. Again, notice that we are using the Type placeholder "T" to represent that generic type for the type of that property. Also notice that we can freely use the private variable "t" within the class.
In order to use this class to hold any Type, we simply need to create a new instance of our new Type, providing the name of the Type within the "<>" brackets and then use that class in a Type-safe manner as shown below.
view source
print?
static void Main(string[] args)
{
//create a string version of our generic class
Gen str = new Gen();
//set the value for the string type
str.Val = "Beyond Relational";
//output the type and value
System.Console.WriteLine(str.Val);
System.Console.WriteLine(str.Val.GetType());
//create another instance of our generic class, using a different type
Gen flt = new Gen();
flt.Val = 12.34;
System.Console.WriteLine(flt.Val);
//output
System.Console.WriteLine(flt.Val.GetType());
Console.ReadLine();
}
}
Generic Collections
view source
print?
public class MessageElement
{
//some functionality
}
public class MessageSearchCriteria
{
// some functioanlity
}
public List ListMessageElement
{
get
{
return lstMsgElemet;
}
set
{
lstMsgElemet = value;
}
}
MessageSearchCriteria objMsgSearch = new MessageSearchCriteria();
//usage of generics
objMsgSearch.ListMessageElement = new List();
Advantages
* Help to make the code in the software components much more reusable.
* High Quality Code and Code Maintainability
* No runtime Casting No Boxing hence Allows Performance Efficiency
* Creates Type safe at compile time as generics specify type at runtime
* Programmer has stronger and flexible control over the code
* The stronger type checking associated with generics helps in finding errors easily at compile time only.
* No code Duplication
Generics refer to classes and methods that work consistently on values of different types
Subscribe to:
Posts (Atom)