Wednesday, February 17, 2010

Extension Methods / Visitor Pattern

Extension method is new to C#.Its allow you to add new method to the existing class.

Description
1.Extension method allows you to add new method to the existing class without modifying the code, recompiling or modifying the original code.
2.Extension method are special kind of static method but they are called using instance method syntax. Their first parameter specify which type the method operate on, and the parameter is precede by “this” modifier.
3.Extension method are only in scope when you explicitly import the namespace into your source code with “using” directive.
For Example in string object there is no method call “Reverse()” function .But if you need to extend the string ….


Sample Code


C# Code


namespace ExtensionMethods
{
public static class ExtensionsClass
{
public static string Reverse(this String strReverse)
{
char[] charArray = new char[strReverse.Length];
int len = strReverse.Length - 1;
for (int i = 0; i <= len; i++)
{
charArray[i] = strReverse[len-i];
}
return new string(charArray);
}
}
}
C# Code


How to use?

string s = "Hello Extension Methods";
string strReverse = s.Reverse ();

Here "s" is nothing but the parameter of Reverse() method.



Conclusion
Extension method is nothing but the Visitor pattern.

Visitor Pattern:-
Visitor pattern allows us to change the class structure without changing the actual class. Its way of separating the logic and algorithm from the current data structure. Due to this you can add new logic to the current data structure without altering the structure. Second you can alter the structure without touching the logic

Thursday, February 4, 2010

Force IE7 Compatibility Mode in IE8 with IIS settings

Force IE7 Compatibility Mode in IE8 with IIS settings
There a ton of examples on the web of how you can force IE8 into IE7 compatibility mode using a meta tag in the header.
This tag needs to be first in the (before any css):


That really stinks if you need to add that to a lot of pages or sites. It’s much easier just to add the header as real HTTP Header via IIS. This can be done via IIS 6 or 7.

IIS 6
Go to the website, bring up the properties for it, and click on the HTTP Headers tab.


HTTP Headers tab of an IIS 6 Website

Then, add a new header as below:
Add custom HTTP Header

IIS 7
IIS 7 is much the same. Just go to the site and click on “HTTP Response Headers”.

IIS 7 Website Properties – IIS Section
Then, just add the header:
Add custom HTTP Header
Incidentally, this just sets a value in the web.config, as below:

< httpProtocol >
< CustomHeaders >
< add name="X-UA-Compatible" value="IE7" / >
< /CustomHeaders >
< /httpProtcol >
< /System.webServer >

Wednesday, November 4, 2009

Problem - BadImageFormatException was unhandled
Recently, when working with Managed DirectX in .NET on a 64 bits system I came across the following error:




BadImageFormatException was unhandled
is not a valid Win32 application. (Exception from HRESULT: 0x800700C1)

Make sure the file image is a valid managed assembly.
Make sure you have supplied a correct file path for the assembly.
Get General help for this exception.
If you ask for more details it gives you the following information:


System.BadImageFormatException was unhandled
Message=" is not a valid Win32 application. (Exception from HRESULT: 0x800700C1)"
Source="Something"
StackTrace:
at Something.Program.Main()
at System.AppDomain.nExecuteAssembly(Assembly assembly, String[] args)
at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Threading.ThreadHelper.ThreadStart()

