Tuesday, September 30, 2008

How to remove duplicate characters in a string using C?

Hai friends,
one of my friend asked me to write a C program which should remove duplicate charaters and print the string in C.
That is the reason why i have deviated todays content with C Program.

Input : Apple
Output : Aple

Input :AABBCC
Output :
I have not runned this program in my machine as i am not having TurboC...
Vara prasaad could please check with this and update me whether am i correct.

C-Program

#include<stdio.h>
#include<string.h>
void main()
{
char str[20];finStr[20];
int strlength=0;int i=0;
int fnInd=0;
printf("Program to remove duplicate charaters from the string\n");
printf("Enter string\n");
scanf("%s",str);
strlength=strlen(str);
for(i=0;i<strlength;i++)
{
if(!isDuplicateAvailable(str,str[i],i))
{
finStr[fnInd]=str[i];
fnInd++;
}
}
printf("\n String after removing duplicates :\n%s",finStr);
}


bool isDuplicateAvailable(char[] argStr,char argChar,int argIndex)
{
for(int j=0;j<strlen(argStr);j++)
{
if(j!=argIndex && argStr[j]==argChar)
{
retrun true;
}
}
return false;
}

Cheers,
Srinivas

Sunday, September 28, 2008

How to handle validations using JavaScript?

There might be many validations specific to business rules adopted .For example there might be form to create user.
There will be plenty of fields where user has to enter his/her details and click on save button.
As soon as user clicks on save button, the functionality is the application should save the details to the database table. Since database designed has many constraints specified or mentioned at design level, some thing like the user name length should be 10 characters according to data base. In such case if user gives user name whose length is 11, obviously there occurs an exception while inserting record into table.
It does not look or feel good if it is thrown from database to user, where user cannot understand the message or can be a server failure exception.

Instead it could be pretty good if those design level constraints, business level rules are handled , validate the user provided data and inserting into table if it is fine else throwing appropriate messages onto user interface.

function fun_validateData(txtUsr)
{
var txtUserName =document.getElementById(txtUsr);
if(txtUserName.value.length>10)
{
alert(‘User name should be less than or equal to 10 characters’);
return false;
}
return true;

}
The above function helps in validating the data provided by user for user name whether its length is less than 10 characters.

<html>
<head></head>
<body>

<asp:TextBox ID="txtUserName" runat="server"></asp:TextBox>
<asp:Button ID="btnSave" runat="server" onclick=”btnSave_Click”/>
</body></html>

In my code behind page in page load event I shall add attributes to onlcik event of “btnSave”.

protected void Page_Load(object sender, EventArgs e)
{
btnSave.Attributes.Add("OnClick", "return fun_validateData('" + txtUserName.ClientID + "');");
}

Since I am saying “return”, so depending upon the boolean value returned from the function (fun_ValidateData) , the page gets postbacked. If the funtion returns true then the page postbacks to raise onclick event of the save button.
If the validate function returns false then the page does not post back and remains there.


Looking into the validate function defined in java script , we can find that it retruns false if the validaiton finds an error in user inputs (username length) and thus the page does not post back.
It returns true when the user input is perfect and raies on click (server) event of the save button.

What is differnce between reference type and value type?

When we build applications that use variables they are allotted to memory blocks either in stack or heap memory.They can be either refernce type or value type.
Please find my source code below and screen shot next to it explaining what is reference and value type.

Code:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace Learnings
{
public partial class Form2 : Form
{
public Form2()
{
InitializeComponent();
}
class classtype
{
public int var;
}
struct stacktype
{
public int var;
}
private void button1_Click(object sender, EventArgs e)
{
stacktype objstk1 = new stacktype();
stacktype objstk2 = objstk1;
objstk2.var = 100;

classtype objcls1 = new classtype();
classtype objcls2 = objcls1;
objcls1.var = 200;

MessageBox.Show("Struct " + objstk1.var + ", " + objstk2.var);
MessageBox.Show("Class " + objcls1.var + ", " + objcls2.var);

}
}
}


Output:














You can observe I have defined a class and a stack.
We know that “new” helps in creating/assigning a memory block.

Variables objstk1 and objstk2 store values assigned to variable (var) in there specific memory locations.

References objcls1 and objcls2 points to a location or stores address of a memory block (heap memory) which is created and has variable var =200.

I am saying objstk1,objstk2 as variables (value variable) and objcls1,objcls2 as refernces (refernce variable) which sounds or says what I mean.


So value type says that it holds real value and reference says that it holds references of memory blocks.


When i say “stacktype objstk2 = objstk1;” then a new memory location is created for objstk2 in stack memory and a separate variable var in it.
When I assign value for var which is holded by objstk1 , obviously will not be assigned for var holded by objstk2.

If I do in this manner then we have same values in var holded by 2 variables.

stacktype objstk1 = new stacktype();
objstk1.var = 100;
stacktype objstk2 = objstk1;


That is first I assigned value to var holded by objstk1 and then assigned objstk1 to objstk2 , which does copy content from objstk1 to objstk2 (shallow copy).



