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.