Solution - Change the solution's plataform to x86
In my case and from what I could find on the web, this usually happens in 64 bits systems (I'm running Windows Vista Business 64 bits edition). The problem is that the compiler trys to output 64 bits compatible code, but because it doesn't have the necessary assemblies to do that, it fails with BadImageFormatException.

So, the solution is to tell the compiler to ouput code for x86 systems (because most assemblies/librarys usually only support x86 systems). After doing this, the problem should be gone (the x86 produced code should run on 64 bits systems).

Next I will explain the steps for configuring a project's output platform. I will use Visual Studio 2005, but it should be very similar in other versions.

We need to do the following:


Go to the solution's properties page
Select Configuration Manager
Add a new platform to the project (targeted to x86 systems)
First we need to go to the solution's properties page. In the Solution Explorer right-click the solution and select Properties.



The Property Pages dialog appears. Make sure that Configuration Properties is selected on the left side of the window. Click on the Configuration Manager button that appears on the top-right corner of the dialog.



The Configuration Manager pops up. Now you should go to the Platform dropdown list of your project. Click on "".



The New Project Platform window appears. Select "x86" in the New platform dropdown, "" in the Copy settings from: field and leave the checkbox off. Click the OK button to close the dialog box.



The project should now appear with "x86" in the Platform's column in the Configuration Manager. Close the Configuration Manager and click OK to close the Solution Property Pages. The solution should now run without problems

Tuesday, October 27, 2009

CONFIGURING MAIL in DB through SPs and Scripts

The SQL Mail problems, that we faced in SQL Server 7.0 and 2000, are no more. SQL Server 2005 supports and uses SMTP email now and there is no longer a need to MAPI client to send email. In SQL Server 2005, the mail feature is called Database Mail. In this article, I am going to demonstrate step-by-step, with illustrations, how to configure Database Mail and send email from SQL Server.

Database Mail has four components.

1. Configuration Component

Configuration component has two sub components. One is the Database Mail account, which contains information such as the SMTP server login, Email account, Login and password for SMTP mail.

The Second sub component is Database Mail Profile. Mail profile can be Public, meaning members of DatabaseMailUserRole in MSDB database can send email. For private profile, a set of users should be defined.

2. Messaging Component

Messaging component is basically all of the objects related to sending email stored in the MSDB database.

3. Database Mail Executable

Database Mail uses the DatabaseMail90.exe executable to send email.

4. Logging and Auditing component

Database Mail stores the log information on MSDB database and it can be queried using sysmail_event_log.

Step 1

Before setting up the Database Mail profile and accounts, we have to enable the Database Mail feature on the server. This can be done in two ways. The first method is to use Transact SQL to enable Database Mail. The second method is to use a GUI.

In the SQL Server Management Studio, execute the following statement.

use master
go
sp_configure 'show advanced options',1
go
reconfigure with override
go
sp_configure 'Database Mail XPs',1
--go
--sp_configure 'SQL Mail XPs',0
go
reconfigure
go
Alternatively, you could use the SQL Server Surface area configuration. Refer Fig 1.0.


Fig 1.0

Step 2

The Configuration Component Database account can be enabled by using the sysmail_add_account procedure. In this article, we are going create the account, "MyMailAccount," using mail.optonline.net as the mail server and

makclaire@optimumonline.net as the e-mail account.

Please execute the statement below.

EXECUTE msdb.dbo.sysmail_add_account_sp
@account_name = 'MyMailAccount',
@description = 'Mail account for Database Mail',
@email_address = 'makclaire@optonline.net',
@display_name = 'MyAccount',
@username='makclaire@optonline.net',
@password='abc123',
@mailserver_name = 'mail.optonline.net'
Step 3

The second sub component of the configuration requires us to create a Mail profile.

In this article, we are going to create "MyMailProfile" using the sysmail_add_profile procedure to create a Database Mail profile.

Please execute the statement below.

EXECUTE msdb.dbo.sysmail_add_profile_sp
@profile_name = 'MyMailProfile',
@description = 'Profile used for database mail'
Step 4

Now execute the sysmail_add_profileaccount procedure, to add the Database Mail account we created in step 2, to the Database Mail profile you created in step 3.

Please execute the statement below.

EXECUTE msdb.dbo.sysmail_add_profileaccount_sp
@profile_name = 'MyMailProfile',
@account_name = 'MyMailAccount',
@sequence_number = 1
Step 5

Use the sysmail_add_principalprofile procedure to grant the Database Mail profile access to the msdb public database role and to make the profile the default Database Mail profile.

Please execute the statement below.

EXECUTE msdb.dbo.sysmail_add_principalprofile_sp
@profile_name = 'MyMailProfile',
@principal_name = 'public',
@is_default = 1 ;
Step 6

Now let us send a test email from SQL Server.

Please execute the statement below.

declare @body1 varchar(100)
set @body1 = 'Server :'+@@servername+ ' My First Database Email '
EXEC msdb.dbo.sp_send_dbmail @recipients='mak_999@yahoo.com',
@subject = 'My Mail Test',
@body = @body1,
@body_format = 'HTML' ;

Sunday, September 13, 2009

RENAME COLUMN/ ADD COLUMN

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'DOCUMENT' AND COLUMN_NAME = 'DOCUMENTDUEDATE')
BEGIN
ALTER TABLE DOCUMENT ADD DOCUMENTDUEDATE DATETIME
END

