Friday, January 23, 2009

Event Logs

We can create event logs using System.Diagnostics.

Application Log


EventLog eventLog = new EventLog("Application");
eventLog.Source = "MyApp";
eventLog.WriteEntry("Application Started", EventLogEntryType.Information);
Security Log

EventLog eventLog = new EventLog("Security");
eventLog.Source = "MyApp";
eventLog.WriteEntry("Application Started", EventLogEntryType.Information);

System Log

EventLog eventLog = new EventLog("System");
eventLog.Source = "MyApp";
eventLog.WriteEntry("Application Started", EventLogEntryType.Information);

Thursday, January 22, 2009

Code Names of Visual Studio.NET

  • Visual Studio .NET (2002) - Rainier
  • Visual Studio .NET 2003 - Everett
  • Visual Studio 2005 - Whidbey
  • Visual Studio 2008 - Orcas
  • .NET 3.0 Framework - WINFX
  • Visual Studio 2010 - HawaiiRefer links
Refer links,

  1. http://en.wikipedia.org/wiki/Microsoft_Visual_Studio
  2. http://en.wikipedia.org/wiki/List_of_Microsoft_codenames

Object Initializer

var objList = (from info in someList
select new YourClassName
{
Property1 = info.Property1,
Property2 = info.Property2,
} into newInfo
select newInfo).AsEnumerable();

where YourClassName is the name of your class you want to initialize.And Property1, Property2 are properties inside the class.

Wednesday, January 21, 2009

Process in .NET

We can get processes in a machine by using Process class.


Process[] process = Process.GetProcesses();
foreach (Process pro in process)
{
Console.WriteLine(pro.ProcessName);
}

or processes by name,

Process[] process = Process.GetProcessesByName("devenv");
foreach (Process pro in process)
{
Console.WriteLine(pro.SessionId);
}

Tuesday, January 20, 2009

Compression Using GZipStream

Compression is very much important in many cases.We can even compress our ViewState so that we can increase the performance of application Here i am going to give code snippets for compression using GZipStream.

FileStream inStream = File.OpenRead(inputFileName);
FileStream outStream = File.Create(outputFileName);
GZipStream gZipStream = new GZipStream(outStream, CompressionMode.Compress);

int bytes = inStream.ReadByte();

while (bytes1 = -1)
{
gZipStream.WriteByte(bytes as byte);
bytes = inStream.ReadByte();
}

:-)

Monday, January 19, 2009

ICallbackEventHandler

Here i am going to give code snippets for ICallbackEventHandler through which we can make asynchronous calls to server so that we can avoid post back of the web page.

Firstly we have to implement the interface ICallbackEventHandler,

public partial class _Default : System.Web.UI.Page, ICallbackEventHandler
then we have to implement two methods in the interface ICallbackEventHandler,

  • GetCallbackResult
  • RaiseCallbackEvent
  #region ICallbackEventHandler Members

public string GetCallbackResult()
{
return result;
}

public void RaiseCallbackEvent(string eventArgument)
{
result = "Call Back Result";
}

#endregion
Here for simplicity i am returning a static data.You can return dynamic data also.Then you need to Get Call back Event Reference through Page.ClientScript

string callback = ClientScript.GetCallbackEventReference(this, "arg", "GetName", "context");
string script = "function CallBack(arg,context){" + callback + ";}";
ClientScript.RegisterClientScriptBlock(this.GetType(), "CB", script, true);
so now our class look like this,

using System;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;

public partial class _Default : System.Web.UI.Page, ICallbackEventHandler
{
public string result;
protected void Page_Load(object sender, EventArgs e)
{
string callback = ClientScript.GetCallbackEventReference(this, "arg", "GetName", "context");
string script = "function CallBack(arg,context){" + callback + ";}";
ClientScript.RegisterClientScriptBlock(this.GetType(), "CB", script, true);
}

#region ICallbackEventHandler Members

public string GetCallbackResult()
{
return result;
}

public void RaiseCallbackEvent(string eventArgument)
{
result = "Call Back Result";
}

#endregion
}
Now add one textbox and one HTML Button to the designer.For call back we should use HTML Button.In the onclick event of HTML Button call the javascript method GetValue();

Our Javascript code looks like,

function GetValue()
{
CallBack();
}
function GetName(arg,context)
{
document.getElementById('txtPercentage').value=arg;
}
Build and Run the application.Now while clicking HTML Button the textbox is populated with the value from the server without posting the page.
This is very useful in practical scenarios.