Coming to refernce types,
When I say “classtype objcls1 = new classtype();” then
At run time a memory block is created in heap memory and its address is assigned to a stack memory block alias objcls1 which is refernce type variable.


When I say “classtype objcls2 = objcls1;” then the same content from objcls1 is copied to new memory block instack memory alias objcls2.


So both refernce variables hold same memory blocks address which is created in heap memory.

So when I assign value to var variable through objcls1 , and can retrieve same value from var holded by objcls2 , since both objcls1 and objcls2 hold same memory block address (heap memory).

Below screen shot helps to understand visually.






Saturday, September 27, 2008

How to display numbers in words?

How to display words for numbers types in a text box?












This can be done using by javascript which makes user delighted for updating the text for every number press..

<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
<title>Untitled Page</title>
<script type="text/javascript" language="javascript">
function dispWrds(txtID,lblID)
{
var txt=document.getElementById(txtID);
var lbl=document.getElementById(lblID);
var val=txt.value;
var actVal=txt.value;
while(val.indexOf("0")==0)
{
val=val.substring(1);
}
actVal=val;
var txt='';
if(val.length==0)
{
txt="0";
}
else
{
val=actVal;
var prevVal;
var vals= getAmtArrays(actVal);
for(var k=vals.length-1;k>=0;k--)
{
val=vals[k];
if(k!=vals.length-1)
{
if(prevVal.length==1)
txt+=' Crore ';
else
txt+=' Crores ';
}
if(val.length==1)
{
txt+=GetWrd1(val);
}
if(val.length==2)
{
txt+=get2Wrd(val);
}
if(val.length==3)
{
txt+=get3Wrd(val);
}
if(val.length==4)
{
txt+=get4Wrd(val);
}
if(val.length==5)
{
txt+=get5Wrd(val);
}
if(val.length==6)
{
txt+=get6Wrd(val);
}
if(val.length==7)
{
txt+=get7Wrd(val);
}
prevVal=val;
}
}
lbl.innerText=txt;
}

function getAmtArrays(val)
{

var rt=new Array();
var ind=-1;
var lp=0;

for(var i=val.length-1;i>=0;i--)
{
if(lp%7==0 || i==val.length-1)
{
ind++;
rt[ind]=val.charAt(i);
}
else
{
rt[ind]+=val.charAt(i);
}
lp++;
}

for(var j=0;j<=rt.length-1;j++)
{

var arr;
for(var i=rt[j].length-1;i>=0;i--)
{
if(i==rt[j].length-1)
arr=rt[j].charAt(i);
else
arr+=rt[j].charAt(i);
}
rt[j]=arr;
}
return rt;
}
function get7Wrd(vl)
{
var val1=vl.charAt(0)+vl.charAt(1);
var val2=vl.charAt(2)+vl.charAt(3);
var val3=vl.charAt(4);
var val4=vl.charAt(5)+vl.charAt(6);
var vl1=get2Wrd(val2);
var vl2=GetWrd1(val3);
return (get2Wrd(val1)==''?'':get2Wrd(val1)+' lakhs ')+
(vl1==''?'': vl1+' Thousand ')+
(vl2==''?'':vl2+' Hundred ')+
get2Wrd(val4);

}

function get6Wrd(vl)
{
var val1=vl.charAt(0);
var val2=vl.charAt(1)+vl.charAt(2);
var val3=vl.charAt(3);
var val4=vl.charAt(4)+vl.charAt(5);
var vl1=get2Wrd(val2);
var vl2=GetWrd1(val3);
return (GetWrd1(val1)==''?'':GetWrd1(val1)+' lakh ')+
(vl1==''?'': vl1+' Thousand ')+
(vl2==''?'':vl2+' Hundred ')+
get2Wrd(val4);
}
function get5Wrd(vl)
{
var val1=vl.charAt(0)+vl.charAt(1);
var val2=vl.charAt(2);
var val3=vl.charAt(3)+vl.charAt(4);
var vl1=GetWrd1(val2);
return (get2Wrd(val1)==''?'':get2Wrd(val1)+' Thousand ')+
(vl1==''?'':vl1+' Hundred ')+get2Wrd(val3);
}
function get4Wrd(vl)
{
var val1=vl.substring(0,1);
var val2=vl.charAt(1);
var val3=vl.substring(2);
var vl1=GetWrd1(val2);
return (GetWrd1(val1)==''?'':GetWrd1(val1)+' Thousand ')
+(vl1==''?'':vl1+' Hundred ')+get2Wrd(val3);
}
function get3Wrd(vl)
{
var val1=vl.substring(0,1);
var val2=vl.substring(1);
return (GetWrd1(val1)==''?'':GetWrd1(val1))+' Hundred '+get2Wrd(val2);
}
function get2Wrd(vl)
{
var val1=vl.substring(0,1);
var val2=vl.substring(1);
if(val1=='1' && val2!=0)
{
return GetWrd11(vl);
}
else if(val2!=0)
{

return GetWrd2(val1+'0')+' '+GetWrd1(val2);
}
else
{
return GetWrd2(vl);
}
}
function GetWrd1(no)
{
if(no=='1')
{
return 'One';
}
if(no=='2')
{
return 'Two';
}
if(no=='3')
{
return 'Three';
}
if(no=='4')
{
return 'Four';
}
if(no=='5')
{
return 'Five';
}
if(no=='6')
{
return 'Six';
}
if(no=='7')
{
return 'Seven';
}
if(no=='8')
{
return 'Eight';
}
if(no=='9')
{
return 'Nine';
}
if(no=='0')
{
return '';
}

}