--To rename an existing column
--EXEC sp_rename 'DOCUMENT.DUEDATE','DOCUMENTDUEDATE','COLUMN'

Tuesday, August 25, 2009

Anonymous Methods

Anonymous methods were introduced in C# 2.0 +. These are alternative for named methods. In simple terms these are "Inline Methods".

Monday, August 24, 2009

Create XML Document

< ?xml version="1.0" encoding="utf-8"? > < >XML< /MainCategory > < >This is a list my XML articles.< /Description> < >true< /Active> < /Category >< /CategoryList >Here's the code:
< %@ Import Namespace="System.Data" % >
< %@ Import Namespace="System.Xml" % >
< %@ Page Language="C#" Debug="true" % >
< runat="server">
void Page_Load(object sender, System.EventArgs e){
if(!Page.IsPostBack){
XmlDocument xmlDoc = new XmlDocument();
// Write down the XML declaration
XmlDeclaration xmlDeclaration = xmlDoc.CreateXmlDeclaration("1.0","utf-8",null);
// Create the root element
XmlElement rootNode = xmlDoc.CreateElement("CategoryList");
xmlDoc.InsertBefore(xmlDeclaration, xmlDoc.DocumentElement);
xmlDoc.AppendChild(rootNode);
// Create a new element and add it to the root node
XmlElement parentNode = xmlDoc.CreateElement("Category");
// Set attribute name and value!
parentNode.SetAttribute("ID", "01");
xmlDoc.DocumentElement.PrependChild(parentNode);
// Create the required nodes
XmlElement mainNode = xmlDoc.CreateElement("MainCategory");
XmlElement descNode = xmlDoc.CreateElement("Description");
XmlElement activeNode = xmlDoc.CreateElement("Active");
// retrieve the text
XmlText categoryText= xmlDoc.CreateTextNode("XML");
XmlText descText = xmlDoc.CreateTextNode("This is a list my XML articles.");
XmlText activeText = xmlDoc.CreateTextNode("true");
// append the nodes to the parentNode without the value
parentNode.AppendChild(mainNode);
parentNode.AppendChild(descNode);
parentNode.AppendChild(activeNode);
// save the value of the fields into the nodes
mainNode.AppendChild(categoryText);
descNode.AppendChild(descText);
activeNode.AppendChild(activeText);
// Save to the XML file
xmlDoc.Save( Server.MapPath("categories.xml"));
Response.Write("XML file created");
}
}
< /script>


< script runat="server" >
void Page_Load(object sender, System.EventArgs e){
if(!Page.IsPostBack){
XmlDocument xmlDoc = new XmlDocument();
// Write down the XML declaration
XmlDeclaration xmlDeclaration = xmlDoc.CreateXmlDeclaration("1.0","utf-8",null);
// Create the root element
XmlElement rootNode = xmlDoc.CreateElement("CategoryList");
xmlDoc.InsertBefore(xmlDeclaration, xmlDoc.DocumentElement);
xmlDoc.AppendChild(rootNode);
// Create a new element and add it to the root node
XmlElement parentNode = xmlDoc.CreateElement("Category");
// Set attribute name and value!
parentNode.SetAttribute("ID", "01");
xmlDoc.DocumentElement.PrependChild(parentNode);
// Create the required nodes
XmlElement mainNode = xmlDoc.CreateElement("MainCategory");
XmlElement descNode = xmlDoc.CreateElement("Description");
XmlElement activeNode = xmlDoc.CreateElement("Active");
// retrieve the text
XmlText categoryText= xmlDoc.CreateTextNode("XML");
XmlText descText = xmlDoc.CreateTextNode("This is a list my XML articles.");
XmlText activeText = xmlDoc.CreateTextNode("true");
// append the nodes to the parentNode without the value
parentNode.AppendChild(mainNode);
parentNode.AppendChild(descNode);
parentNode.AppendChild(activeNode);
// save the value of the fields into the nodes
mainNode.AppendChild(categoryText);
descNode.AppendChild(descText);
activeNode.AppendChild(activeText);
// Save to the XML file
xmlDoc.Save( Server.MapPath("categories.xml"));
Response.Write("XML file created");
}
}
< /script >