For more details, visit http://msdn.microsoft.com/en-us/library/system.web.ui.icallbackeventhandler.aspx

Group By in LINQ

Here is a sample to show how we can do Group By operation using LINQ,

var listInfo = (from infoResult in context.Results
                where infoResult.ResultID == resultID
                group infoResult by new
                { infoResult.SomeID, infoResult.Name } into newInfo
                select new ClassName
                {
                   SomeID = newInfo.Key.SomeID,
                   Name = newInfo.Key.Name,
                   Count = newInfo.Count(),
                   TotalCount = (from infoResult2 in context.Results
                                 where infoResult2.ResultID== resultID
                                 select infoResult2).Count()
                }).AsEnumerable();

Tuesday, January 13, 2009

Reading from Cookies

Cookies are a nice feature to store data in client side so that we can manage the state in the client side.

Reading from Cookies


protected void Page_PreInit(object sender, EventArgs e)
{
if (Request.Cookies["Theme"] == null)
{
Response.Cookies["Theme"].Value = "ThemeName";
Response.Cookies["Theme"].Expires = DateTime.Now.AddDays(2);
}
else
this.Theme = Request.Cookies["Theme"].Value.ToString();
}

ROW_NUMBER()

ROW_NUMBER() is using for retrieving the row numbers just like displaying in the result pane.

Select * from
(Select *,ROW_NUMBER() OVER(ORDER BY EmployeeID) as RowNumber
from Employee)Temp

where RowNumber BETWEEN 2 AND 4

Parsing XML in SQL - OPENXML

We can parse XML Documents from SQL using OPENXML. Before that we use an sp named sp_xml_preparedocument.
EXEC sp_xml_preparedocument @doc OUTPUT, @doc
SELECT EmployeeID,EmployeeName
FROM   OPENXML (@doc, '/EmployeeList/Employee')
WITH
   (
      EmployeeID  varchar(10),
      EmployeeName varchar(150)
   )
We can even use INNER JOIN or many other queries on OPEN XML.
For bulk data updation or insertion this query is very useful to parse the input XML Data.

State Management - HTTPContext.Current.Items

We can store Objects in HTTPContext.Current.Items for small usages.we can add objects into Items collection just like normal Collections we are using.


LIST listEmployee = HTTPContext.Current.Items as LIST;

if(listEmployee == null)
{
listEmployee = Getyourdata();
HTTPContext.Current.Items["Key"] = listEmployee ;
}

Cross Page Posting

By using cross Page Posting We can access controls or properties in the previous page from the current page.

Suppose We have a textbox in Default.aspx named txtName,So create a property returning its text,


public string Name
{
get
{
return txtName.Text;
}
}
we have a hyperlink and its NavigateUrl is default2.aspx.
In Default2.aspx set PreviousPageType in the source,

<%@ PreviousPageType VirtualPath="~/New/Default.aspx"%>
and in the code behind access the property Name from the first page like this,

if (IsCrossPagePostBack)
{
lblName.Text= PreviousPage.Name;
}
in the second page.

Encrypting Web.config

RSAProtectedConfigurationProvider.
This is the default provider and uses the RSA public key encryption to encrypt and decrypt data.

DataProtectionConfigurationProvider.
This provider uses DPAPI to encrypt and decrypt data.

Configuration config = ConfigurationManager.OpenExeConfiguration("");
ConfigurationSection configSection = config.GetSection("connectionStrings");
if (flag)
configSection.SectionInformation.
ProtectSection("DataProtectionConfigurationProvider");

else
configSection.SectionInformation.UnprotectSection();
config.Save();

private Configuration GetMappedExeConfigurationSections()
{
ExeConfigurationFileMap fileMap = new ExeConfigurationFileMap();
fileMap.ExeConfigFilename =Server.MapPath("~/web.config");
Configuration config = ConfigurationManager.OpenMappedExeConfiguration
(fileMap,
ConfigurationUserLevel.None);
return config;
}

File Upload - uploading multiple Files

We can upload multiple files from multiple file upload controls using a single code.

HTTPFileCollection fileCollection=Request.Files;
for(int i=0;i
{
HttpPostedFile file=fileCollection[i];
If(fileCollection.ContentLength > 0)
{
file.SaveAs(filePath);
}
}