Tuesday, October 26, 2004

Redirecting to a page inside a Frameset using Response.Redirect()

Some times we might have to use Framesets and when we want to redirect a page to another frame on the page, here is the script to do itJust a simple javascript to be rendered.

Response.Write(" script window.open('login.aspx','_top'); script")

or......

Response.Write("script window.parent.frames[2].location='http://lion/page.aspx?'; script ") ;

Monday, October 25, 2004

How to create a ShutDown command using C#

Did we run into a problem sometimes, we felt the need to restart the computer after installation of a DOTNet package,

This is how you can do it, using C# code.
Nice piece of code!!!...
have a look............

Link - http://www.mentalis.org/soft/class.qpx?id=7

Tuesday, October 19, 2004

Changing the server name after installing SQL server.

There are many a times when we might have to change our system name after installing SQL server and SQL might throw an error during some operations,
You need to change the srvname fields in the sysservers table in the master DB, but this cannot be done directly form the table view, as ad-hoc updates to this table is not allowed, below is an sp using which we can achieve the task.

****For Default Instance****
sp_dropserver
go
sp_addserver , local
go

****Foa a named instance****
sp_dropserver
go
sp_addserver , local
go

For more info and FAQs check this link.
http://support.microsoft.com/kb/257716/en-us

Monday, October 18, 2004

Getting the Name of the Printer attached using C# Code

Use printer admin object (prnadmin.dll)

Here is the snippet...
Dim tObjPrinter As Object

Private mObjPrintMaster As Object

Try

mObjPrintMaster = CreateObject("PrintMaster.PrintMaster.1")

tObjPrinter = CreateObject("Printer.Printer.1")

mObjPrintMaster.PrinterGet("",PrinterName , tObjPrinter)

mObjPrintMaster.DefaultPrinter = mStrPrinterName

mObjPrintMaster.PrinterSet(tObjPrinter)

Catch ex As Exception

End Try

Thursday, October 14, 2004

Change DotNet Policy settings thro Code

Once upon a time, i was very desperate to get a piece of windows control work for a web, i needed some code to change the policy settings, so it was then when i stumbled at this wonderful piece of code that describes how to change policy and assembly trust settings through code.

the orignal url for the article goes like this.

http://blogs.msdn.com/shawnfa/archive/2004/09/09/227534.aspx

