Search this blog

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

Wednesday, October 6, 2010

C#: Find Century from Year

Today one of friend asked me, how to find century from the year thru C# code. The following code snippet helps:


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




February Release of the Visual Studio 2010 and .NET Framework 4 Training Kit

The Visual Studio 2010 and .NET Framework 4 Training Kit includes presentations, hands-on labs, and demos. This content is designed to help you learn how to utilize the Visual Studio 2010 features and a variety of framework technologies including:
  • 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
This version of the Training Kit works with Visual Studio 2010 RC and .NET Framework 4 RC.

Wednesday, October 21, 2009

Download VS 2010 and .NET Framework 4.0 Training Kit Beta 2


 
The Visual Studio 2010 and .NET Framework 4 Training Kit includes presentations, hands-on labs, and demos. 



 This content is designed to help you learn how to utilize the Visual Studio 2010 features and a variety of framework technologies including:
  • 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
This version of the Training Kit works with Visual Studio 2010 Beta 2 and .NET Framework 4 Beta 2.


Monday, October 12, 2009

Interface in .NET


What is Interface?
          Interface is a Collection of abstract methods, members encapsulated together into a specific functionality. It contains only the signature of the members. The implementation of these members will be available on the class that implements the interface

Interface can be a member of class or namespace and it contains only the signature of following members
   1. Methods
   2. Properties
   3. Indexers
   4. Events or Delegates


When you go for Interface?
          C# doesn’t support Multiple Inheritance. To overcome these problems we can use Interface. Also interface provides more design facility. Interface let you separate the definition of the object from their implementation. Also there are several others reason like,
   1. your application may requires many unrelated object types to provide certain functionality
   2. it is more flexible than base class
   3. you don’t need to inherit implementation from base class
   4. it is very useful when you can’t use class inheritance where as structure can’t inherit from class but it can be implemented thru interface




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

Here is an another piece of code to findout the filename of current page that is being viewed.


using System;
using System.IO;

Response.Write(Path.GetFileName(HttpContext.Current.Request.FilePath).ToLower());

How to Get Current Page URL thru ASP.NET?

The following Piece of code helps to get the current URL in Asp.Net.


using System;

Uri MyUrl = Request.Url;

Response.Write(
"URL: " + MyUrl.AbsoluteUri + "<br>");


Hope this code will be helpful to beginners

DataAdapter

The DataAdapter is a ADO.NET class, it provides disconnected data access, also acting as a middleman to provide all kind of interaction between the database and a DataSet.

The DataAdapter is used either to fill a DataTable or DataSet with data from the database by it's Fill method. After the memory-resident data has been manipulated, the DataAdapter can commit the changes to the database by calling the Update method.

The DataAdapter provides four properties that represent database commands:
  • SelectCommand
  • InsertCommand
  • DeleteCommand
  • UpdateCommand

Data Provider

The Data Provider is a one of the major components of ADO.NET architecture, it is responsible for providing and maintaining the connection to the database. A DataProvider is a collection of related components that work together to provide data in an efficient manner.

Currently, the following data providers are available in .NET Framework,

  • SQL Server
  • OLEDB
  • ODBC
  • Oracle

Each DataProvider consists of the following component classes:

The Connection object which provides a connection to the database
The Command object which is used to execute a command
The DataReader object which provides a forward-only, read only, connected recordset
The DataAdapter object which populates a disconnected DataSet with data and performs update

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

To Read & Write Event Log thru C#, System.Diagnostics.EventLog class will help. When we read from Eventlog, the following code will helps

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#

The Following sample code helps to Read Data from Event Log. This is a sample windows application written by 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

Windows Workflow Foundation (WF) is the programming model, engine and tools for quickly building workflow enabled applications on Windows. This download is a collection of hands-on labs for Windows Workflow Foundation. The HOL contains both C# and VB.NET versions of the labs to help .NET developers learn WF. These labs are suitable for a .NET developer with 6 months experience who wants to learn about Windows Workflow Foundation. Each lab is approximately 60 minutes of work. The download package includes lab manuals for each lab, pre-requisite files for the labs and sample completed solutions for each exercise in the labs. MSDN has more information about Windows Workflow Foundation.

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

The String object is immutable. Every time you use one of the methods in the System.String class, you create a new string object in memory, which requires a new allocation of space for that new object. In situations where you need to perform repeated modifications to a string, the overhead associated with creating a new String object can be costly.

The System.Text.StringBuilder class can be used when you want to modify a string without creating a new object. For example, using the StringBuilder class can boost performance when concatenating many strings together in a loop.

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