function GetWrd11(no)
{
if(no=='11')
{
return 'Eleven';
}
if(no=='12')
{
return 'Twelve';
}
if(no=='13')
{
return 'Thirteen';
}
if(no=='14')
{
return 'Fourteen';
}
if(no=='15')
{
return 'Fifteen';
}
if(no=='16')
{
return 'Sixteen';
}
if(no=='17')
{
return 'Seventeen';
}
if(no=='18')
{
return 'Eighteen';
}
if(no=='19')
{
return 'Nineteen';
}


}

function GetWrd2(no)
{
if(no=='11')
{
return 'Eleven';
}
if(no=='10')
{
return 'Ten';
}
if(no=='20')
{
return 'Twenty';
}
if(no=='30')
{
return 'Thirty';
}
if(no=='40')
{
return 'Fourty';
}
if(no=='50')
{
return 'Fifty';
}
if(no=='60')
{
return 'Sixty';
}
if(no=='70')
{
return 'Seventy';
}
if(no=='80')
{
return 'Eighty';
}
if(no=='90')
{
return 'Ninety';
}
if(no=='00')
{
return '';
}

}
function chk_Number()
{

return true;
return false;
}

function IsNumber(val)
{
var nums="0123456789";
if(nums.indexOf(val)==-1)
return false;
return true;
}
function textPasted(obj)
{
var str=obj.value;
var finVal='';

for(var i=0;i<obj.value.length;i++)
{
if(IsNumber(str.charAt(i)))
{
finVal+=str.charAt(i);
}
}
obj.value=finVal;


}
</script>
</head>
<body>

<br />

<input " onkeyup="dispWrds('txtAmount','lblAmount');" onkeypress="return chk_Number();" onpaste="return false;" onmouseover="textPasted(this);"/>
<br />

<label id="lblAmount" ></label>
</body>
</html>


You can observe for every key press made by the user updates the relevant number in words and displays in the bottom label.

Friday, September 26, 2008

What is XMLHttpRequest?

We are aware that browser understands html and sends requests to servers which are avilable remotely.

It might be ftp server or web server or any thing whose reuest/response is specific to a protocol.
For ftp servers we have communication channel called File Transfer protocol,
For web servers we have communication channel called Hyper text transfer protocol.

Protocol can be stated as the process or state of communication for exchanging infromation.
(Protocol is Simillar to a 3 volts input led can be operated with 3 volts battery but not with 230 volts Ac plug in switch board :),
I mean each protocol has its own rules for understanding, sending, retrieving data through there specific assigned ports using communication channel.)
When you consider this 'XmlHttpRequest' , it says that it is request sent by browser to a web server.



Usually we send request to webserver through browser which loads the entire page in server memory and then gets html content rendered on to the web page.
So even for transactions which are very light (click on a button displaying online voting status, etc...) it does not sounds good to reload the enttre page and loading the
results.

Xml http rquest object is used here in an effective manner to send request to the server to get online voting result but not again loading the whole page in server memory or rendering whole html content on to browser, instead calls a page that gives response or result in string and displays it onto a label in browser which looks like a windows desktop appliation.


So it works very simillar to javascript which behaves like working on client side.
It is trurly running in server but the response or test from server is used just to update a html control or display alert box etc...

Also things like suppose you are inserting bulk of records (2lakhs) into data base and it does not look good if the page gets hanged up unless all records are inserted.
Instead you can create a back end thread that inserts records into data base and using xml http reuest object you can call a web server page which runs sql statement that gives count of records and display the (count)status in page (number of records inserted still now) for every 2 mins .

Function that creates and returns the XmlHttpObject



function getAjaxObject()
{

var xmlHttpReq;
try
{
xmlHttpReq=new XMLHttpRequest();//for fire fox ,safari browsers
}
catch(e)
{
//For IE browsers. 2 for 2 different versions. i donot remember which of these are specific to
try
{
xmlHttpReq=new ActiveXObject("Microsoft.XMLHTTP");
}
catch(e)
{
try
{
xmlHttpReq=new ActiveXObject("Msxml2.XMLHTTP");
}
catch(e)
{
alert('Your browser doesnt support XmlHttpRequest');
return null;
}
}
return xmlHttpReq;
}
return xmlHttpReq;
}

The above mentioned java script function returns an "XMLHttpRequest" Object based on client browser.
By using this object we can interact with server page to run required logic and get response from it like calling a javascript function.

You can see there are 3 ways of creating xml http req object which depends upon the browser client uses. As this object plays vital role in sending http request to server and
retirve the response and embedded to html content using specific dom objects.



Example :