1
2 Modify the security policy to give an assembly FullTrust from the LocalIntranet
3
4
5 This method modifies the machine policy level and adds a code group that
6 matches the given application's key and name but does not take into account
7 version information.
8
9 If the policy is set up in a way that is different from the default CLR security policy,
10 this method may not produce the intended results. Assuming a default security policy, the
11 goal of this method is to produce a policy that looks like this:
12
13 Machine level:
14 1. All code: Nothing
15 1.1 Zone - MyComputer: FullTrust
16 1.1.1 StrongName - MS Key: FullTrust
17 1.1.2 StrongName - ECMA Key: FullTrust
18 1.2 Zone - Intranet: LocalIntranet
19 1.2.1 All code: Same site Web
20 1.2.2 All code: Same directory FileIO
21 1.2.3 StrongName - appKey, assemblyName: FullTrust
22 1.3 Zone - Internet: Internet
23 1.3.1 - All code: Same site Web
24 1.4 Zone - Untrusted: Nothing
25 1.5 Zone - Trusted: Internet
26 1.5.1 All code: Same site Web
27
28 assembly to grant FullTrust form the Intranet
29 Key of the assembly
30
31 If or are null
32
33
34 If is empty
35
36 true if the policy was modified, false otherwise
37 public static bool TrustIntranetAssembly(string assemblyName, StrongNamePublicKeyBlob appKey)
38 {
39 Debug.Assert(assemblyName != null && assemblyName != String.Empty, "assemblyName cannot be empty");
40 Debug.Assert(appKey != null, "appKey cannot be null");
41
42 if(assemblyName == null)
43 throw new ArgumentNullException("assemblyName");
44 if(assemblyName == String.Empty)
45 throw new ArgumentOutOfRangeException("assemblyName", assemblyName, "assemblyName cannot be empty");
46 if(appKey == null)
47 throw new ArgumentNullException("appKey");
48
49 bool addedGroup = false;
50
51 IEnumerator policyEnumerator = SecurityManager.PolicyHierarchy();
52
53 iterate over each policy level until we find the machine level group
54 while(policyEnumerator.MoveNext())
55 {
56 PolicyLevel policyLevel = policyEnumerator.Current as PolicyLevel;
57 Debug.Assert(policyLevel != null, "Unexpected object in policy enumerator");
58
59 if(policyLevel.Label.Equals("Machine"))
60 {
61 get a list of all the code groups on the machine level
62 CodeGroup root = policyLevel.RootCodeGroup;
63 IList children = root.Children;
64
65 iterate over each child until we find the LocalIntranet zone
66 for(int i = 0; i < children.Count; i++)
67 {
68 CodeGroup currentGroup = children[i] as CodeGroup;
69 Debug.Assert(currentGroup != null, "Unexpected object in code group's children");
70
71 if(currentGroup.Name.Equals("LocalIntranet_Zone"))
72 {
73 create permission objects that can be used to give the application FullTrust
74 IMembershipCondition membershipCondition = new StrongNameMembershipCondition(appKey, assemblyName, null);
75 PermissionSet permissionSet = new PermissionSet(PermissionState.Unrestricted);
76 PolicyStatement statement = new PolicyStatement(permissionSet);
77
78 now combine these objects into a CodeGroup
79 CodeGroup appCodeGroup = new UnionCodeGroup(membershipCondition, statement);
80 appCodeGroup.Description = String.Format("Allow {0} to run off the Intranet with FullTrust", assemblyName);
81 appCodeGroup.Name = assemblyName;
82
83 and make this CodeGroup a child of the Intranet zone
84 currentGroup.AddChild(appCodeGroup);
85 addedGroup = true;
86 break;
87 }
88 }
89 break;
90 }
91 }
92
93 Commit the changes to the policy
95 if(addedGroup)
95 SecurityManager.SavePolicy();
96
97 return addedGroup;
98 }

The CodeGroup.Children property (called at line 63) returns a copy of the child nodes, not a reference to the underlying child node collection. Modifying an item from this copy won't do much to alter the actual policy hierarchy.
To fix this, one would need to remove the LocalIntranet_Zone group from its parent group, then add the modified copy back as a new child. The "quick fix" version of this would be to add the following lines between your lines 84 and 85:
root.RemoveChild(currentGroup); root.AddChild(currentGroup);
There would still be at least two remaining problems:
1. Neither your original code nor my modification account for the possibility of concurrent modifications to the policy. The only way to be sure that no other process has modified the saved policy between the read and the write would be to place a write lock on the underlying file (security.config in this case) before starting the read. Of course, this would probably block the various SecurityManager operations as well, which means one would need to modify the file's XML directly.
2. Members of the local Users group cannot write to the underlying security configuration files, so policy modification is not functionality that should really be built into very many applications via code like this.

A story about a Cracked Pot..........a good Moral.....

Cracked Pots

A water bearer in China had two large pots, each hung on the ends ofa pole which he carried across his neck. One of the pots had a crackin it, while the other pot was perfect and always delivered a full portionof water.

At the end of the long walk from the stream to the house, the crackedpot arrived only half full. For a full two years this went on daily, withthe bearer delivering only one and a half pots full of water to his house.

Of course, the perfect pot was proud of its accomplishments, perfectfor which it was made. But the poor cracked pot was ashamed of its ownimperfection, and miserable that it was able to accomplish only half ofwhat it had been made to do.

After 2 years of what it perceived to be a bitter failure, it spoke to thewater bearer one day by the stream. "I am ashamed of myself, andbecause this crack in my side causes water to leak out all the way backto your house."

