Search this blog
Wednesday, October 6, 2010
C#: Find Century from Year
int year = 2010;
int cent = year / 100;
year %= 100;
if (year > 0)
cent = cent + 1;
Console.WriteLine("{0}C",cent);
Output:
21C
Tuesday, June 29, 2010
Throw Vs Throw ex
Throw | Throw Ex |
try{ // do some operation that can fail } catch (Exception ex) { // do some local cleanup throw; } | try { // do some operation that can fail } catch (Exception ex) { // do some local cleanup throw ex; } |
It preserve the Stack information with Exception | It Won't Send Stack information with Exception |
This is called as "Rethrow" | This is called as "Breaking the Stack" |
If want to throw new exception, throw new ApplicationException("operation failed!"); | If want to throw new exception, throw new ApplicationException("operation failed!",ex); |
Finalize Vs Dispose
Finalize | Dispose |
Implicit way to destroy the object | Explicit Way to Destroy Object |
It Cannot Override | It Can be Override |
It freed up the memory used by the object only when scope of the expired | Dispose is forcibly freed up the memory |
It is called by GC at runtime | It is called by user |
If you call finalize, it will move to finalize queue, GC will finalize the object by freed up the memory | It will directly freed up the memory |
It will be handling by GC, no inconsistent error occur | Error will occur, because it is not controlled by GC |
Thursday, February 11, 2010
Visual Studio 2010 and .NET Framework 4 Training Kit

- C# 4.0
- Visual Basic 10
- F#
- Parallel Extensions
- Windows Communication Foundation
- Windows Workflow
- Windows Presentation Foundation
- ASP.NET 4
- Windows 7
- Entity Framework
- ADO.NET Data Services
- Managed Extensibility Framework
- Visual Studio Team System
Wednesday, October 21, 2009
Download VS 2010 and .NET Framework 4.0 Training Kit Beta 2
- C# 4.0
- Visual Basic 10
- F#
- Parallel Extensions
- Windows Communication Foundation
- Windows Workflow
- Windows Presentation Foundation
- ASP.NET 4
- Windows 7
- Entity Framework
- ADO.NET Data Services
- Managed Extensibility Framework
- Visual Studio Team System
Monday, October 12, 2009
Interface in .NET
Tuesday, September 29, 2009
Unable to evaluate expression because the code is optimized or a native frame is on top of the call stack
When I tried Execute the Following Code, try
{
Response.Redirect("Default2.aspx");
}
catch (Exception Ex)
{
Response.Write(Ex.Message.ToString());
}
I got the following Error
Unable to evaluate expression because the code is optimized or a native frame is on top of the call stack.
I removed the try ... catch ... block, then I tried only with
Response.Redirect("Default2.aspx");
then it works fine. finally I came to know that Response.Redirect wont works with in try ... catch ... block.
Hope it helps you too.
Find the Filename Of Current Page in ASP.NET
using System;
using System.IO;
Response.Write(Path.GetFileName(HttpContext.Current.Request.FilePath).ToLower());
How to Get Current Page URL thru ASP.NET?
using System;
Uri MyUrl = Request.Url;
Response.Write("URL: " + MyUrl.AbsoluteUri + "<br>");
DataAdapter
- SelectCommand
- InsertCommand
- DeleteCommand
- UpdateCommand
Data Provider
- SQL Server
- OLEDB
- ODBC
- Oracle
What is DataSet?
DataSet is an ADO.NET object, it helps to store the data in memory for program use. It is a disconnected in-memory cache. We can do the all the database process with dataset like update, delete and adding new record. After finished all the operation with dataset, changes can be made back with database for updating.
Wednesday, August 19, 2009
Filter the EventLog Entries thru C# Code
EventLog EvLog = new EventLog("Application", ".");
foreach (System.Diagnostics.EventLogEntry entry in EvLog.Entries)
{
.....
}
This code will read all the Entries from Event Log, here there is no option to filter the entries of Event log.To implement the filter on the Eventlog, we have to check the value one by one in the for each loop, as given below
foreach (System.Diagnostics.EventLogEntry entry in EvLog.Entries)
{
if (entry.TimeWritten > DateTime.Now.AddDays(-1))
{
.....
}
}
If the list of entries are more in the Event log, then this is not proper way. It will leads to performance issue.To avoid this, we can use WMI Query Language. this Query Language is same as SQL Query structure, we can filter the data in the same way of SQL.
Win32_NTLogEvent is a WMI class which is used to translate instances from the Windowsevent log.
Have a look at the following sample code, (written in C# and windows application)
string SomeDateTime = "20090817000000.000000+000";
string Query = String.Format("SELECT * FROM Win32_NTLogEvent WHERE Logfile = 'Application' AND TimeGenerated > '{0}'", SomeDateTime);
ManagementObjectSearcher mos = new ManagementObjectSearcher(Query);
object o;
foreach (ManagementObject mo in mos.Get())
{
foreach (PropertyData pd in mo.Properties)
{
o = mo[pd.Name];
if (o != null)
{
listBox1.Items.Add(String.Format("{0}: {1}", pd.Name,mo[pd.Name].ToString()));
}
}
listBox1.Items.Add("---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
}
In this sample code, we are using following Query
SELECT * FROM Win32_NTLogEvent WHERE Logfile = 'Application' AND TimeGenerated > 20090817000000.000000+000
This query will fetch the data from Application Log, where the log created on or after 17-Aug-2008This is code display the filtered output in listbox control as shown below
Monday, August 17, 2009
Read Event Log using C#
In the following sample code, I used 2 controls, Listbox and EventLog Controls.
Set the Log Property of Eventlog control to name of the log to read or write. I selected System Log to test this code
In the Form Load Event, I written the following code,
foreach (System.Diagnostics.EventLogEntry entry in eventLog1.Entries)
{
listBox1.Items.Add(entry.EntryType.ToString() + " - " + entry.TimeWritten + " - " + entry.Source + " - " + entry.UserName);
}
This code, read the Data from Log file and written display in to listbox control.Now if run the code, it will display as shown in screen shot
Wednesday, July 1, 2009
Hands-on Labs for Windows® Workflow Foundation in C# and VB.NET
This download comes in two flavors for download. The first download (WFHOLs.exe) is a set of 10 hands-on labs for WF development using .NET 3.0 in Visual Studio 2005. These labs start with an introduction to WF and explore intermediate and advanced WF topics and functionality.
The second download (WFHOLs-3.5.msi) is a set of 11 hands-on labs that have been updated for use with .NET 3.5 and Visual Studio 2008. This lab contains the ten labs for .NET 3.0, and includes an additional lab to demonstrate to the WF developer how to use the new Windows Communication Foundation (WCF) activities added with the .NET Framework 3.5.
Note: Using the .NET 3.0 labs with Visual Studio 2005 requires the release version of the Windows Workflow Foundation extensions.
Download "Hands-on Labs for Windows® Workflow Foundation in C# and VB.NET"
Tuesday, June 9, 2009
Encryption and Decryption Algorithm – ASP.NET, C#
The following code can helps to Encrypt or Decrypt a value based on passing any key code (your own key)
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;
using System.Security.Cryptography;
using System.IO;
using System.Text;
namespace WebApplication1
{
public class KeyGen2
{
public static string DESEnCode(string pToEncrypt, string sKey)
{
pToEncrypt = HttpContext.Current.Server.UrlEncode(pToEncrypt);
DESCryptoServiceProvider des = new DESCryptoServiceProvider();
byte[] inputByteArray = Encoding.GetEncoding("UTF-8").GetBytes(pToEncrypt);
des.Key = ASCIIEncoding.ASCII.GetBytes(sKey);
des.IV = ASCIIEncoding.ASCII.GetBytes(sKey);
MemoryStream ms = new MemoryStream();
CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(), CryptoStreamMode.Write);
cs.Write(inputByteArray, 0, inputByteArray.Length);
cs.FlushFinalBlock();
StringBuilder ret = new StringBuilder();
foreach (byte b in ms.ToArray())
{
ret.AppendFormat("{0:X2}", b);
}
ret.ToString();
return ret.ToString();
}
public static string DESDeCode(string pToDecrypt, string sKey)
{
DESCryptoServiceProvider des = new DESCryptoServiceProvider();
byte[] inputByteArray = new byte[pToDecrypt.Length / 2];
for (int x = 0; x <>
{
int i = (Convert.ToInt32(pToDecrypt.Substring(x * 2, 2), 16));
inputByteArray[x] = (byte)i;
}
des.Key = ASCIIEncoding.ASCII.GetBytes(sKey);
des.IV = ASCIIEncoding.ASCII.GetBytes(sKey);
MemoryStream ms = new MemoryStream();
CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(), CryptoStreamMode.Write);
cs.Write(inputByteArray, 0, inputByteArray.Length);
cs.FlushFinalBlock();
StringBuilder ret = new StringBuilder();
return HttpContext.Current.Server.UrlDecode(System.Text.Encoding.Default.GetString(ms.ToArray()));
}
}
}
To Test the above Algorithm (Encrypt or Decrypt), you can use this method. In this method, I used "!#$a54?3" as Key
| public string encryptQueryString(string strQueryString) { return KeyGen2.DESEnCode(strQueryString, "!#$a54?3"); } public string decryptQueryString(string strQueryString) { return KeyGen2.DESDeCode(strQueryString, "!#$a54?3"); } |
Call Parent Page Method from Child Page thru ASP.NET, C#
The following codesnippet helps to call parent Page Javascript method from Child Page’s Code behind.
As per this code, I have a method "ParentMethod1()" in Parent page.
using System.Text;
StringBuilder sbScript = new StringBuilder();
sbScript.Append("<script language='javascript'>");
sbScript.Append(Environment.NewLine);
sbScript.Append("window.parent.ParentMethod1())");
sbScript.Append(Environment.NewLine);
sbScript.Append("</script>");
ClientScript.RegisterStartupScript(this.GetType(), "CloseWindow", sbScript.ToString());
Sunday, June 7, 2009
String Vs StringBuilder
How to find out, what version of ASP.NET is installed in our Machine?
VB.NET:
Response.Write(System.Environment.Version.ToString())
C# Code:
Response.Write(System.Environment.Version.ToString());
How to Compare Time Using C# or VB.NET?
This code helps to Compare Time Using C# or VB.NET
C# Code:
string t1 = DateTime.Parse("3:30 PM").ToString("t");
string t2 = DateTime.Now.ToString("t");
if (DateTime.Compare(DateTime.Parse(t1), DateTime.Parse(t2)) <>
{
Response.Write(t1.ToString() + " is <> + t2.ToString());
}
else
{
Response.Write(t1.ToString() + " is > than " + t2.ToString());
}
VB.NET Code:
Dim t1 As String = DateTime.Parse("3:30 PM").ToString("t")
Dim t2 As String = DateTime.Now.ToString("t")
If DateTime.Compare(DateTime.Parse(t1), DateTime.Parse(t2)) < style="color:blue">Then
Response.Write(t1.ToString() & " is <> & t2.ToString())
Else
Response.Write(t1.ToString() & " is > than " & t2.ToString())
End If