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 >

Wednesday, August 19, 2009

Difference between "ref" and "out"

Both are used when sending arguments by reference instead of values. Both should be explicitly written in the calling function and called function. The main difference is that in "ref" the function expects that the reference sent is already initiated. Where as "out" does not expect it to be initiated or it ignores the initiation of the type.
I will be spending more time on this later...

Monday, August 17, 2009

PAGE METHOD

function GetdueDateFromSever() {
var state = document.getElementById("ctl00_cplHolderDefault_ddlIssueState").options[document.getElementById("ctl00_cplHolderDefault_ddlIssueState").selectedIndex].value;
var receivedDate = document.getElementById("ctl00_cplHolderDefault_wdcInqReceivedDate_input").value;
var dateOfLetter = document.getElementById("ctl00_cplHolderDefault_wdcDateOfLetter_input").value;
var inquiryType = document.getElementById("ctl00_cplHolderDefault_ddlInquiryType").options[document.getElementById("ctl00_cplHolderDefault_ddlInquiryType").selectedIndex].value;
var responsibleFunction = document.getElementById("ctl00_cplHolderDefault_lstResponsibleFunction");
var responsiblefunction1 = '';
for (var i = 0; i < responsibleFunction.options.length; ++i) {
if (responsibleFunction.options[i].selected == true) {
responsiblefunction1 = responsiblefunction1.concat(responsibleFunction.options[i].value + ',')
}
}

//
var varResult;
if (state != -1 && receivedDate != "") {
var varWebRequest = new Sys.Net.WebRequest();
varWebRequest.set_httpVerb('POST');
varWebRequest.get_headers()['Content-Type'] = 'application/json; charset=utf-8';
//
//, subEntityName: subEntityName
var varUrlParams = { receivedDate: receivedDate, state: state, inquiryType: inquiryType, responsiblefunction1: responsiblefunction1, dateOfLetter: dateOfLetter };
varWebRequest.set_url(Sys.Net.WebRequest._createUrl(PageMethods.get_path() + "/getDueDateFromServer", varUrlParams));
var varBody = null;
varBody = Sys.Serialization.JavaScriptSerializer.serialize(varUrlParams);
if (varBody === "{}") varBody = "";
varWebRequest.set_body(varBody);
//
var varExecutor = new Sys.Net.XMLHttpSyncExecutor();
varWebRequest.set_executor(varExecutor);
varWebRequest.invoke();
//
if (varExecutor.get_responseAvailable())
varResult = varExecutor.get_object();

document.getElementById("ctl00_cplHolderDefault_wdcDueDate_input").value = varResult;
document.getElementById("ctl00_cplHolderDefault_hdnDueDate").value = varResult;
}
}











[WebMethod()]
[ScriptMethod()]
public static string getDueDateFromServer(string receivedDate, string state, string inquiryType, string responsiblefunction1, string dateOfLetter)
{
CSSI.VUE.CS.Web.Service.Inquiry.SchemaHeader sh = WebHelper.GetServiceSoapHeader("INQUIRY", "INQUIRYRESEARCHREP1DATASCHEMA") as CSSI.VUE.CS.Web.Service.Inquiry.SchemaHeader;
InquiryService inquiryService = WebHelper.GetInquiryService();
inquiryService.SchemaHeaderValue = sh;
XmlDocument xdDueDateList = new XmlDocument();
xdDueDateList.LoadXml(@"" + state + "" + receivedDate + "" + dateOfLetter + "" + inquiryType + "" + responsiblefunction1 + "");
////
XmlNode xnUserList = inquiryService.GetDueDateByState(xdDueDateList);

string dueDate = xnUserList.SelectSingleNode("//DUEDATE").InnerText;
if (dueDate == "01/01/1900")
{
dueDate = "";
}
return dueDate;
}

Sunday, August 16, 2009

RAISE ERROR

RAISERROR ('User does not have privileges to perform this action.' -- Message text.
,11 -- Severity
,1 -- State
,N'number' -- First argument.
,5);
RETURN

Saturday, August 15, 2009