The bearer said to the pot, "Did you notice that there were flowers onlyon your side of the path, but not on the other pot's side?

That's because I have always known about your flaw, and I plantedflower seeds on your side of the path, and every day while we walkback, you've watered them.

For two years I have been able to pick these beautiful flowers to decoratethe table. Without you being just the way you are, there would not be thisbeauty to grace the house"

Moral: Each of us has our own unique flaws.
We're all cracked pots.But it's the cracks and flaws we each have that make our lives together so very interesting and rewarding. You've just got to take each person for what they are, and look for the good in them.

Blessings to all our crackpot friends.

Email Address Validation in C# using RegEx Pattern

Sometimes there may arise a situation where in we need to validate an email address through code using C#.
This is a sample to do it.
Ex code to do it using the regex libraries.
It's an incredibly complex regular expression to be compliant with RFC822

using System.Text;
using System.Text.RegularExpressions;
using System.Text.RegularExpressions.Regex;

public static bool ValidateEmailPattern(string String)
{
Regex mailPattern = new Regex(@"^([a-zA-Z0-9_\-\.]+)@([a-zA-Z0-9_\-\.]+)\.([a-zA-Z]{2,5}){1,25}$");
return (mailPattern .IsMatch(String));
}

the string is the email address, u need to send the string and the function returns true if its good, or false if it does not match.

Check this link for further reading
http://www.thecodeproject.com/csharp/rfc822validator.asp


Monday, October 11, 2004

How to add a Image URL picker property to a Control

***adding a image URL picker property****
//Set the attribute of the property to use the ImageURLEditor type.

Editor(typeof(System.Web.UI.Design.ImageUrlEditor), typeof(System.Drawing.Design.UITypeEditor))

Adding a Collection Editor property to a custom control

**This sample shows how to add a collection editor window property to a Custom Control**


using System;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.ComponentModel;
namespace ControlSampleLibrary
{
// This is my object class.
public class ClassObj
{
private string _ObjectString;
public string ObjectString
{
get { return _ObjectString; }
set { _ObjectString = value; }
}
public ClassObj() { _ObjectString = string.Empty; }
public ClassObj(string s) { _ObjectString = s; }
public override bool Equals(Object obj)
{
if (obj==null GetType() != obj.GetType()) return false;
if (ObjectString!=((ClassObj)obj).ObjectString) return false;
return true;
}
public override int GetHashCode()
{
int x = 0;
return x;
}
}
// This is the modified type-specific collection.
public class ClassColl : System.Collections.CollectionBase
{
public int Add(ClassObj obj) { return List.Add(obj); }
public void Insert(int index, ClassObj obj) { List.Insert(index, obj); }
public void Remove(ClassObj obj) { List.Remove(obj); }
public bool Contains(ClassObj obj) { return List.Contains(obj); }
public void CopyTo(ClassObj[] array, int index) { List.CopyTo(array, index); }

public int IndexOf(object obj)
{
if (obj is int)
return (int)obj;
if (obj is string)
{
for (int i = 0; i < List.Count; i++)
if (((ClassObj)List[i]).ObjectString == obj.ToString())
return i;
return -1;
}
else
{
throw new ArgumentException("Only a string or an integer is permitted for the indexer.");
}
}
public ClassObj this[object obj]
{
get { return (ClassObj)List[IndexOf(obj)]; }
set { List[IndexOf(obj)] = value;}
}
}

// This is the Web server control.
[ToolboxData("<{0}:SampleControl runat=server>")]
public class SampleControl : System.Web.UI.WebControls.WebControl
{
private ClassColl _Col = new ClassColl();
[Category("Things")]
[PersistenceMode(PersistenceMode.InnerProperty)]
public ClassColl Col
{
get { return _Col; }
}
protected override void Render(HtmlTextWriter output)
{
output.Write(this.ToString());
}
}
}

