http://www.amazon.com/gp/product/1430234040?ie=UTF8&tag=aspnettelligent-20&linkCode=as2&camp=1789&creative=9325&creativeASIN=1430234040"
The .NET Framework allows developers to use the same set of skills to rapidly buid great applications for the web, windows, services and more.
Showing posts with label C#. Show all posts
Showing posts with label C#. Show all posts
ASP.NET MVC 3 Framework
Many people are searching for a BEST book for ASP.NET MVC 3 Frameowrk. I can guarantee you will enjoy reading below book for ASP.NET MVC 3 Framework.
http://www.amazon.com/gp/product/1430234040?ie=UTF8&tag=aspnettelligent-20&linkCode=as2&camp=1789&creative=9325&creativeASIN=1430234040"
http://www.amazon.com/gp/product/1430234040?ie=UTF8&tag=aspnettelligent-20&linkCode=as2&camp=1789&creative=9325&creativeASIN=1430234040"
Remove dots(.), hyphens(-), spaces,braces’(‘ and ‘)’ from string in C#
If you want to remove dots(.), hyphens(-), spaces, braces ‘(‘ and ‘)’ from a string in C# then you can use any solution given below.
string str = "A sample string having many . and ......It also has a hyphen (-) and too Many hyphens(------) Enjoy!!";
// Solution1: Use of String concat Function and Lambda Extension Method
var solution1 = string.Concat(str.Where(i => !new[] { '.', ' ', '-', '(', ')' }.Contains(i)));
Response.Write(solution1);
// Solution2: Use of Regular Expression. (Make sure you add using System.Text.RegularExpressions; on top of your page before using below solution2)
var solution2 = Regex.Replace(str, "[ ().-]+", "");
Response.Write(solution2);
// Solution3 : Use of Lambda and Extension Methods
var solution3 = str.ToCharArray().Where(i => i != ' ' && i != '-' && i != '.' && i != '(' && i != ')' ).Aggregate(" ", (a, b) => a + b);
Response.Write(solution3);
string str = "A sample string having many . and ......It also has a hyphen (-) and too Many hyphens(------) Enjoy!!";
// Solution1: Use of String concat Function and Lambda Extension Method
var solution1 = string.Concat(str.Where(i => !new[] { '.', ' ', '-', '(', ')' }.Contains(i)));
Response.Write(solution1);
// Solution2: Use of Regular Expression. (Make sure you add using System.Text.RegularExpressions; on top of your page before using below solution2)
var solution2 = Regex.Replace(str, "[ ().-]+", "");
Response.Write(solution2);
// Solution3 : Use of Lambda and Extension Methods
var solution3 = str.ToCharArray().Where(i => i != ' ' && i != '-' && i != '.' && i != '(' && i != ')' ).Aggregate(" ", (a, b) => a + b);
Response.Write(solution3);
Remove Duplicates From List in C#
To Remove Duplicates From List can be done by many different ways. You can use Distinct extension method to remove duplicates.
Below program that removes duplicates from the list in C#.
using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
static void Main()
{
// List having duplicate integer elements.
List<int> list = new List<int>();
list.Add(7);
list.Add(2);
list.Add(5);
list.Add(5);
list.Add(2);
list.Add(3);
list.Add(7);
// Get distinct elements and convert again into a list.
List<int> distinct = list.Distinct().ToList();
foreach (int value in distinct)
{
Console.WriteLine("Distinct : {0}", value);
}
}
}
OR
You can use LINQ to object to remove duplicates from list,
using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
static void Main()
{
// List having duplicate string elements.
List<string> list = new List<string>();
list.Add("A");
list.Add("A");
list.Add("C");
list.Add("D");
list.Add("B");
list.Add("A");
list.Add("E");
list.Add("E");
// Get distinct elements.
var distinct = (from item in list orderby item select item).Distinct();
foreach (string value in distinct)
{
Console.WriteLine("Distinct : {0}", value);
}
}
}
Below program that removes duplicates from the list in C#.
using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
static void Main()
{
// List having duplicate integer elements.
List<int> list = new List<int>();
list.Add(7);
list.Add(2);
list.Add(5);
list.Add(5);
list.Add(2);
list.Add(3);
list.Add(7);
// Get distinct elements and convert again into a list.
List<int> distinct = list.Distinct().ToList();
foreach (int value in distinct)
{
Console.WriteLine("Distinct : {0}", value);
}
}
}
OR
You can use LINQ to object to remove duplicates from list,
using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
static void Main()
{
// List having duplicate string elements.
List<string> list = new List<string>();
list.Add("A");
list.Add("A");
list.Add("C");
list.Add("D");
list.Add("B");
list.Add("A");
list.Add("E");
list.Add("E");
// Get distinct elements.
var distinct = (from item in list orderby item select item).Distinct();
foreach (string value in distinct)
{
Console.WriteLine("Distinct : {0}", value);
}
}
}
Sort Integer and String Array in C#
Example 1: Sort Int[] Array
This example int[] array that you have in your C# program. You can call static Array.Sort Method and use it to sort a integer array in place. The result is an ascending order of numbers.
using System;
using System.Collections.Generic;
using System.Text;
class Program
{
static void Main(string[] args)
{
int[] data = { 999,9,19,555,5,18,399};
Array.Sort(data);
foreach (int i in data)
Console.WriteLine(i);
Console.ReadLine();
}
}
Example 2: Sort string[] Array
This example string[] array that you have in your C# program. You can call static Array.Sort Method and use it to sort a string array in place. The result is an alphabetical sort.
using System;
class Program
{
static void Main()
{
string[] str = new string[]
{
"British",
"Indian",
"American",
"Chinese",
"Malaysians"
};
Array.Sort(str);
foreach (string s in str)
Console.WriteLine(s);
Console.ReadLine();
}
Example 3: Sort string Array with LINQ
This example string[] array that you have in your C# program. You can call static Array.Sort Method and use it to sort a string array in place. The result is an alphabetical sort. We will use LINQ query expression to order its contents.
using System;
using System.Linq;
class Program
{
static void Main()
{
string[] str = new string[]
{
"British",
"Indian",
"American",
"Chinese",
"Malaysians"
};
var sort = from s in str
orderby s
select s;
foreach (string c in sort)
Console.WriteLine(c);
Console.ReadLine();
}
}
Example 4: Sort string Array in reverse using LINQ
This example string[] array that you have in your C# program. You can call static Array.Sort Method and use it to sort a string array in place. The result is an alphabetical decending sort. We will use LINQ query expression to order its contents.
using System;
using System.Linq;
class Program
{
static void Main()
{
string[] str = new string[]
{
"British",
"Indian",
"American",
"Chinese",
"Malaysians"
};
var desc = from s in str
orderby s descending
select s;
foreach (string s in desc)
Console.WriteLine(s);
Console.ReadLine();
}
}
Example 5: Sort List
List<string> is a generic List collection of strings. It is stored as a string array. We can use LINQ exact same way we used in Example 3 and 4.
using System;
using System.Collections.Generic;class Program
{
static void Main()
{
List<string> lst = new List<string>()
{
"British",
"Indian",
"American",
"Chinese",
"Malaysians"
};
lst.Sort();
foreach (string s in lst)
Console.WriteLine(s);
Console.ReadLine();
}
}
This example int[] array that you have in your C# program. You can call static Array.Sort Method and use it to sort a integer array in place. The result is an ascending order of numbers.
using System;
using System.Collections.Generic;
using System.Text;
class Program
{
static void Main(string[] args)
{
int[] data = { 999,9,19,555,5,18,399};
Array.Sort(data);
foreach (int i in data)
Console.WriteLine(i);
Console.ReadLine();
}
}
Example 2: Sort string[] Array
This example string[] array that you have in your C# program. You can call static Array.Sort Method and use it to sort a string array in place. The result is an alphabetical sort.
using System;
class Program
{
static void Main()
{
string[] str = new string[]
{
"British",
"Indian",
"American",
"Chinese",
"Malaysians"
};
Array.Sort(str);
foreach (string s in str)
Console.WriteLine(s);
Console.ReadLine();
}
Example 3: Sort string Array with LINQ
This example string[] array that you have in your C# program. You can call static Array.Sort Method and use it to sort a string array in place. The result is an alphabetical sort. We will use LINQ query expression to order its contents.
using System;
using System.Linq;
class Program
{
static void Main()
{
string[] str = new string[]
{
"British",
"Indian",
"American",
"Chinese",
"Malaysians"
};
var sort = from s in str
orderby s
select s;
foreach (string c in sort)
Console.WriteLine(c);
Console.ReadLine();
}
}
Example 4: Sort string Array in reverse using LINQ
This example string[] array that you have in your C# program. You can call static Array.Sort Method and use it to sort a string array in place. The result is an alphabetical decending sort. We will use LINQ query expression to order its contents.
using System;
using System.Linq;
class Program
{
static void Main()
{
string[] str = new string[]
{
"British",
"Indian",
"American",
"Chinese",
"Malaysians"
};
var desc = from s in str
orderby s descending
select s;
foreach (string s in desc)
Console.WriteLine(s);
Console.ReadLine();
}
}
Example 5: Sort List
List<string> is a generic List collection of strings. It is stored as a string array. We can use LINQ exact same way we used in Example 3 and 4.
using System;
using System.Collections.Generic;class Program
{
static void Main()
{
List<string> lst = new List<string>()
{
"British",
"Indian",
"American",
"Chinese",
"Malaysians"
};
lst.Sort();
foreach (string s in lst)
Console.WriteLine(s);
Console.ReadLine();
}
}
Changing Master Page at Runtime
Solution 1:
Changing Master Page at Runtime by user code.
Many times we have to change Master Page at Runtime by user code. Page_PreInit event will execute just before that page is render. We can write a simple code in Page_PreInit event like below,
protected void Page_PreInit(object sender, EventArgs e)
{
if (Membership.GetUser() == null) //check if the user is logged in or not
this.MasterPageFile = "~/General.master";
else
this.MasterPageFile = "~/MyPortal.master";
}
Solution 2:
Changing Master Page at Runtime by user code based on users roles and responsibilities.
Sometimes there different types of users for the same application. All users have their own roles and responsibilities for the application.
For e.g There are different types of users for my portal application. They all should be able to browse their role related master page.
1. Executive Directors
2. Admin
3. Investment Officers
4. Users
For above portal application senerio we can write code in content Page_PreInit event like below,
protected void Page_PreInit(object sender, EventArgs e)
{
int varRole = 0;
int.TryParse(Session["Role"].ToString(),out varRole);
if (varRole == 1)
{
this.MasterPageFile = "ExecDir.master";
}
if (varRole == 2)
{
this.MasterPageFile = "Admin.master";
}
if (varRole == 3)
{
this.MasterPageFile = "Officer.master";
}
if (varRole == 4)
{
this.MasterPageFile = "User.master";
}
}
How to Rename a File
How to Rename a File? To Rename a file in C# is,
string path1 = @"c:\MyTest1.txt";
string path2 = @"c:\MyTest2.txt";
System.IO.File.Move(path1,path2);
To Rename a file in VB.Net is,
Dim path1 As String = "c:\MyTest1.txt"
Dim path2 As String = "c:\MyTest2.txt"
System.IO.File.Move(path1,path2)
string path1 = @"c:\MyTest1.txt";
string path2 = @"c:\MyTest2.txt";
System.IO.File.Move(path1,path2);
To Rename a file in VB.Net is,
Dim path1 As String = "c:\MyTest1.txt"
Dim path2 As String = "c:\MyTest2.txt"
System.IO.File.Move(path1,path2)
Clear All TextBoxes on a form
If you want to clear/Reset all Textboxes on a form, below solution will help you clear all Textboxes at a time.
You can write a simple funtion using below code,
public static void ClearAllTextBoxes(Control oControl)
{
foreach (Control ct in oControl.Controls)
{
if (ct is TextBox)
{
TextBox tb = (TextBox)ct.FindControl(ct.ID);
tb.Text = string.Empty;
}
if (ct.HasControls())
{
ClearAllTextBoxes(ct);
}
}
}
Call above Funtion using below code,
ClearAllTextBoxes(this);
You can write a simple funtion using below code,
public static void ClearAllTextBoxes(Control oControl)
{
foreach (Control ct in oControl.Controls)
{
if (ct is TextBox)
{
TextBox tb = (TextBox)ct.FindControl(ct.ID);
tb.Text = string.Empty;
}
if (ct.HasControls())
{
ClearAllTextBoxes(ct);
}
}
}
Call above Funtion using below code,
ClearAllTextBoxes(this);
Javascript Alert message from code behind in ASP.NET
We all know that we can display javascript alert message from code behind in ASP.NET using Page.ClientScript.RegisterStartupScript.
Page.ClientScript.RegisterStartupScript(this.GetType(),"myscript","alert('hello world!');");
However, above method can break under ASP.NET AJAX environment. For AJAX we need to use ScriptManager.RegisterStartupScript. Below code displays javascript alert message both in AJAX environment and on regular page as well.
ScriptManager.RegisterStartupScript(this,this.GetType(),"myscript","alert('hello world!');",true);
For more information on ClientScriptManager.RegisterStartupScript Method you can visit,
Get Assembly Name
Sometimes you are asked to get/find Assembly name of a class.
You can use below code to get/find Assembly Name in VB.Net,
Dim assembly As System.Reflection.Assembly = System.Reflection.Assembly.GetAssembly(GetType(Class1))
Response.Write(assembly.GetName().Name)
You can use below code to get/find Assembly Name in C#,
System.Reflection.Assembly assembly = System.Reflection.Assembly.GetAssembly(typeof(Class1));
Response.Write(assembly.GetName().Name);
Here in above code Assembly.GetAssembly Method gets the currently loaded assembly in which the specified class is defined.
You can use below code to get/find Assembly Name in VB.Net,
Dim assembly As System.Reflection.Assembly = System.Reflection.Assembly.GetAssembly(GetType(Class1))
Response.Write(assembly.GetName().Name)
You can use below code to get/find Assembly Name in C#,
System.Reflection.Assembly assembly = System.Reflection.Assembly.GetAssembly(typeof(Class1));
Response.Write(assembly.GetName().Name);
Here in above code Assembly.GetAssembly Method gets the currently loaded assembly in which the specified class is defined.
DateTime in different formats
Using DateTime.Tostring() method, you can display Date and/or Time based on your requirement.
Find the code below displaying Date in 24 different formats.
Response.Write("Displaying DateTime in 24 Different Formats....");
strFormat = dt.ToString("MM/dd/yyyy");
Response.Write("Format 1: " + strFormat);
strFormat = dt.ToString("dddd, dd MMMM yyyy");
Response.Write("Format 2: " + strFormat);
strFormat = dt.ToString("dddd, dd MMMM yyyy HH:mm");
Response.Write("Format 3: " + strFormat);
strFormat = dt.ToString("dddd, dd MMMM yyyy hh:mm tt");
Response.Write("Format 4: " + strFormat);
strFormat = dt.ToString("dddd, dd MMMM yyyy H:mm");
Response.Write("Format 5: " + strFormat);
strFormat = dt.ToString("dddd, dd MMMM yyyy h:mm tt");
Response.Write("Format 6: " + strFormat);
strFormat = dt.ToString("dddd, dd MMMM yyyy HH:mm:ss");
Response.Write("Format 7: " + strFormat);
strFormat = dt.ToString("MM/dd/yyyy HH:mm");
Response.Write("Format 8: " + strFormat);
strFormat = dt.ToString("MM/dd/yyyy hh:mm tt");
Response.Write("Format 9: " + strFormat);
strFormat = dt.ToString("MM/dd/yyyy H:mm");
Response.Write("Format 10: " + strFormat);
strFormat = dt.ToString("MM/dd/yyyy h:mm tt");
Response.Write("Format 11: " + strFormat);
strFormat = dt.ToString("MM/dd/yyyy HH:mm:ss");
Response.Write("Format 12: " + strFormat);
strFormat = dt.ToString("MMMM dd");
Response.Write("Format 13: " + strFormat);
strFormat = dt.ToString("yyyy'-'MM'-'dd'T'HH':'mm':'ss.fffffffK");
Response.Write("Format 14: " + strFormat);
strFormat = dt.ToString("ddd, dd MMM yyyy HH':'mm':'ss 'GMT'");
Response.Write("Format 15: " + strFormat);
strFormat = dt.ToString("yyyy'-'MM'-'dd'T'HH':'mm':'ss");
Response.Write("Format 16: " + strFormat);
strFormat = dt.ToString("HH:mm");
Response.Write("Format 17: " + strFormat);
strFormat = dt.ToString("hh:mm tt");
Response.Write("Format 18: " + strFormat);
strFormat = dt.ToString("H:mm");
Response.Write("Format 19: " + strFormat);
strFormat = dt.ToString("h:mm tt");
Response.Write("Format 20: " + strFormat);
strFormat = dt.ToString("HH:mm:ss");
Response.Write("Format 21: " + strFormat);
strFormat = dt.ToString("yyyy'-'MM'-'dd HH':'mm':'ss'Z'");
Response.Write("Format 22: " + strFormat);
strFormat = dt.ToString("dddd, dd MMMM yyyy HH:mm:ss");
Response.Write("Format 23: " + strFormat);
strFormat = dt.ToString("yyyy MMMM");
Response.Write("Format 24: " + strFormat);
Find the code below displaying Date in 24 different formats.
Response.Write("Displaying DateTime in 24 Different Formats....");
strFormat = dt.ToString("MM/dd/yyyy");
Response.Write("Format 1: " + strFormat);
strFormat = dt.ToString("dddd, dd MMMM yyyy");
Response.Write("Format 2: " + strFormat);
strFormat = dt.ToString("dddd, dd MMMM yyyy HH:mm");
Response.Write("Format 3: " + strFormat);
strFormat = dt.ToString("dddd, dd MMMM yyyy hh:mm tt");
Response.Write("Format 4: " + strFormat);
strFormat = dt.ToString("dddd, dd MMMM yyyy H:mm");
Response.Write("Format 5: " + strFormat);
strFormat = dt.ToString("dddd, dd MMMM yyyy h:mm tt");
Response.Write("Format 6: " + strFormat);
strFormat = dt.ToString("dddd, dd MMMM yyyy HH:mm:ss");
Response.Write("Format 7: " + strFormat);
strFormat = dt.ToString("MM/dd/yyyy HH:mm");
Response.Write("Format 8: " + strFormat);
strFormat = dt.ToString("MM/dd/yyyy hh:mm tt");
Response.Write("Format 9: " + strFormat);
strFormat = dt.ToString("MM/dd/yyyy H:mm");
Response.Write("Format 10: " + strFormat);
strFormat = dt.ToString("MM/dd/yyyy h:mm tt");
Response.Write("Format 11: " + strFormat);
strFormat = dt.ToString("MM/dd/yyyy HH:mm:ss");
Response.Write("Format 12: " + strFormat);
strFormat = dt.ToString("MMMM dd");
Response.Write("Format 13: " + strFormat);
strFormat = dt.ToString("yyyy'-'MM'-'dd'T'HH':'mm':'ss.fffffffK");
Response.Write("Format 14: " + strFormat);
strFormat = dt.ToString("ddd, dd MMM yyyy HH':'mm':'ss 'GMT'");
Response.Write("Format 15: " + strFormat);
strFormat = dt.ToString("yyyy'-'MM'-'dd'T'HH':'mm':'ss");
Response.Write("Format 16: " + strFormat);
strFormat = dt.ToString("HH:mm");
Response.Write("Format 17: " + strFormat);
strFormat = dt.ToString("hh:mm tt");
Response.Write("Format 18: " + strFormat);
strFormat = dt.ToString("H:mm");
Response.Write("Format 19: " + strFormat);
strFormat = dt.ToString("h:mm tt");
Response.Write("Format 20: " + strFormat);
strFormat = dt.ToString("HH:mm:ss");
Response.Write("Format 21: " + strFormat);
strFormat = dt.ToString("yyyy'-'MM'-'dd HH':'mm':'ss'Z'");
Response.Write("Format 22: " + strFormat);
strFormat = dt.ToString("dddd, dd MMMM yyyy HH:mm:ss");
Response.Write("Format 23: " + strFormat);
strFormat = dt.ToString("yyyy MMMM");
Response.Write("Format 24: " + strFormat);
Sending email from ASP.NET
Sending Email from an ASP.NET web application is a simple task.
For sending Email from ASP.NET web application we need to add one namespace,
using System.Net.Mail;
After this we can create a method , sendEmail().
public void sendEmail()
{
MailMessage message = new MailMessage();
message.From = new MailAddress("test@gmail.com");
message.To.Add(new MailAddress("test1@gmail.com"));
message.Subject = "Sending an email from ASP.NET web application";
message.Body = "Your Email Content here…";
SmtpClient client = new SmtpClient();
client.Host = "Give your mail server IP";
client.Port = Put port number;
client.Send(message );
}
You can use this function anywhere from application.
For sending Email from ASP.NET web application we need to add one namespace,
using System.Net.Mail;
After this we can create a method , sendEmail().
public void sendEmail()
{
MailMessage message = new MailMessage();
message.From = new MailAddress("test@gmail.com");
message.To.Add(new MailAddress("test1@gmail.com"));
message.Subject = "Sending an email from ASP.NET web application";
message.Body = "Your Email Content here…";
SmtpClient client = new SmtpClient();
client.Host = "Give your mail server IP";
client.Port = Put port number;
client.Send(message );
}
You can use this function anywhere from application.
Validate Email Address using RegularExpressionValidator
Sometimes there might be the requirement to Validate Email Address using RegularExpressionValidator in application.
If Email address Textbox on your form is Required Field, then try to use following code on your page.
<asp:TextBox ID="txtEmail" runat="server" />
<asp:RequiredFieldValidator ID="txtEmailRequired" runat="server"
ControlToValidate="txtEmail"
Text="* Required"
Display="Dynamic" />
<asp:RegularExpressionValidator ID="RegularExpressionValidator1" runat="server"
ErrorMessage="eg: emailAdd@domain.com"
ControlToValidate="txtEmail"
ValidationExpression="\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*"
Display="Dynamic">
</asp:RegularExpressionValidator>
If Email address Textbox on your form is NOT a Required Field, then you can use following code on your page.
<asp:TextBox ID="txtEmail" runat="server" />
<asp:RegularExpressionValidator ID="RegularExpressionValidator1" runat="server"
ErrorMessage="eg: emailAdd@domain.com"
ControlToValidate="txtEmail"
ValidationExpression="\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*"
Display="Dynamic">
</asp:RegularExpressionValidator>
Remove Querystring item in ASP.NET
If we try to remove/delete a query string directly using below code, we will get an error - collection is read-only.
Request.QueryString.Remove("QSname")
In order to solve above error problem, we need to write below code before we remove them.
// reflect to readonly property
PropertyInfo isreadonly = typeof(System.Collections.Specialized.NameValueCollection).GetProperty("IsReadOnly", BindingFlags.Instance | BindingFlags.NonPublic);
// make collection editable
isreadonly.SetValue(this.Request.QueryString, false, null);
// remove
this.Request.QueryString.Remove("QSname");
Generate Random Number in C#
You can use below code to generate a new Random number each time.
Random rd = new Random();
Int32 rdNum = rd.Next();
Response.Write(rdNum.ToString());
Random rd = new Random();
Int32 rdNum = rd.Next();
Response.Write(rdNum.ToString());
Page life Cycle of an ASP.NET page
Following are the events occur during ASP.NET Page Life Cycle:
1)Page_PreInit
2)Page_Init
3)Page_InitComplete
4)Page_PreLoad
5)Page_Load
6)Control Events
7)Page_LoadComplete
8)Page_PreRender
9)SaveViewState
10)Page_Render
11)Page_Unload
Among above events Page_Render is the only event which is raised by page. So we can't write code for this event.
How to clear Text box
How to clear Textbox value is easy. You can do it many different ways.
TextBox1.Text = "";
OR
TextBox1.Text = string.empty;
OR
TextBox1.Text = null;
TextBox1.Text = "";
OR
TextBox1.Text = string.empty;
OR
TextBox1.Text = null;
Check if the Year is Leap Year or Not in C#
How to check if the Year is Leap Year or Not? Using DateTime keyword we can easily find out whether the Year is Leap Year or Not in C#.
int varYear = 2010;
bool varResult = DateTime.IsLeapYear(varYear);
if (varResult.Equals(true))
{
Response.Write(varYear + " is a Leap Year");
}
else
{
Response.Write(varYear + " is not a Leap Year");
}
int varYear = 2010;
bool varResult = DateTime.IsLeapYear(varYear);
if (varResult.Equals(true))
{
Response.Write(varYear + " is a Leap Year");
}
else
{
Response.Write(varYear + " is not a Leap Year");
}
Calculate the Time taken by a web page to execute
How to Calculate time taken by a web page to excute? Or Calculate execution time of a web page?
Here is a simple solution help you find out the number of Milliseconds or seconds or minutes taken by a web page to execute.
1. Copy below code in your Global.asax file.
2. Once you run your .aspx page, below code will display Number of time taken by a web page to execute.
void Application_BeginRequest(object sender, EventArgs e)
{
Context.Items.Add("startime", DateTime.Now);
}
void Application_EndRequest(object sender, EventArgs e)
{
//Get the start time
DateTime dt =(DateTime)Context.Items["startime"];
//calculate the time difference between start and end of request
TimeSpan ts = DateTime.Now - dt; // Display time in Milliseconds
Response.Write("Number of Milliseconds for execution of this page "+" - "+ ts.TotalMilliseconds);
// Display time in Seconds
Response.Write("Number of Seconds for execution of this page " + " - " + ts.TotalSeconds);
// Display time in minutes
Response.Write("Number of Minutes for execution of this page " + " - " + ts.TotalMinutes);
}
Here is a simple solution help you find out the number of Milliseconds or seconds or minutes taken by a web page to execute.
1. Copy below code in your Global.asax file.
2. Once you run your .aspx page, below code will display Number of time taken by a web page to execute.
void Application_BeginRequest(object sender, EventArgs e)
{
Context.Items.Add("startime", DateTime.Now);
}
void Application_EndRequest(object sender, EventArgs e)
{
//Get the start time
DateTime dt =(DateTime)Context.Items["startime"];
//calculate the time difference between start and end of request
TimeSpan ts = DateTime.Now - dt; // Display time in Milliseconds
Response.Write("Number of Milliseconds for execution of this page "+" - "+ ts.TotalMilliseconds);
// Display time in Seconds
Response.Write("Number of Seconds for execution of this page " + " - " + ts.TotalSeconds);
// Display time in minutes
Response.Write("Number of Minutes for execution of this page " + " - " + ts.TotalMinutes);
}
Find number of Days in a Month
How to find number of Days in a given Month from a web application or windows application? Copy one line of code in your page.
DateTime.DaysInMonth(Year,Month);
OR
Response.Write(DateTime.DaysInMonth(2010, 7));
The above line should display result as 31.
DateTime.DaysInMonth(Year,Month);
OR
Response.Write(DateTime.DaysInMonth(2010, 7));
The above line should display result as 31.
Add Website URL to your Favorites Menu from web application
How to add a website/webiste URL to your Favorites Menu from an application? You can copy below sample code to your .aspx page and you are all set.
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="AddToFavoritesMenu.aspx.cs" Inherits="AddToFavoritesMenu" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<head id="Head1" runat="server">
<title></title>
<script type="text/javascript">
function AddToFavoriteMenu() {
window.external.AddFavorite("http://www.webnetrevolution.blogspot.com", ".NET Sample Code");
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<input id="Button1" type="button" value="Click here to Add to favorites Menu.." onclick="AddToFavoriteMenu()" />
</div>
</form>
</body>
</html>
When you click the button on the webpage, it will prompt a nice InputBox (same InputBox when you click on ‘Add to Favorites…’ on your browser). You can change the defualt name or you can click on Add to add it in your favorites menu.
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="AddToFavoritesMenu.aspx.cs" Inherits="AddToFavoritesMenu" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<head id="Head1" runat="server">
<title></title>
<script type="text/javascript">
function AddToFavoriteMenu() {
window.external.AddFavorite("http://www.webnetrevolution.blogspot.com", ".NET Sample Code");
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<input id="Button1" type="button" value="Click here to Add to favorites Menu.." onclick="AddToFavoriteMenu()" />
</div>
</form>
</body>
</html>
When you click the button on the webpage, it will prompt a nice InputBox (same InputBox when you click on ‘Add to Favorites…’ on your browser). You can change the defualt name or you can click on Add to add it in your favorites menu.
Subscribe to:
Posts (Atom)