Thursday, December 30, 2004

Adding attributes to the HtmlTextArea control

You can add as many attributes you want in any control the limitation is that it must know those attributes.

_textarea = new HtmlTextArea();
_textarea.ID = "HAHA";
_textarea.Attributes.Add("onkeypress","return taLimit()");
_textarea.Attributes.Add("onkeyup","return taCount(myCounter)");
_textarea.Attributes.Add("name","Description");
_textarea.Attributes.Add("rows","7");
_textarea.Attributes.Add("wrap","physical");
_textarea.Attributes.Add("runat","server");
_textarea.Cols = 40;
_textarea.Attributes.Add("maxLength","255");


In the above code you can see that I added many attributes to the HtmlTextArea control.

Thursday, December 23, 2004

Sorting in ArrayList (Ascending and Descending Order)

Here you how you can sort the ArrayList in Ascending and Descending Order.

Ascending Order:

for(int i=0;i<=_leftListBox.Items.Count-1;i++)
{
aList.Add(_leftListBox.Items[i].Text);
}

aList.Add("Azam");
aList.Add("aa");
aList.Add("haha");
aList.Sort();

Descending Order:

for(int i=0;i<=_leftListBox.Items.Count-1;i++)
{
aList.Add(_leftListBox.Items[i].Text);
}

aList.Add("Azam");
aList.Add("aa");
aList.Add("haha");
aList.Sort();
aList.Reverse(); // This sorts it in Descending order

if you use something like this it wont work and than you have to implement the IComparable interface:

foreach(ListItem item in _leftListBox.Items)
{
aList.Add(item);
}
aList.Sort();

Tuesday, December 21, 2004

Remving an Item from the ListBox

This code is executed on a button click and used to remove the selected item from the ListBox.