DOTNET reinstall script

*****This Script Corrects broken dll links, handy script if ur DOTNet installation does something funny......*****
*****write copy the entire script and save as a batch file.
***if u r typing from the command prompt, ignore the lines that start with "Echo", type only the commands below the Echo line.

Echo Stop IIS
iisreset /stop

echo "----------------------"

echo "Deleting the ASPNET account."
net user ASPNET /delete

echo "----------------------"

echo "Reregistering ASP.NET and the ASPNET account."
aspnet_regiis -i

echo "Restarting IIS."
iisreset /start

echo "----------------------"

Getting the Running Process and to Kill a process

'The RunningPrcs array contains all the process in the m/c.

Dim RunningPrcs() As Diagnostics.Process
Dim Currprcs As Diagnostics.ProcessRunningPrcs = Diagnostics.Process.GetProcesses()

'The following code enumerates through all the processes and kills a particular 'process based on a condn.

For Each Currprcs In RunningPrcs
If Currprcs.ProcessName = "YOUR PROCESS"
Then
Currprcs.Kill()
End If
Next

For more info check this link in ms site
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpref/html/frlrfsystemdiagnosticsprocessclassgetprocessestopic2.asp

Sample code to create and load data to a dataset manually

********Sample code to create a Dataset, Datatable and adding data to the Dataset*********


DataSet dummyDataSet=new DataSet("dummyDataSet");
DataTable dummyTable=new DataTable("dummyTable");
ArrayList dmcol=new ArrayList();
dmcol.Add("myval1");
dmcol.Add("myval2");
dmcol.Add("myval3");
dmcol.Add("myval4");
int i;
dummyDataSet.Namespace= "Your NameSpace";
DataColumn c2 = new DataColumn("User");
DataColumn c1 = new DataColumn("Action");
DataColumn c3 = new DataColumn("Time");
dummyTable.Columns.Add(c1);
dummyTable.Columns.Add(c2);
dummyTable.Columns.Add(c3);
dummyDataSet.Tables.Add(dummyTable);

// Add rows.
DataRow newRow;
for(i=0; i "lessthan" dmcol.Count; i++)
{
newRow = dummyTable.NewRow();
newRow["User"]= dmcol[i].ToString();
newRow["Time"]= dmcol[i].ToString();
newRow["Action"]= dmcol[i].ToString();
dummyTable.Rows.Add(newRow);
}//ends for loop

dummyDataSet.AcceptChanges();


Using XML TextWriter to create an XML file

**********This code sample shows how to use XML text writer to create an XML file********


string XmlFile;
System.IO.DirectoryInfo directoryInfo;
System.IO.DirectoryInfo directoryXML;

//Get the applications startup path
directoryInfo = System.IO.Directory.GetParent(Application.StartupPath);

//Set the output path
if (directoryInfo.Name.ToString() == "bin")
{
directoryXML = System.IO.Directory.GetParent(directoryInfo.FullName);
XmlFile = directoryXML.FullName + "\\" + OutputFileName.Text;
}
else
{
XmlFile = directoryInfo.FullName + "\\" + OutputFileName.Text;
}

//create the xml text writer object by providing the filename to write to
//and the desired encoding. If the encoding is left null, then the writer
//assumes UTF-8.
XmlTextWriter XmlWtr = new System.Xml.XmlTextWriter(XmlFile,null);

//set the formatting option of the xml file. The default indentation is 2 character spaces.
//To change the default, use the Indentation property to set the number of IndentChars to use
//and use the IndentChar property to set the character to use for indentation, such as the
//tab character. Here the default is used.
XmlWtr.Formatting=Formatting.Indented;

//begin to write the xml document. This creates the xml declaration with the version attribute
//set to "1.0".
XmlWtr.WriteStartDocument();

//start the first element.
XmlWtr.WriteStartElement("customers");

//create our first customer element.
//this is a child element of the customers element.
XmlWtr.WriteStartElement("customer");

