.Net, ASP.Net, C#, VB.net, SQL Server, Xml, CSS, Design Patterns related tips, tricks, code snippets, articles, links, thoughts, etc. from Binu & Subi Thayamkery.

Binu Thayamkery is a seasoned software architect with more than 13 years of experience in developing enterprise grade connected systems using Microsoft Technologies. In his current position as a lead consultant-solution architect with Prudential Financial, he is working on architecture of next generation investment reporting framework using .net 3.5/WCF/AJAX, etc. He holds a Masters Degree in Computer Science from Colorado State University. Subi Thayamkery is an experienced software developer with more than 8 years of developing various application software systems ranging from workflow automation systems to compliance management tools. She currently works as a technology consultant for Prudential Financial where she helps develop a new system for corportate governance department. She holds an Electrical Engineering degree from New Jersey Institute of Technology.

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

Friday, July 25, 2008

Simple Cascading Drop Down List using ASP.Net AJAX

Here is a step by step tutorial to create a simple cascading drop down list,

1) Add a new asp.bet (aspx) page and 2 drop down controls into it.



<asp:DropDownList ID="One" runat="server">

</asp:DropDownList><br />



<asp:DropDownList ID="Two" runat="server">

</asp:DropDownList>


2) Add some server side code to populate the first drop down, depending on selection on first drop down we will populate the second one. (well thats the idea :)




    protected void Page_Load(object sender, EventArgs e)

    {

        
if (!IsPostBack)

        {

            
//Populate "One"

            One.Items.Add(new ListItem("BMW", "BMW"));

            One.Items.Add(
new ListItem("Audi", "Audi"));

            One.Items.Add(
new ListItem("Honda", "Honda"));

            One.Items.Add(
new ListItem("Pick One", ""));

            One.Items[3].Selected =
true;

            Two.Items.Add(
new ListItem("Pick One", ""));



            
//add attribute for "One"

            One.Attributes.Add("onchange", "return getModels();");



        }

    }



3) ok, at this point, its worth running your project and see whether controls display propery with the first list showing makes of the cars and second one showing the default item.

4) Switch back to aspx code, and add a scriptmanager control to it (this is the heart of asp.net ajax... read more here.. Make sure that EnablePageMethods is set to true. This will enable us to call server side page methods from Javascript.





<asp:ScriptManager ID="sm" runat="server" EnablePageMethods="true" >

</asp:ScriptManager>


5) Now we are ready to write some javascript code, you might have noticed (and you got a script error possibly when you ran your project the first time) that we have added "onchange" event attribute to our first drop down list. Now we will write some javascript code to handle it. What we will do is to call the server side method to get the second drop down's values and populate the control with it.

When we call server side method, we use PageMethods. format. Here is how our server side method will look like,




[System.Web.Services.WebMethodAttribute(), System.Web.Script.Services.ScriptMethodAttribute()]

public static string GetModels(string key)

{

    
if (key == "BMW")

    {

        
return ("330 i|330 xi|530 i|530 xi|750 i|X5|X3");

    }

    
if (key == "Audi")

    {

        
return ("A4|A4 Turbo|A6 Quattro|A8 Q");

    }

    
if (key == "Honda")

    {

        
return ("Civic EX|Accord EX-L|Accord EX-LV6|Pilot EX");

    }

    
return ("");

    

}



Simple isn't it? Notice the attributes set on the method. These attributes will enable it to be accessible from the Javascript side. So back to Javascript now...below given code shows it all...




<script language="javascript" type="text/javascript" >

//This is the mehod called from first drop downs "onchange" event

function getModels()

{



    
var makelist = document.getElementById("One");

    
// get selected car make from dropdown list

    var key = makelist.options[makelist.selectedIndex].value;

    
// call the method on the server and wait till the code

    // has completed its execution.

    PageMethods.GetModels(key,OnGetModelsComplete);

}

function OnGetModelsComplete(result)

{  

    
//you get the related models of car here!

    //use it to populate the drop down

    PopulateModels(result);

}

function PopulateModels(result)

{

    
var models = document.getElementById("Two");

    
for (var count=models.options.length-1;count > -1; count--)

    {    

        models.options[count] =
null;

    }

    
var items = result.split('|');

    

    
var idValue;

    
var textValue;

    
var optionItem;

    
for(i = 0; i < items.length;i++)

    {

        textValue = items[i];

        idValue = items[i];

        optionItem =
new Option( textValue, idValue,  false, false);

        models.options[i] = optionItem;

    }

}