var xmlHttp=getAjaxObject();
if(xmlHttp!=null)
{
var url="../Test.aspx?L="+argu;
xmlHttp.open("GET",url,true);
xmlHttp.onreadystatechange = function() {
if (xmlHttp.readyState == 4) {
alert(xmlHttp.responseText);
}
}
xmlHttp.send(null);

in a javascript function upon a button click


Form the above example
It is clear that we call this line of codes in javascript function since it should not reload the whole page,
First line retrieves the xml http object,
Next i am saving the url of the page which runs the logic accoriding to my requirement ans gives me response or text into a variable.(Along with query strings if there are)
Next xmlHttp.open("GET",url,true);

syntax :-

xmlHttp.open(type,url,asynchronously);


type can be "get" or "post"
usually when you have big or huge data to send to server (query string ) , we use "post"
when expecting result from server we use "get".

Url is the page address which gives appropriate response.

asynchronously defines that the state of sender after sending request and seeking for result.

If it is true (asynchronously) then as soon as the request is sent to the server , the browser does not stay or wait for response instead continues its execution to next line or function.

If it is false (synchronously) then browser stays or waits for the result from the server.

If we set it true (asynchronously) then it seems to be like a javascript function or logic running asynchronously that is Ajax (Asynchronous Java script).
It is also suggested to use true for effective response feel.



Next (Onreadystatechange) is an event that is calls a function every time the xml http request object state changes.



onreadystatechange is an event to handle response status.

0 The request is not initialized
1 The request has been set up.
2 The request has been sent.
3 The request is in process.
4 The requset is complete.

Next you can see an alert box that displays response text recieved from server.
That to in the state change event and the state value is 4 (complete)




There after we say "XMLHttpRequest" object send (null).
which means the request is sent to web server.
Note :
1) when you say send , if the request is asynchronous then your javascript continues to next line or function execution.
2) xmlHttp.status , helps in getting the status whether there is any error like server url not found etc...

Behind saying this process as Ajax i can also say it can be used as DHTML that is dynamically updating the html , of course the html content might be the response from server or
or logic build on client side according to the response text from web server.





Example using xml http object.

This application throws an alert box displaying the time at server (web server) and time at browser end upon a button click.

My aspx page

>%@ Page Language="C#" AutoEventWireup="true" CodeFile="XmlHttpResponse.aspx.cs" Inherits="XmlHttpResponse" %<

You can observer aspx page which gives response for XmlHttpRequest objects is blank except a page tag,
Page tag should be there so that server can identify this page based upon url sent through xml http request object.
(User Interface is not required, as this works as a back end service but does not load at client’s browser).


Code behind page

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

public partial class XmlHttpResponse : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
//Checking the reuest type and then giving desired response
if(Request.QueryString["ReqType"]!=null)
{
if (Request.QueryString["ReqType"].ToString() == "1")
{
//I considered request type 1 is to get the date and time at server side
string strServerTime = DateTime.Now.ToString("dd/MM/yyyy hh:mm:ss");
//Expires set to one says that after the response is sent to the requested browser no caching should be done.
Response.Expires = -1;
//Writing the response back to the requested browser
Response.Write(strServerTime);
}
}
}
}


Since there is no User interface for this aspx page which handles xml http request object and sends response, i can say this service (response for request) is similar to a web service.










Since in my case server and client are same machines, you can observe same time.
If it is the case with different machines you can different times and formats.







Cheers,
Srinivas

Thursday, September 25, 2008

What is globalization and localization?

Theory:

Working for applications which are specific to a location (Windows applications, domestic web applications, windows service etc) , whose users shall provide requirements about there interface display language (mostly English) can be hard coded or not required to be configured or bothered at run time.

But web applications can be accessed by different users from different countries and locations. But the web application or web site which you publish in a machine or server is location specific.

Since application server is location specific and the request it receives from users through browsers are globalize or not from same locations , your web application should be capable enough of sending rich content (HTML) and language specific response to specific browsers. This can be done easily by using Resource files.

Obviously to differentiate requests from different browsers, each Http Request from browser sent to the web server sends the request object information which includes language from browser settings available for the client browser.
(In Internet explorer: - Tools/ Internet Options /General (Tab)/Languages (button), you can change your browser settings while testing globalization concept).
Request.UserLanguages[0] gives the first language in the list selected by client.

Now starts the real use of Resource files on application server side which are called according to this Userlanguage.

protected void Page_Load(object sender, EventArgs e)
{
string[] strUserLanguage=Request.UserLanguages;
Thread.CurrentThread.CurrentUICulture = new System.Globalization.CultureInfo(strUserLanguage[0]);
Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo(strUserLanguage[0]);
this.InitializeCulture();
}

You can observe in the above lines of code I am calling group of instructions or lines of code in page load of a page.
What is happening here?

First I am taking the user (Browser request object) location language into variable.
As we know every time web server recieves a request , it is state less. That is it request object is not persistent or state full after response is sent to browser.
So every time it recieves a request it does not know from where it is though it has received request from same browser many times earlier.

So each time it recieves a request , page load event fires every time and in this event handler fuunction (Page_Load) I should change culture information available on currently created thread to run the request according to user language.

CurrentUICulture : - Modifying current UICulture , User Interface in web page (language) according to users language.