//writes the entire element with the specified element name and
//string value respectively.
XmlWtr.WriteElementString("name", "Kevin Anders");
XmlWtr.WriteElementString("phone", "555.555.5555");

//end the customer element.
XmlWtr.WriteEndElement();

//create another customer.
XmlWtr.WriteStartElement("customer");
XmlWtr.WriteElementString("name", "Staci Richard");
XmlWtr.WriteElementString("phone", "555.122.1552");

//end the second customer element.
XmlWtr.WriteEndElement();

//end the customers element.
XmlWtr.WriteEndElement();

//now end the document.
XmlWtr.WriteEndDocument();

//now flush the contents of the stream.
XmlWtr.Flush();

//close the text writerj and write the xml file.
XmlWtr.Close();
statusBar1.Text = "Output file has been written";
}
}

Writing an XML to Excel using XSL Transform

******This example shows how to write an XML to an excel file using XSLT*******

///******Write this code block on the page code behind file******///

//if outputting content to Webpage uncomment these 2 lines below.
// Response.ContentType = "application/vnd.ms-excel";
// Response.Charset = "";
DataSet ds = new DataSet();
ds.ReadXml( @"E:\Kannan\XMLtoExcel Sample APP\sampleXML.xml");
XmlDataDocument xdd = new XmlDataDocument(ds);
XslTransform xt = new XslTransform();
xt.Load(@"E:\Kannan\XMLtoExcel Sample APP\xslSheet.xsl");
FileStream fs = new FileStream("c:\\test1.xls",FileMode.Create);
using (fs)
{
xt.Transform(xdd, null, fs);
}

///**************************XSL Style sheet file code*************************///
//Copy the contents and save the file as .XSL


xmlns="urn:schemas-microsoft-com:office:spreadsheet"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:msxsl="urn:schemas-microsoft-com:xslt"
xmlns:user="urn:my-scripts"
xmlns:o="urn:schemas-microsoft-com:office:office"
xmlns:x="urn:schemas-microsoft-com:office:excel"
xmlns:ss="urn:schemas-microsoft-com:office:spreadsheet" >

xmlns:o="urn:schemas-microsoft-com:office:office"
xmlns:x="urn:schemas-microsoft-com:office:excel"
xmlns:ss="urn:schemas-microsoft-com:office:spreadsheet"
xmlns:html="http://www.w3.org/TR/REC-html40">




































Example to Read an Excel file using ADO.net using Excel file as Datasource using VB.net

******Example to Read an Excel file using ADO.net using Excel file as Datasource*******

' Create connection string variable. Modify the "Data Source" parameter as
' appropriate for your environment.
Dim sConnectionString As String = "Provider=Microsoft.Jet.OLEDB.4.0;" _
& "Data Source=c:\ExcelData.xls" _
& ";" & "Extended Properties=Excel 8.0;"

' Create the connection object by using the preceding connection string.
Dim objConn As New OleDbConnection(sConnectionString)

' Open connection with the database.
objConn.Open()

' The code to follow uses a SQL SELECT command to display the data from the worksheet.
' Create new OleDbCommand to return data from worksheet.
Dim objCmdSelect As New OleDbCommand("SELECT * FROM [Sheet1$]", objConn)

' Create new OleDbDataAdapter that is used to build a DataSet
' based on the preceding SQL SELECT statement.
Dim objAdapter1 As New OleDbDataAdapter

' Pass the Select command to the adapter.
objAdapter1.SelectCommand = objCmdSelect

' Create new DataSet to hold information from the worksheet.
Dim objDataset1 As New DataSet

' Fill the DataSet with the information from the worksheet.
objAdapter1.Fill(objDataset1, "XLData")
objDataset1.WriteXml("C:\testxmlfile.xml", XmlWriteMode.WriteSchema)

' Build a table from the original data.
DataGrid1.DataSource = objDataset1.Tables(0).DefaultView
DataGrid1.DataBind()