</script>






The out-of-band call on PageMethods.... takes the first parameter as the input to the function and the second parameter the callback function name. This function will be calledback when the response gets back from the server...and rest is
all simple as taking the result and doing what ever you want with it..in this case build second drop down list option values...

Cheers!

Friday, April 25, 2008

Creating Schema from Xml file

Here is a code snippet that creates a simple schema file from an
Xml file. It uses XmlSchemaInference class (available from .net 2.0+)
to inferschema from an xml file.


        XmlReader reader = XmlReader.Create(@"c:\binu\customer.xml");

        
XmlSchemaSet schemaSet = new XmlSchemaSet();

        
XmlSchemaInference schema = new XmlSchemaInference();



        schemaSet = schema.InferSchema(reader);

        
TextWriter writer = new StreamWriter(@"c:\binu\customer.xsd");

        
foreach (XmlSchema s in schemaSet.Schemas())

        {

            s.Write(writer);

        }




Sample Xml file used:


<Customers>

<
Customer CustomerName="Maria Anders" Country="Germany"/>

<
Customer CustomerName="Ana Trujillo" Country="Russia"/>

<
Customer CustomerName="Antonio Moreno" Country="Spain"/>

<
Customer CustomerName="Thomas Hardy" Country="United Kingdom"/>

<
Customer CustomerName="Maria Anders" Country="Holand"/>

<
Customer CustomerName="Christina Berglund" Country="Sweden"/>

</
Customers>




Output:


<?xml version="1.0" encoding="utf-8"?>

<
xs:schema attributeFormDefault="unqualified" elementFormDefault="qualified" xmlns:xs="http://www.w3.org/2001/XMLSchema">

  <
xs:element name="Customers">

    <
xs:complexType>

      <
xs:sequence>

        <
xs:element maxOccurs="unbounded" name="Customer">

          <
xs:complexType>

            <
xs:attribute name="CustomerName" type="xs:string" use="required" />

            <
xs:attribute name="Country" type="xs:string" use="required" />

          </
xs:complexType>

        </
xs:element>

      </
xs:sequence>

    </
xs:complexType>

  </
xs:element>

</
xs:schema>


Happy coding!
Cheers!

Friday, January 05, 2007

Windows Service and .Net

Before .net , writing a windows service (NT Service) used to be a messy C++ job. .Net made writing a
windows service simple and straight forward.

What process is a good candidate to be written as a Windows service?

A long running process or a repeating process that requires no user interaction, no
user interface, not even a console - just sit and do some work kind of process - you write it as a
windows service. Just make sure that you document your service well and publish, so that every one
knows the existence of it. Because for the server ops people, when they take inventory of stuff running
in a server, a custom windows service is not the first one makes the list. This might result in your
service not started after a server re-start and so on.

So it is a good practice to setup your service to start automatically, also if your service does not
require any special permissiona run it under local account. If it requires special permissions like
accessing a file share, create a service account with least required access and run service under that
account...

Next post I will discuss writing a simple service...

Cheers!

Wednesday, April 12, 2006

Convert String to Proper Case / Title Case

Proper case/ Title case = First letter of every word is capitalized.
In VB 6.0, we use StrConv() function to convert to proper case.



1 Dim stringVariable as String
2 stringVariable = "hello world"
3 stringVariable = StrConv(stringVariable,vbProperCase)
4 Debug.Print stringvariable 'Prints Hello World



In VB.Net, we could still use the same function, use the Microsoft.VisualBasic Namespace.

1 Dim stringVariable as String
2 stringVariable = "hello world"
3 stringVariable = StrConv(s,VbStrConv.ProperCase)
4 System.Diagnostics.Debug.Writeln (stringvariable) 'Prints Hello World


If you are using c#, you could use the same technique, only point to note is that you will need to pass the locale ID to the StrConv() function (optional param is not possible)

1 string stringVariable = "hello world";
2 stringVariable = Strings.StrConv(s,VbStrConv.ProperCase,new CultureInfo("en-us").LCID);
3 System.Diagnostics.Debug.Writeln (stringvariable); //Prints Hello World


A little more elegant solution is to use TextInfo class to achieve the same.
C# code is shown below,

1 string stringVariable = "hello world";
2 stringVariable = System.Threading.Thread.CurrentThread.CurrentCulture.TextInfo.ToTitleCase(Input.ToLower());
3 System.Diagnostics.Debug.Writeln (stringvariable); //Prints Hello World

Happy Coding!
Cheers!