CurrentCulture : - Modifying Curent Culture ,Options dependant upon users culture are affected (Currency,Time format etc…).
Atlast I am initialzing the culture of the request object before processing it.

Globalisation : Developing a web site whose response content (language settings) is updated dynamically according to users language (Request object).

Localisation : Developing a web site whose response content is always static but configurable through resource files.


Practical :


Globaliastion :

1) Right click on your web site in visual studio 2005.
2) Add Asp.Net folder\App_GlobalResources
3) Right click on App_GlobalResources folder and click on Add new item and add a “Resource.resx” file.
Note : Be specific about the file name , let it be Resource.resx.


For each different languages that you are willing to support through your website, should be added in the simillar fashion but the file names should be accoring to the language.
Syntax :- Resource.language.resx
Resource.en-US.resx where en-US is the language from US according to browser language settings.

So if there is request from a country whose language settings is not matched with the resource file , I mean if there is no resource file for a request (language) then process “Resource.resx” file (default file) will be considered.

For example let us take telugu from India which is “te-IN”.

Create a new aspx page (Globalisation.aspx).
In globalisation.aspx.cs

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Threading;
using System.Collections.Specialized;

public partial class Globalisation : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (Request.QueryString["cid"] != null)
{
//Assigning culture to current running thread which is taken from query string
Thread.CurrentThread.CurrentUICulture = new System.Globalization.CultureInfo(Request.QueryString["cid"].ToString());
Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo(Request.QueryString["cid"].ToString());
this.InitializeCulture();
}
//After the culture is initialized then i am displaying current cultures native name (if india bharat desam ...)
//This is current culture dependant
lblCul.Text = System.Globalization.CultureInfo.CurrentCulture.NativeName;

//Here comes the role of resource file, sine the laanguage is from query string
//suppose if it is 'te-IN' (telugu - india) , then Resource.te-IN.resx file available
//in app_globalresources folder is considered , if does not exist then Resource.resx (Default file is considered)
//This is UI culture specific
btnShow.Text = Resources.Resource.btnShow.ToString();

//i am displaying current cultures Currency (if india Rs)
//This is current culture dependant
lblCurrency.Text = System.Globalization.CultureInfo.CurrentCulture.NumberFormat.CurrencySymbol;
}
}

I am expecting a query sting which sends the language instead of taking from request object. This helps in checking globalisation for different languages just by changing the query string instead of changing in browser every time.

Please read comments mentioned in above code for each line.

So create a resoource file with name Resource.te-IN.resx to test application of Telugug India as explained earlier.

When you double click on the created resource file you can see in this manner.

















I have entered text ,
btnShow under name column says the id of the control from my aspx page for which I am willing to change the text.
The text that I want to display for thi te-IN culture is my name in telugu. (You can get language specific fints from many 3rd part web sites)
At this instant you can even value in english no problem.





<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Label ID="lblCul" runat="server">
</asp:Label>
<asp:Label ID="lblUICul" runat="server">
</asp:Label>
<asp:Label ID="lblCurrency" runat="server">
</asp:Label>
<asp:Button ID="btnShow" runat="server" />
<asp:Calendar id="clnder" runat="server"></asp:Calendar>
</div>
</form>
</body>
</html>




You can observe in the above aspx page html content there is no text for button (id=btnShow), but while running appliaction I am able to view text saying my name in telugu.

















If Resource.te-IN.resx file does not exist then , the value defined for this “btnShow” ID from default (Resource.resx) is considered.



Conclusion :

So you need to bother map resource files only for displaying text or labels etc… but things like CurrentCulture dependant (currency, Time format) are automatically updated once you assign a specific language or culture to current running thread.

How to apply skins for RAD controls in ASP.NET

Regarding Rapid components skin i would like to make you more apparent about browser functionality.

What ever product or tool, either you or I or third party develops, it cannot do beyond the extent what browser understands.
What ever it is , the final destination is the response should give html content.
To make the content displayed on browser, to make user more effective or attentive you should build using CSS (cascading style sheets), which is similar to XSD for XML files.

So even skins what rad tool is using for its components obviously use CSS files to make content decorated on to the bowser window. I think you got what do I mean.

There 2 ways to define Skins for Rad tool.
Use existing skins provided by Telerik (Third party , Rad product developer). They are
Default
Default2006
Hay
Inbox
Office2007
Sunset
Telerik
Vist
Web20
WebBlue


Default is the skin which is applied to a rad component you create in the page, for which you can change while creating .
Example :-

You can define in aspx page
<telerik:RadComboBox ID="RadComboBox1" runat="server" EnableEmbeddedSkins="false" Skin="Vista">
You can define in aspx.cs
RadComboBox1.Skin = "SunSet"; in aspx.cs

Note : While using existing Telerik provided skins be very sure about case , because skins are case sensitive.
You cannot give SunSEt for Sunset which throws error.










If I use Vista skin.








If use Sunset skin

Define or customise your own skin according to your own view specifications.

Main important attribute which you should set to false is EnableEmbeddedSkins.
EnableEmbeddedSkins=”false” case when you are trying to define your own customised skin. (Saying not to embed default skin and disable them).