' Clean up objects.
objConn.Close()

Function to Check special characters in text box in C#

//Copy and paste this function in the code behind file in C#.
//Call this function to check for special charecters in a text field.

private bool checkSpecialChars(string[] stringtochk)
{
bool nochkspchr = false; int i = 0; char[] ch = {'!','@','#','$','%','^','&','(',')','- ','_','+','=','\\','','{','}','[',']','?','<','>','.',',','~','`'};

while(i < stringtochk.Length)
{
if ((stringtochk[i].IndexOfAny(ch)) == -1)
nochkspchr = true;
else
{
MessageBox.Show("Cannot have special characters, Please enter valid characters [A-Z][a-z][0-9]","Configuration Manager",MessageBoxButtons.OK,MessageBoxIcon.Warning);
nochkspchr = false;
return false;
}
i++;
}
return nochkspchr;
}

JavaScript code block for Smart Navigation

function Unload()
{
var XPOS, YPOS;
<% if (bMovePlace){%>
XPOS = document.body.scrollLeft + event.x;
YPOS = document.body.scrollTop + event.y;
<% }%> <% else {%>
XPOS = <% = iscrXPos%>;
YPOS = <% = iscrYPos%>;
<% }%>
SetCookie("XPOS", XPOS) SetCookie("YPOS", YPOS) }

function Load()
{
var XPOS, YPOS;
<% if (bMovePlace == false){%>
XPOS = <% = iscrXPos%>;
YPOS = <% = iscrYPos%>;
SetCookie("XPOS", XPOS) SetCookie("YPOS", YPOS) <% }%>
XPOS = GetCookie("XPOS");
YPOS = GetCookie("YPOS");
if ((XPOS != null) && (YPOS != null))
window.scrollBy(XPOS, YPOS);

RTFEdit_Desc.document.body.innerHTML = window.document.forms(0).Hidden_Desc.value + "
" + window.document.forms(0).Hidden_Add_Desc.value;
}

function SetCookie(name, value)
{
document.cookie = name + "=" + escape(value)
}

function getCookieVal (offset)
{
var endstr = document.cookie.indexOf (";", offset);
if (endstr == -1) endstr = document.cookie.length;
return unescape(document.cookie.substring(offset, endstr));
}

function GetCookie (name)
{
var arg = name + "=";
var alen = arg.length; var clen = document.cookie.length;
var i = 0;
while (i < clen)
{
var j = i + alen;
if (document.cookie.substring(i, j) == arg) return getCookieVal (j);
i = document.cookie.indexOf(" ", i) + 1;
if (i == 0) break;
}
return null;
}

Setting the default button that should submit the form when enter key is pressed

How can we set the default button that should submit the form and raise its Click event on the server when the enter key is pressed on the form
.NET Classes used : System.Web.UI.Control
It is usual for a web form to have more than one button control. How can you set the default button that should submit the form and raise its Click event on the server when the enter key is pressed on the form?
The textbox and the other input controls don't have a property that allow you to specify such a default button.
The answer is in a simple client-side javascript function called whenever a button is pressed, that, if the button pressed is the Enter key, cancels the default submit and simulates a click on the wanted button. Here's the function, that you can copy and paste as-is into your ASPX pages, or that you can paste into a separate .js file, referenced by any ASPX page that needs it:

< language="javascript">
function KeyDownHandler(btn)
{
// process only the Enter key
if (event.keyCode == 13)
{
// cancel the default submit
event.returnValue=false;
event.cancel = true;
// submit the form by programmatically clicking the specified button
btn.click();
}
}
< /script>

Now, in the input controls declaration you just have to call this function when a button is pressed, by handling the onKeyPressed client-side event, and pass a reference to the default button:


< runat="server" id="FN" onkeydown= "KeyDownHandler(DefButton)">


Common Regular Expression Patterns

Integer "^[0-9]";

VarCharSmall "^([a-zA-Z0-9\s]{0,50})$";