ALTER TABLE ADD NEW COLUMN

ALTER TABLE table_name ADD column_name datatype
ALTER TABLE table_name DROP COLUMN column_name

ALTER TABLE table_name ALTER COLUMN column_name datatype

Friday, August 14, 2009

Check Non Integers inJavascript

you can use isNaN function to check if a value is a Non Integer.

Thursday, August 13, 2009

Access Master page events from Content page

The following are the steps to be taken to access a master page's event from a content page.

1. Create a drop down list in the Master page.

2. Create an Event handler for SelectIndexChanged event.

3. Define an event in the Master page for the Dropdowns select index changed with the above signature.

4. Subscribe to the event in the contentpage that care about the changing of the ddl.



Here is the code to subscribe the event from the content page.
protected void Page_Init(object sender, EventArgs e)
{
Master.EventHandlerName += new CommandEventHandler(MasterPageEventName);
}

protected void MasterPageEventName(object sender, CommandEventArgs e)

{

string text = e.CommandName;

string value = e.CommandArgument.ToString();

}

NOTE: We can use delegates as well.

Monday, August 10, 2009

Sql Server Split Function

Here is the split function that splits the given varchar with the given dilimiteer




CREATE FUNCTION [dbo].[ufn_Split](@text varchar(8000), @delimiter
varchar(20) = ' ')
RETURNS @Strings TABLE
(
position int IDENTITY PRIMARY KEY,
value varchar(8000)
)
AS
BEGIN
DECLARE @index int
SET @index = -1
WHILE (LEN(@text) > 0)
BEGIN
SET @index = CHARINDEX(@delimiter , @text)
IF (@index = 0) AND (LEN(@text) > 0)
BEGIN
INSERT INTO @Strings VALUES (@text)
BREAK
END
IF (@index > 1)
BEGIN
INSERT INTO @Strings VALUES (LEFT(@text, @index - 1))
SET @text = RIGHT(@text, (LEN(@text) - @index))
END
ELSE
BEGIN

--You can uncomment the below statement if you want to insert nulls
--INSERT INTO @Strings VALUES (NULL)
SET @text = RIGHT(@text, (LEN(@text) - @index))
END
END
RETURN
END

Sunday, August 9, 2009

Date Companrision using Javascript

Here is a sample script to validate if a date is greater thank another date.