As I said before to control the desing of the content you should define css file according to your view requirement.
So now the task in this case is to create Style sheet file.

To make my job easier and to make you understand easily , I will create a skin of my own called “MyStyle1” which should have the following contents.

Folder created seperately for this style and I name that folder as “MyStyle1”.
I should create a sub folder in this folder saying “ComboBox”.
(I have same folder from C:\Program Files\Telerik\RadControls for ASPNET AJAX Q2 2008\Skins\Vista\ComboBox to make my job easy).

I should create a separate style sheet name (ComboBox.MyStyle1.css).
(To make my job easier I copied file content at
C:\Program Files\Telerik\RadControls for ASPNET AJAX Q2 2008\Skins\Vista\ ComboBox.Vista.css).
(Modified the content in combobox.mystyle1.css file, which has Vista to MyStyle1)
So now my style sheet folder structure in project is








I should link this style sheet folder in head tag as

My aspx page is

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

<%@ Register Assembly="Telerik.Web.UI" Namespace="Telerik.Web.UI" TagPrefix="telerik" %>


<html >
<head runat="server">
<title>Untitled Page</title>
<link href="MyStyle1/ComboBox.MyStyle1.css" type="text/css" rel="stylesheet" />
</head>
<body>
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server" />
<div >
<telerik:RadComboBox ID="RadComboBox1" runat="server" EnableEmbeddedSkins="false" Skin="MyStyle1">
<Items>
<telerik:RadComboBoxItem Text="1" runat="server" />
<telerik:RadComboBoxItem Text="2" CssClass="test" runat="server"/>
<telerik:RadComboBoxItem Text="3" runat="server" />
<telerik:RadComboBoxItem Text="4" runat="server" />

</Items>
<CollapseAnimation Duration="200" Type="OutQuint" />
</telerik:RadComboBox>
</div>
</form>
</body>
</html>



Also to make you find the difference in view while using MyStyle1.css and Vista I have copied “rcbArrowCell.gif” file from
C:\Program Files\Telerik\RadControls for ASPNET AJAX Q2 2008\Skins\Sunset\ComboBox folder and replaced exisintg at ../Rad1/MyStyle1/ rcbArrowCell.gif (vista skin image file with sunset skin image file).


You can observe output with “MyStyle1”.











You can find change in colour/image background since I have used same image files from Vista but replaced rcbArrowCell.gif image file with the one from Sunset.




Modifying the style or view (skins) can also be done for asp or html component

Here i am having 2 buttons , click on first button applies class (style) "Test1" from Stylesheet2.css file and click on second button applies class(style) "Test2" from Stylesheet2.css file
This is done using javascript, so the view gets modified smoothly

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head id="dc_head">
<title>Test</title>
<link href="StyleSheet2.css" rel="stylesheet" type="text/css" id="lnk"/>
<script type="text/javascript" language="javascript">
function applyskin(skn)
{
document.getElementById('div_test1').className=skn;
}

</script>
</head>
<body>

<div class="Test1" id="div_test1">
Using same style sheet class file not modifying the path but just trying to change the class name<br />
<input type="button" value="Test1" id="btnTest1" onclick="applyskin('Test1');"/> <input type="button" value="Test2" id="btnTest2" onclick="applyskin('Test2');" />
<br/>
Hai Friends
</div>
</body>
</html>


Stylesheet2.css file content

body {
}
.Test1
{
background-color:Gray;
}
.Test2
{
background-color:Yellow;
}

Wednesday, September 24, 2008

What is viewstate?

When we ceate a component like asp:textbox or asp:button in a web form, we can observe an attribute named "EnablViewState", which is boolean.

By default the view state of the component is true.
Usually we have view state and control state for a component inorder to provide page persistence during the post backs or between http requests.
In which we can disable or enable the view state of the component but cannot the control state.

So control state of the component is mandatory to provide minimun information to the user.
The reason behind introducing view state is to avert unnecessary data rendered into html, which increases performance.


Example :
in aspx page :
<form id="form1" runat="server">
<div>
<asp:Button ID="btnEF" Text="False" runat="server" OnClick="btnEF_Click" />
<asp:Button ID="btnTF" Text="True" runat="server" OnClick="btnTF_Click" />

<asp:TextBox ID="txtEF" Text="False" EnableViewState="false" runat="server"></asp:TextBox>
<asp:Button ID="btnTest" Text="Test" runat="server" EnableViewState="false" />
</div>
</form>


in aspx.cs page :

protected void btnEF_Click(object sender, EventArgs e)
{
txtEF.Text = "1";
btnTest.Text = "1";
}
protected void btnTF_Click(object sender, EventArgs e)
{
txtEF.Text = "2";
txtEF.Visible =false;
btnTest.Text = "2";
}

Observing the above example we can find 2 controls (textbox and button) with enable view state false in aspx.
In aspx.cs "btnEF_Click" we are just trying to assign text but not controlling the view of the controls.
but "btnTF_Click" we are assiging the text but controlling the visiblity of a text box control whose enable view state is false.
So in "btnTF_Click" we are setting the textbox control visibilty false, now when you click on button "btnEF" i.e; in "btnEF_Click" function we have not
written any code to set the component visibilty to true, but the text box component will be displayed because its enable view state is false whose view state is
not saved.