private void _delFromListBox(object sender, EventArgs e)
{

for(int i=_rightListBox.Items.Count-1;i>=0;i--)
{
if(_rightListBox.Items[i].Selected)
{
_rightListBox.Items.Remove(_rightListBox.Items[i]);
}
}

Code room on www.msdn.microsoft.com

Code room is a new pilot in which microsoft chooses 3 developers from one state and they are given a task, software application to build in 5 hours. Its pretty intense and fun to watch.

for more details go to www.msdn.microsoft.com


Thursday, December 16, 2004

String Concatenation

You can easily perform string contatenation like this:

string a = "hello";
string b = " world";

string c = a+b; // c contains hello world

Not a good idea ! Why ? because strings are immutable and everytime you concatenate the new copy of the string is made meaning a new object. So if you want to concatenate two strings use the StringBuilder class append method. StringBuilder has a link list data structure and no new objects are made when concatenation operation is performed.


Developing Asp.net Server Controls

Starting from December 16 till January 9th 2005. I will be mostly learning how to make WebServer Controls. You can view and buy some of the controls from my website www.azamsharp.cjb.net.

This will take me some sleepless nights but somethings have to be done in certain time.

"Knowledge is power"


Friday, December 10, 2004

FireFox kicks IE Butt

All my life I have been installing different softwares so that my IE wont open pop up windows and run faster. The easy solution is to just switch to FireFox browser.

This is the best internet browser I have ever seen.

Download FireFox:

http://www.mozilla.org/products/firefox/


Returning class object or the DataSet

Suppose you have a class:

public class Person
{
private string _name;
private string _code;

public Person()
{
_name = null;
_code = null;

}

public string Name
{

get { return _name; }

}


}

Now there is another class which use the Person class:

public class getDetails
{

Person person = new Person();
getPhoneNumber(person.Name); // This will return the person name
.
.
.
return person // returns the whole Person object

}

Another way of returning the data can be of using DataSet. We query in the database and populate the dataset using the result of that query.

The question is when to use what approach. When we simple want to display the data on the client side we should use dataSet, having said so also remember that dataset can also be traversed but its a tiring process.
On the other hand if we would like to make some calculations on the returned data we can use the return object type approach.


Sunday, December 05, 2004

Line breaks in the Xml file while reading the path

my fellow developer found this interesting feature. If you have an Xml file that contains the path to the harddrive. Something like this:


C:\temp\myfile.pdf


This will retrieve the path fine but look the following Xml file:


C:\temp\myfile
.pdf



If you retrieve the path from this xml file you will get something like this in the string.
string filePath = "\r\n"

Which is the code for the return character and the new line character. You should not leave any spaces when specifying the path in the xml file.

Friday, December 03, 2004

Splitting

Here is a simple code to split the UserName from the Domain Name.

One way of doing this:

string s1 = "GEEK/author";
string s2;
int idx = s1.IndexOf('/');
if (idx != -1)


{ s2 = s1.Substring(idx + 1);}

else
{ // do some error handling}



Here is another version of the same code:


private bool IsAuthenticated()
{

// Here get getIdentity simple returns the "GEEK\author"
int indexValue = getIdentity().IndexOf('\\') + 1;
return getIdentity().Substring(indexValue) == AUTHENTICATEDUSER ? true : false;
}


Here is another way:

if(username.endswith("//author"))
{
// Authenticated
}


Thursday, December 02, 2004

Disco file code can't be generated

This error is really annoying since it does not really tells whats wrong. Error is generated when you try to make a proxy of your web service which does not contain WebMethods.

So always have one dummy methods before adding a proxy for the client.

Tuesday, November 30, 2004

WindowsIdentity, WindowsPrinciple and Role based security

Here is a small code snippet I wrote to show how to use WindowsIdentity, WindowsPrinciple objects and Role based security.


// Tells the clr which principal is in use
AppDomain.CurrentDomain.SetPrincipalPolicy(PrincipalPolicy.WindowsPrincipal);


// Gets the identity of the current user
WindowsIdentity wi = WindowsIdentity.GetCurrent();


// prints the name of the current windows user
Console.WriteLine(wi.Name);


// prints the type of the authentication
Console.WriteLine(wi.AuthenticationType);


// make an object of WindowsPrinciple
WindowsPrincipal prin = new WindowsPrincipal(wi);


// prints the name of the current windows user
Console.WriteLine(prin.Identity.Name);

// checks if the user is an Administrator return false if not else return true
// This is where we check for the role based security
Console.WriteLine(prin.IsInRole(WindowsBuiltInRole.Administrator));



Sunday, November 28, 2004

Sending credentials to WebService

Sometimes you need to send your windows credentials to the webservice. A simple way can be to use Network credentials provided by Microsoft.net framework.

The credentials are made on the webservice proxy.

MyWebService.Service1 proxy = new MyWebService.Service1();
proxy.Credentials = new NetworkCredential("Administrator","adminPassword");

Now if you have windows integrated security turned on ( It can be turned on from IIS ) it will only allow those users who have the windows login credentials and other users will get the 401 Access denied error.

Saturday, November 27, 2004

Reading Xml what to choose ??

When reading Xml files you can choose XmlReader or XmlDocument. Each has a different purpose. XmlReader is a forward only non cached way of reading Xml documents. It does not remember that it passes through.

On the other hand using XmlDocument gives you advantage of jumping from one node to the other. Once an xml file is loaded into XmlDocument object , it knows the structure of the xml document and waits for your commands.

Friday, November 26, 2004

Cannot create offline cache (error while creating asp.net project)

After sitting infront of computer for 2 hours and trying to solve this crazy error which was generated each time I try to create asp.net application.

"Unable to create the offline cache in c:\inetpub\Username\wwwroot"

It really is annoying and the this is a bug in Vs.net which will be fixed in Vs.net 2005. I solved this problem by moving my directory outside the wwwroot. So I create the project in C:\inetput and it works.

Some people also solve this problem by installing Visual Studio.net 2003 from scratch.

Sunday, November 21, 2004

Converting ArrayList to the Class Array

Hi,

Sometimes we have data in the ArrayList and we need to convert it to our class type array.
ArrayList provides a method of ToArray that converts an ArrayList to the type of our class array.

here is what we can do:

return (Person[]) aList.ToArray(typeof(Person));

Here aList is the ArrayList.


Friday, November 19, 2004

Java Client connection to .net Web Service

I have just uploaded an article about "How to make a Java client that connects to an .net Web Service".

You can view my article on my website under articles link.

www.azamsharp.cjb.net


Security Attributes in Microsoft.net

You can use windows credentials on any method you like by simple placing a Security Attribute on that method. In the code sample below I just used the user coscmasm which belongs to the LAB563 Domain. So, if you log in to your windows using coscmasm only than you can use the getName method.


using System;
using System.Security.Permissions;
using System.Security.Principal;

public class Foo
{
[PrincipalPermissionAttribute(SecurityAction.Demand, Name=@"LAB563\coscmasm")]
public void getName()
{
Console.WriteLine("This is coscmasm");
}
}
class App
{
static void Main()
{
AppDomain.CurrentDomain.SetPrincipalPolicy(
PrincipalPolicy.WindowsPrincipal);
try
{
Foo f = new Foo();
f.getName();
}
catch(Exception ex)
{
Console.WriteLine(ex.Message);
}
}
}

Friday, October 15, 2004

Value Types

We know that all the primitives types are derived from the System.ValueType.

Have you ever wondered what would happen if you write:

System.ValueType x = 10;

So whats the type of 'x'. If you do a GetType() on x you will find out that the type is Int32. What it does is it assigns 'x' the type dependent upon the value of 'x'.

After the above statement if you say:

x = 23.45;

It will be treated as double Cool right :).

Check my articles on my website www.azamsharp.cjb.net in which I talked about Boxing and UnBoxing you will find more about System.ValueType.

Tuesday, October 05, 2004

NewLine in Repeator Control

You can easily display the data ( Item Template ) on newlines if you use the DIV
Tag. Meaning that inside the DIV tag write the Item Template tag and it will automatically create data or items on newline in the Repeator control.


Sunday, October 03, 2004

IF-ELSE statements

Its really cool to see that sometimes simple if-else conditional statements can be so confusing.

Here is a conditional statement:

if( 1 == 1 ) // You can make any condition it does not matter
string myString = "Hello World";

What do you expect will it run or not ? Well it will not run and give you error "Embedded statement cannot be a declaration"

You can write the same statement correctly if you add the paranthesis like this:

if( 1 == 1 )
{
string myString = "Hello World";
}

Do you find it amazing cause I sure do ?

Sending Parameters to MapQuest QueryString

Its really easy to embed your text with MapQuest QueryString. Like in the url below I did a MapQuest request depending on two zipcodes.

http://www.mapquest.com/directions/main.adp?go=1&do=nw&un=m&2tabval=address&cl=EN&ct=NA&1tabval=address&1y=US&1a=&1c=&1s=&1z=77004&2y=US&2a=&2c=&2s=&2z=77082&idx=0&id=41602f43-002a1-002b4-cdbcf381&aid=41602f43-002a2-002b4-cdbcf381&bs.x=0&bs.y=0

If you look at the URL closely you can see the ZipCodes 77004 and 77082. You can embed your own variables and values in this querystring and get the address/directions depending upon the parameters which are send by you from your own application.

Saturday, October 02, 2004

XML Schema Defination Tool

Just came arround this great tool. Its called XML Schema Defination Tool or xsd. It can convert your C# or VB.NET .cs (class file) to a XML Schema (xsd) file and vice versa.

It can also translates your untyped DataSet to Strongly typed DataSet. For more information see www.msdn.microsoft.com .


Sunday, September 19, 2004

Redirecting in the Catch Block

One of my good friend told me that you cannot Redirect in catch without doing something special. Try writing some code that throws an exception and than in the catch block redirect it to some new page. Something like this:

try {
// write some code that creates an exception
}

catch(Exception ex)
{
// Redirect to other page
Response.Redirect("NewPage.aspx");
}

If you try to do this it will throw System.ThreadingException. In order to do this successfully you need to redirect like this:

Response.Redirect("NewPage.aspx",false);

Here false means that the old page thread will not be discarded and will be removed later on by the GC. Another approach can be using an instance of System.Threading and stopping the thread before the Redirection.


Thursday, September 16, 2004

Could not Lock file strange Access Database Error

I was just trying to populate my datagrid with some data from Access Database and I got this error. Took me 1 hour to solve it. Maybe you people will sometime run into this error. Just copy the database file (.mdb file) to the C:/ or any other directory and Access it, offcourse you are going to ask me if this the best solutions well NO ITS NOT. Its actually the worst solution. The problem this error references is about database being opened more users.

I have not found a good solution yet. Offcourse microsoft suggest to play with Registeries, I don't think I would ever like to do that.

Monday, September 06, 2004

WinCV.exe

WinCV is a tool in Microsoft.net through which you can find all the methods, Interfaces, properties that a certain class contains. Its very usefull if you want to find that if this class implements IDisposible Interface or is this method virtual or not.

Just search in your Microsoft Visual Studio.net folder for WinCV.exe and double click to run it.


Saturday, September 04, 2004

C# 2.0


I recently saw Anders Hejlsberg, Lead Architect of the C# language answering questions on the white board.

He talked about many cool features that they are thinking to add in C# 2.0. One of the features I liked was the functionality to reconize class types.

We all write code like this:

Point p = new Point();

In C# 2.0 you can write the same statement something like this:

var p = new Point();

For complete details visit http://msdn.microsoft.com/msdntv/episode.aspx?xml=episodes/en/20040624csharpah/manifest.xml



Whats wrong in using Static Methods

The question here is that why can't we use static methods in our class instead of making a Singleton pattern. I found the solution and explaination on web. View the code below:

public class A {
public static string staticVariableCopiedFromB = B.staticVariable;
public static string staticVariable = "This is a string defined in A";
}

public class B {
public static string staticVariableCopiedFromA = A.staticVariable;
public static string staticVariable = "This is a string defined in B";
}

public class Test {
static void Main(string[] args)
Console.WriteLine(A.staticVariableCopiedFromB);
Console.WriteLine(B.staticVariableCopiedFromA);
}

Now just try to dry the program. Our common sense suggest that the output of this program should be like this:
This is a string defined in B
This is a string defined in A

Unfortunately this is not the case and you will only see the following output:
This is a string defined in B

Why is that so?
Lets see whats happening in Main().
1) A.staticVariableCopiedFromB: This goes to class A and notices that A.staticVariableCopiedFromB depends upon B.staticVariable, so it goes to B.staticVariable get the string "This is a string defined in B" and assigned to A.staticVariableCopiedFromB.

2) Next is B.staticVariableCopiedFromA: It goes to class B and see that B.staticVariableCopiedFromA depends upon A.staticVariable but then realizes that it was never Initiazed and hence assigns "null" to B.staticVariableCopiedFromA and output nothing.

The problem with static methods is complex Initializations and you never know who can change what and its very hard to find such problems.

Also you cannot override static methods. On the other hand you can Inherit from the Singleton class.


Friday, September 03, 2004

First Blog Entry

Hello Everyone and welcome to my BLOG. Here I will post my thoughts on the .net framework and the languages included in the .net framework.

Thanks everyone,