VarCharBig "^([a-zA-Z0-9\s]{0,255})$";

Date(MM/DD/YYYY) "^((0[1-9])(1[0-2]))\/((0[1-9])(1\d)(2\d)(3[0-1]))\/((\d{4}))$";

Date(DD/MM/YYYY) "^(((0[1-9])(1\d)(2\d)(3[0-1])))\/(0[1-9])(1[0-2]))\/((\d{4}))$";

PasswordChar "^([a-zA-Z0-9@*#]{8,15})$";

EmailAddress "^([a-zA-Z0-9_\-])([a-zA-Z0-9_\-\.]*)@(\[((25[0-5]2[0-4][0-9]1[0-9][0-9][1-9][0-9][0-9])\.){3}((([a-zA-Z0-9\-]+)\.)+))([a-zA-Z]{2,}(25[0-5]2[0-4][0-9]1[0-9][0-9][1-9][0-9][0-9])\])$";

PhoneNumber(US) "^1?\s*-?\s*(\d{3}\(\s*\d{3}\s*\))\s*-?\s*\d{3}\s*-?\s*\d{4}$";

PhoneNumber(International) "^\d(\d-){7,20}";

Getting a Control's Property using Reflection

******this code block loops thro the controls and gets the associated text entered in the TextBox using Reflection******

foreach(Control c in this.Controls)
{
if(c.ToString() == "System.Web.UI.TextBox")
{
PropertyInfo p1 = c.GetType().GetProperty("Text");
string strVal = p1.GetValue (c,BindingFlags.GetProperty,null,null,null).ToString();
}
}

Code to check for CAPS Lock Mode

state = NativeMethods.GetKeyState(0x14 /*VK_CAPTIAL*/);
capsKeyDown = Convert.ToBoolean(NativeMethods.HIWORD(state));
capsKeyON = Convert.ToBoolean(NativeMethods.LOWORD(state));

if((state == -127 state == 1 ) && capsKeyON == true)
{
pictureBox1.Visible = true;
}
else if((state == -128 state == 0) && capsKeyON == false)
{
pictureBox1.Visible = false;
}

Persisting a Property value for a Web Control

//This code block shows how to persist a boolean property value in a web control.

[
Bindable(true),
Category("Behaviour"),
DefaultValue(true),
Description("Show Condition")
]
public bool ShowCondition
{
get
{
bool selval;
if( ViewState["ShowCondition"] == null)
{
selval = true;
}
else
{
selval = (bool) ViewState["ShowCondition"];
}
return(selval);
}
set
{
this.ViewState["ShowCondition"] = value;
}
}

Friday, October 08, 2004

Adding an Event Handler for a Button in a Web Control

//Declare the Event as an object.
private static readonly object EventSave = new object();

//Create a Property to enable the user assign an Event.

[
Category("Action"),
DefaultValue(""),
Description("Raised when the user clicks the Save button")
]
public event EventHandler Save
{
add
{
Events.AddHandler(EventSave,value);
}
remove
{
Events.RemoveHandler(EventSave,value);
}
}

//get the list of events for the handler, if not null wire it to the handler in the button save click event inside the web control.

EventHandler SaveHandler=(EventHandler)Events[EventSave];
if(SaveHandler!=null)
{
SaveHandler(this,e);
}


***********Another example using Event Bubbling********************


# region EventBubbling
protected virtual void onSave(EventArgs e)
{
EventHandler SaveHandler=(EventHandler)Events[EventSave];
if(SaveHandler!=null)
{
SaveHandler(this,e);
}
}
#region Event bubbling
protected override bool OnBubbleEvent(object source, EventArgs e)
{
bool handled = false;
if (e is CommandEventArgs)
{
CommandEventArgs ce = (CommandEventArgs)e;
if (ce.CommandName == "Save")
{
onSave(EventArgs.Empty);
handled = true;
}
}
return handled;
}
#endregion Event bubbling