Monday 24 March 2008

How to find the id within UserControls once rendered as HTML

First, why would we need to find the Id of a UserControl element? When the html is built dynamically .Net will build the ids of a control that is in a UserControl and render the html ids dynamically. So if you wanted to refer to an item that was build in a user control and do something with it in JavaScript for example it wouldn't work as each time the page is rendered client side it could have different ids for that element.

Here is an example of how to get a handle on the correct id.

First lets create a simple UserControl.

Create a web project and add a web user control, calling it Results. On the Results.ascx page at a TextBox control so it looks something like below.

image

Set the Id of the TextBox to tbResults.

Now drop the control onto your default.aspx and preview in browser.

View the source code that has been rendered to the client. You should see something like this:

<textarea name="Results1$tbResults" rows="2" cols="20" id="Results1_tbResults" style="height:84px;"></textarea>


As you can see, rather than the id being as you set it 'tbResults' it has changed; in this case to include the name of the actual control. (obviously in this case every time you run this code it will produce the same, but in more complex controls perhaps using datagrids and multiple controls, it wouldn't quite be as simple).

So how can we gain access to the id when they are built dynamically so that we can programmatically do something with them.

Well lets go to your Results.ascx.cs page and add a bit more code.

We are going to create a property in the component so that we can get the name of the ClientID. We do this through the property available on each control called ClientID (simple really)

Your code should look something like this:

public partial class Results : System.Web.UI.UserControl
{
// a private string to hold the Client id
private string _tbResultsId;

// a string so that we can get the value of the client id
public string tbResultsId
{
get
{
// set the private string to the Client id
_tbResultsId = tbResults.ClientID;

// return the client id
return _tbResultsId;

}
}


protected void Page_Load(object sender, EventArgs e)
{

}

}

We should now be able to get a handle on the ClientID via the tbResultsId property of the control.

We can check if this is working by adding a bit of html to the default.aspx page.

Add the following code under the texbox and then view the default page in a browser.


<br />The actual name of the tbResults is: <%= Results1.tbResultsId %><br />

You should see the in your browser something like this:

image

by outputting the property tbResultsId we were able to render the actual name of the id. So now you have a way of accessing the ids even when built dynamically. This is ideal when you are using JavaScript on rendered controls. Simple output the name in JavaScript using <%= Results1.tbResultsId %> everytime you need to write the name of the id.

Saturday 22 March 2008

Value Types


Stack and Heap

Before explaining value types, I think it is necessary to have a brief overview of memory.

There are two main types of memory types Stack and Heap (I'm sure the purists amongst you will explain that this is not the case and become very technical about it; however for this discussion of types it will suffice)

So what is the difference between the two.

Matthew Cochran has an excellent article to explain the difference, and is worth reading through.

C# Heap(ing) Vs Stack(ing) in .NET:

Value Types

If you have read Matthews article you will know that Value Types are stored on the Stack.

Lets take a look at the three general types

  • Built in types
  • User-defined types
  • Enumeration types
Built in types

These are types that are provided by the .NET Framework. All built in numeric types are value types, examples are:

Type C# alias
System.SByte sbyte
System.Byte byte
System.Int16 short
System.Int32 int
System.Uint32 uint
System.Int64 long
System.Single float
System.Double double
System.Decimal decimal
System.Char char
System.Boolean bool
System.IntPtr - N/A -
System.DateTime date

 

The above table shows the most common value types, there are over 300 others not listed here in the .NET Framework.

Declaring a value type

int i = 0;
bool b = false;


/*
New to .NET 2 is Nullable option.
This allows you to set an integer or a boolean for example to not assigned
*/
Nullable<bool> b = null;

// This can also be written as
bool? b = null;



 Once a value has been declared as Nullable you can then use the HasValue  and Value members.


if (b.HasValue)

{


    lblMessage.Text = string.Format("b is {0}", b.Value);


}



 



User-defined Types (Structures / Struct)



Structures behave similar to Classes except the values are stored on the stack. Structures are built from other value types. For example you may have a Struct that you would use for ExamDates.



protected void Page_Load(object sender, EventArgs e)
{



    DateTime MyStartDate = DateTime.Now;

ExamDates MyExam = new ExamDates(MyStartDate);
lblMessage.Text = MyExam.ToString();

}



struct ExamDates
{
DateTime startDate;
public ExamDates(DateTime _startDate)
{
_startDate = _startDate.AddDays(30);
startDate = _startDate;
}
public override string ToString()
{
return string.Format("The exam date is {0}", startDate);
}
}


 



What the above does is create a user-defined type of ExamDates that takes one parameter of a start date of the exam. 30 Days are added to the start date to get the exam date. We have overridden the ToString() method  so that it always returns text about the exam date.



Enumerator Types



Enumerators are used to supply a list of choice. For example for an enumerator that uses the type of exam we are doing, we could use the following



// C#



enum Courses : int { MCTS_70536, MCTS_70528, MCPD_70547};



Courses MyCourse = Courses.MCPD_70547;

MCTS / MCPD

A few of the staff at work are working towards the Microsoft Certified Professional Developer (MCPD) in Web Development. To achieve this they need to pass three exams. Two for the MCTS and one for the MCPD.

 

Microsoft Certified Technical Specialist (MCTS)
Consists of two exams.

The first:

  • 70-536: Microsoft .NET Framework 2.0 - Application Development Foundation 

And for the Web Development version of the MCPD you need the second part of the MCTS

  • 70-528: Microsoft .NET Framework 2.0 - Web-Based Client Development.

Microsoft Certified Professional Developer (MCPD)
Finally to achieve the MCPD

  • 70-547: Designing and Developing Web Applications by Using the Microsoft .NET Framework

 

MCTS MCPD
70-536 70-547
70-528:  

 

Over the coming months I am planning to blog about various sections of the course that might be useful to someone who is working their way through the MCTS / MCPD.

You should also be able to find further information on the Global Travel Group - Ecommerce team blog

Monday 17 March 2008

Using Cookies C# ASP.Net

c# Cookies

Part 1- Using cookies

The easy way...

How to store a single value in a cookie

Response.Cookies["name"].Value = "Sean Tiernan";

Multiple values

This example shows how to write a cookie with multiple key value pairs in the cookie UID

Response.Cookies["UID"]["firstname"] = "Sean";
Response.Cookies["UID"]["surname"] = "Tiernan";


How to read information from a cookie



// Check if cookie exists

if (Request.Cookies["UID"] != null)


{


    // Read cookie information - firstname into a string called firstname

  
firstName = Server.HtmlEncode(Request.Cookies["UID"]["firstname"]);


// Assign to a textbox

    tbFirstName.Text = firstName;



// Read surname into a string called surname

    surname = Server.HtmlEncode(Request.Cookies["UID"]["surname"]);


// Assign to a text box

    tbSurname.Text = surname;



}




Thursday 13 March 2008

Running IIS on XP Home

I use Visual Studio 2005 and wanted to use IIS to test publishing a site to, but only have XP Home on my PC upstairs in my office so need to find a way to get IIS running on XP Home. I know I can hear you saying it now .... "You should upgrade to XP Professional". However let me explain why I didn't want to do this an my frustration.

I have a full (legit) version of Windows XP professional that I bought as an upgrade to a laptop (this has since died and is now in little pieces, but that's another story!). As I have an upgrade the most logical thing to do is upgrade my XP Home to XP professional.

Here is my dilemma - The XP Professional is SPK 1 and the XP Home has SPK 2. Windows doesn't allow you to upgrade to XP Professional SPK 1 it needs to be SPK 2.

OK the next step would be to somehow upgrade the XP Pro SPK 1 to XP Pro SPK 2. I found a way to do this using slipstream, at least that's what I thought. I tried several times to get this working, but every time it crashed the OS and I had to do a complete re-install of XP Home. So I finally gave up on the upgrade and I have done without the extra facilities that the Pro version provided.

To be honest the only thing I missed was the ISS. Which brings me back to the reason why I didn't want to pay for another upgrade, when I already have bought one when all I need is IIS.

So ... back to going about installing the IIS.

I discovered that this was possible with a few tweaks of the system.

I can't claim any of these methods of my own, but thought I would share them with you here. I did have to overcome a slight problem which I will cover shortly.

The crux of the installation is that you will need Windows 2000 to get IIS off.

  1. change the sysoc.inf file located at C:\Windows\Inf\sysoc.inf

    and change the iis entry from

    iis=iis.dll,OcEntry,iis.inf,hide,7

    to this

    iis=iis2.dll,OcEntry,iis2.inf,,7

  2. copy the iis.dl_ and iis.in_ from the Win 2000 CD and expand it to a temp file

  3. Copy the iis.dll and iis.inf files to

    c:\windows\System32\Setup and c:\windows\inf respectfully

  4. Goto Add and remove programs and you should now see the option to add IIS under the windows components

    You will need to change the default user name in Directory Security in IIS for you Default web site from IUSR_NAME so that it uses the computer name as well so it will say YOURCOMPUTERNAME\IUSR_NAME

    A full explanation can be found on adamv.com

    As mentioned though I did have a few problems after get it installed. I set up the permission and ran some test .htm pages, and they all worked fine. However I couldn't run .asp page. So I tried following the suggestions on Brooks Younce pages.

    How to Fix it! (if nothing else can!)
    Open "Control Panel" and then "Administrative Tools" then Open "Services"...
    Locate the "Distributed Transaction Coordinator" make sure the process is "Started" and "Automatic"
    (If its not, open a command line and type "msdtc -install", then try and start the service)
    Open a command line and type the following...
    cd %windir%\system32\inetsrv
    rundll32 wamreg.dll, CreateIISPackage (NOTE: "CreateIISPackage" must be typed exactly; it is case-sensitive.)
    regsvr32 asptxn.dll (wait for a dialog box to notify you asptxn has registered correctly)
    IISRESTART
    Open "Control Panel" then "Component Services"...
    You should see all three IIS COM+ applications that have been recreated

    - http://www.brooksyounce.com

    It took a while to get the Distributed Transactions Coordinator installed, but finally got there.

    This however still didn't solve the problem.

    After much digging I finally found out what the answer was. All it was in the end was another permission setting.

    In the Component Services you need to edit the properties of the
    IIS Out-Of-Process Pooled Applications

    image

    You need to change the identity to use the System account

    image

    I now have a working version of IIS on my XP Home without buying another version of the upgrade.

    Technorati Tags: ,,

    Sunday 9 March 2008

    Plugins for Windows Live Writer

    Just installed a few plugins for Live Writer.

    I quite like this one for posting Polaroid type images. Just choose any image set the angle and add a caption - really simple.

    Windows live Writer

    Just downloaded and installed the windows live writer and this is the post using the software.

    Its seems quite easy to use anyone who uses word will have no problem using it.

     

    It has some nice features like adding maps.

    Map image

    I will install this on my laptop so that I can start to write things when I am away from home.

    Ok, lets see if this will publish.