Tuesday, September 23, 2008

Memory concepts at runtime

We have two kind of memorys.
1) Heap Memory
2)Stack Memory.

Usually the variables might be value or referneced type should be stored in a memory to access.

As there are 2 different memories there sholud be set of rules defined where to store these variables.


a) When we try to create an object in runtime they will created inside heap memory.
But the reference type variable refering to this object can be in heap or stack. To explain when they will be in stack or heap we should be aware with the
following concepts.

i) A variable can be declared inside a function or as a variable member to a class.

The above mentioned line is vital while considering memory management.
A variable declared as local in a function will be stored in stack where as declared as a variable member in a class will be stored in heap.

So that is why it is recommended to use a very less global variables in a class whose memory gets created in heap memory.

So for stack memory it is not required to trap memory cleaning, but for heap memory we have (GC) garbage collector which should run algorithm for cleaning the
heap memory.

b) Static funtions and variable will always be created in heap memory which will created only once but not for every instance of the class.

c) Instance functions get loaded into stack memory so when a function gets called by another , as soon as called function is completed it will be removed from
stack memory, obviously relevant variables will be removed from stack.

d) A refernce type variable pointing to a object is also declared as variable members to class then that refernce type variable along with its pointing object will be stored in heap memory.

So we should be sure about the variable (reference or value) that we declare is according to set of rules defined above.

Sunday, September 21, 2008

how to upload a image to gridview?

















It is a tiny application about “How to upload images?”. User shall provide username, browse file from local machine and once clicks on “add” button the details are saved (database or file system).
Please find the code above for your reference
In the above source code you can observe that the file(image) uploaded by client is saved using a class “UserDetailsData” which is created exclusively to save or retrieve user details which is user name and relative of the uploaded image file at server.
There 2 ways of uploading image file.
1) If you use data base , you create a table with column say “Image” whose data type should be BLOB (Binary Large Object).
While inserting a row into this table you can insert the byte stream of the image file uploaded at this column and while retrieving you should type cast the blob data to byte[] array and save into a file whose src should be used to a img tag to display.
2) The other way in Image column which can be Varchar , you can just save the uploaded image and save to application server local disk and whose file path can be saved in this Image column.
While retrieving you can read the path and assign it directly to img tag as src.

In the above example I have done it using (2) but since I am not Orcale data base server , so I used serialization concept to save user name and image file path into a data table and then writing the state of data table to a text file (Object persistence).






Regarding form view, what ever component we use to display , it might be grid view or form view it does the same thing.In the example i stated which i have done for grid view.For list view




<form id="form1" runat="server">
<div>
<asp:Label ID="lblmsg" runat="server"></asp:Label>
<table width="50%"><tr><td colspan="3">
<center>Upload Images</center>


<asp:FormView ID="frm_Dets" runat="server" Width="100%">
<HeaderTemplate><table width="100%"><tr><td style="width:20%">UserName</td><td>Snap</td></tr></table></HeaderTemplate>
<ItemTemplate>
<table width="100%">
<tr><td style="width:20%"><asp:Label ID="lblUserName" runat="server" Text='<%#Eval("User_name") %>'></asp:Label></td>
<td><img id="img_Snap" runat="server" src='<%#Eval("Image_URL") %>' title='<%#Eval("User_name") %>' style="width:100px" />
</td></tr>
</table>
</ItemTemplate>
</asp:FormView>


<asp:GridView ID="grd_Dets" runat="server" AutoGenerateColumns="false" Width="100%">
<Columns>
<asp:TemplateField>
<HeaderTemplate>User Name</HeaderTemplate>
<ItemTemplate><asp:Label ID="lblUserName" runat="server" Text='<%#Eval("User_name") %>'></asp:Label></ItemTemplate>
<ItemStyle Width="20%" HorizontalAlign="center" />

</asp:TemplateField>
<asp:TemplateField >
<HeaderTemplate>Snap</HeaderTemplate>
<ItemTemplate>
<img id="img_Snap" runat="server" src='<%#Eval("Image_URL") %>' title='<%#Eval("User_name") %>' style="width:100px" />
</ItemTemplate>
<ItemStyle Width="80%" HorizontalAlign="Center" />
</asp:TemplateField>
</Columns>
</asp:GridView>
</td></tr>

<tr><td style="width:30%"><asp:TextBox ID="txtUserName" runat="server"></asp:TextBox></td>
<td style="width:60%"><asp:FileUpload ID="fl_upload" runat="server" /></td>
<td><asp:Button ID="btnAdd" runat="server" Text="Add" OnClick="btnAdd_Click" /></td>
</tr>
</table>

</div>
</form>