if (ExamRangeFrom != "" && ExamRangeTo != "") {
var str1 = ExamRangeFrom;
var str2 = ExamRangeTo;
if (str1.length < 10) {
var temp1 = new Array();
temp1 = str1.split('/');
if (temp1[0].length < 2) {
temp1[0] = "0" + temp1[0];
}
if (temp1[1].length < 2) {
temp1[1] = "0" + temp1[1];
}
str1 = temp1[0] + "/" + temp1[1] + "/" + temp1[2];
}
if (str2.length < 10) {
var temp2 = new Array();
temp2 = str2.split('/');
if (temp2[0].length < 2) {
temp2[0] = "0" + temp2[0];
}
if (temp2[1].length < 2) {
temp2[1] = "0" + temp2[1];
}
str2 = temp2[0] + "/" + temp2[1] + "/" + temp2[2];
}
var mon1 = parseInt(str1.substring(0, 2), 10);
var dt1 = parseInt(str1.substring(3, 5), 10);
var yr1 = parseInt(str1.substring(6, 10), 10);
var mon2 = parseInt(str2.substring(0, 2), 10);
var dt2 = parseInt(str2.substring(3, 5), 10);
var yr2 = parseInt(str2.substring(6, 10), 10);
var date1 = new Date(yr1, mon1, dt1);
var date2 = new Date(yr2, mon2, dt2);
if (date2 < date1) {
varalert = varalert + "Exam To date should not be less than From date.";
alert(varalert);
return false;
}

Friday, August 7, 2009

Ranking your Records

There are some senarios where we are asked to fetch the second highest earning employee from the list of employees.
Here is the scenario I had to work: There are three tables, 1. Student, 2.Exam, 3.StudentExam. Student has all the student names and is independent table. Exam has all the exam names and is independent. StudentExam has the marks earned by each student in exams he has taken and I should say acts as a middle table between student and Exam and is dependent on both. I need to fetch the higest scorer for each exam and display his name. I tried group by but it shows all the records. After a short search in the internet I found this wonderful function in SQL 2005 (not sure if exists in prior version of sql server), Rank(). With this my query has become quite simple. Here is what I wrote in order to achieve the above criteria.

SELECT STUDENT, EXAM, MARKS FROM
(
SELECT STUDENT.NAME STUDENT, EXAM.NAME EXAM,

RANK () OVER(PARTITION BY EXAM.NAME ORDER BY MARKSSCORED DESC) AS RANK,
MAX(MARKSSCORED) AS MARKS
FROM STUDENT, EXAM, STUDENTEXAM
WHERE STUDENT.STUDENTID = STUDENTEXAM.STUDENTID
AND EXAM.EXAMID = STUDENTEXAM.EXAMID
GROUP BY EXAM.NAME, STUDENT.NAME, MARKSSCORED
) TMP
WHERE RANK = 1

Thursday, August 6, 2009

Filter a DataTable

There will be a requirement where you have to filter out the data you fetched from the database into a DataTable. In this scenario we can user a DataView to filter out the data.
Ex: I have states of India and their zone
DataTable dtStates(ID, Name, Zone) : 1 Andhra Pradesh South, 2 Arunachal Pradesh East, 3 Bihar North
I need to filter out the ones that are in south zone. Here is the code for it
DataView dvSouthZoneStates = dtStates.DefaultView;
dvSouthZoneStates.RowFilter = "Zone='South'";
Now we can use this DataView to bind data.

It is not possible to run two different versions of ASP.NET in the same IIS process. Please use the IIS Administration Tool to reconfigure your server

If you are working with IIS 6 then you will face this issue. This issue though will not rise in IIS5.
Simply,
create a new application pool and move the site that you will be upgrading to that pool.

Here is a nice article on this
http://weblogs.asp.net/owscott/archive/2006/01/26/436607.aspx

Print Friendly Version

There will be scenarios where you want to print a page without the Print Icon or Close buttons. All you need to do is put the printable data inside a dive and then add the iframe tag at the end of that screen and on print load the ifram with the div content. Here is the code.


function ClickToPrint() {
try {
var oIframe = document.getElementById('ifrmPrint');
var oContent = document.getElementById('divprint').innerHTML;
var oDoc = (oIframe.contentWindow oIframe.contentDocument);
if (oDoc.document) oDoc = oDoc.document;
oDoc.write("<><>title< /title>");
oDoc.write("< /head>< onload="'this.focus();">");
oDoc.write(oContent + "< /body>");
oDoc.close();
return false;
}
catch (e) {
self.print();
}
}

Focus Popup Window

When you click on a field that opens a popup window. Now if you this window is still opened but not focused and you click on the field again, a new window opens. This might be a requirement for some but mostly we want to get the focus back on the already opened window. This is a simple task here is the solution.

window.open('something.aspx', 'OpenWindow', 'toolbar=no,width=750px,height=500px,top=100px,left=130px,scrollbars=yes,resizable=1,menubar=no');
var txt = 'something.aspx';
OpenWindow=
window.open(txt, 'OpenWindow', 'toolbar=no,width=750px,height=500px,top=100px,left=130px,scrollbars=yes,resizable=1,menubar=no');
if (window.focus) {
OpenWindow.focus();
return false;
}

Wednesday, August 5, 2009

Checking Nulls

This is my very first blog. In order to keep it simple I am just giving a tip for the new developers who are eager to complete the code but might overlook a very simple yet annoying issue.
Most of the time during coding we fail to address the NULL exceptions. This will be 80% of the time. In order to avoid this we need to make sure that the field we are working on if its from database is NOT null in case its a "nullable" field in the db.
Similarly, we need to check if a "QueryString", "Variable", "Session" , "DataSet", "Table" and so on are not NULL before we start working on it. This will reduce 70% of the issues during testing.