private void BindGrid()
{
try
{
UserDetailsData objUserDetailsData = new UserDetailsData();
DataTable dt = objUserDetailsData.GetUserDetails(UserDtsFilePath);
//Created a seperate class called userdetailsdata.cs to read information from File which saves
//serialized databale about the username and url of the fileuploaded by user
if (dt != null)
{
//Binding to gridview.
grd_Dets.DataSource = dt;
grd_Dets.DataBind();

//Binding to formview
frm_Dets.DataSource = dt;
frm_Dets.DataBind();
}

}
catch
{
throw;
}
}

Saturday, September 20, 2008

How to handle try catches?

Many programmers hit there minds with this question. I considered yes and so I use to avoid using it but at final release to client , I found many issues raised by him and I am unable to replicate few of them , client is not able to guide me the way he got the error , some times the page (asp.net) showing “/Server Exception” which makes user irritated etc…

At last I believed this is all because of improper exceptional handling. I does not mean that if try catches are implemented these errors could not occur , but instead if you implement this exception handling by logging errors into a error log file in catch blocks, client can give you that error log file for reference and you can resolve the issues easily than expecting how they have come?



I felt 3 different ways to apply these try catches.
try
{
}
catch
{
throw;
}

(1)


try
{
}
catch(Excexption exp)
{
LogError(exp.Messagge);
throw exp;
}
(2)

try
{
}
catch
{
}

(3)


In the above mentioned cases
1) If you would not like to handle the exception or log it you can thow the expecption, such that be sure that if and only if you are throwing to a calling or parent function.
You cannot throw exception in a parent function instead if you would like to handle you can write (label.Text=exp.Message), which displays the error on to user interface instead having server exceptions or making user irritated.
Before showing error you can log that error into a text file.
Ex:-
public void btn_Calculate(object sender,Eventargs e)
{
try
{
//Since this function is called when user clicks on calculate button from UI
//i.e; the first function executed it is called parent function.
//Now this function calls Calculate() function which becomes child function.


int c=Calculate(a1,b1);
..
..

}
catch(Exception exp){
logError(exp.Message,” btn_Calculate”);
lblError.Text=exp.Message;
}
}
//This calculate function is a child function which is called by another function.
private int Calculate(a,b){
//Child function that has to be actually to handle exceptions.
try
{


return value;

}
catch (Exception exp)
{
logerror(exp.Message,”Sum()”);
throw exp;
}
}

private int Sum(a,b){

//Child function that logs error but returns -1 instead of throwing exception
try
{


return value;
}
catch (Exception exp)
{
logerror(exp.Message,”Sum()”);
return -1;
}
}
private int Sum(a,b){
//Child function that doesnot even log error but returns -1
try
{


return value;
}
catch (Exception exp)
{
return -1;
}
}
private int Sum(a,b){
//Child function that doesnot handle exception


return value;
//When there is any exception in child function , then the exception is raised in //parent function, so the error can be handled , but if there are multiple child //functions even error is handled at parent function but you cannot trace in //which function the error occurred unless you handle in each and log to error //log text file.
}
There are also specific exceptions like OracleException,SMTPException etc…
These Exceptions are child classes to a parent class called Excpetion.


So things like when you connect to oracle or retrieve data using datareader connected to oracle and send a mail to user, it could be good if you use OracleException,SMTPException objects.
try
{
}
catch(OracleException oraexp){
//This catch block holds error when oracle error ossurs
LogError(oraexp.ErrorNumber,”Excpetion due to oracle”);
}
catch(SMTPException smtpexp){
//This catch block holds error when smtp error occurs
LogError(smtpexp.innerExpetion.Message,”Excpetion while sending mail”);
}
Functions which you feel that they are perfect and 100% there is no way of throwing errors then you need not handle try catches.

Note : Finally blocks can also be appended which depends upon you function.

try
{
}
catch
{
}
finnally
{
//To dispose objects that are local to this function and imperative that the value or object
//returned to parent function should not be disposed :)
}

TNS Error ORA 12154

There are many ways that this error could occur, I would like to get into few of them to the best of my knowledge and how this ORA-12154: TNS can be resolved.

I was worried many times while I was trying to connect to a oracle data base server with this error.

For the first time when you install oracle10g client software select Administrator, so that you can configure your local machine to a remote data base server through configuration management tool provided iff you install administrator.

Once you have configured to a data base, you can find it in a text file (tnsnames.ora) located at oracle installation path sub directory network\admin.


Ex :-
DPG =
(DESCRIPTION =
(ADDRESS = (PROTOCOL = TCP)(HOST = dbdev)(PORT = 1521))
(CONNECT_DATA =
(SERVER = DEDICATED)
(SID = dpg)
)
)



DPG Database service name you configure
dbdevOracle data base server name
SIDData base name on server

Once it is configured, you can connect to this data base with any user name created to this data base. Funny thing is, I still observed TNS Error while doing all the above steps. I created a new application (.NET) and used oracleclient.dll to connect to this configured data base.Shocking is I am able to connect to this configured data base from other application but not with this new application. I believe this step surely avoids the error you get. Observe the path where application is, if there is any folder that contains ‘(‘or ‘)’ in folder name or path with ‘(‘or ‘)’ in it then definitely you will get this TNS error even if you are configured. The new application which is throwing TNS Error is because I saved this application in path having ‘)’ and ‘(‘. Hope this helps you :).