if refdata is an object of class ReferralData, and we'd like to list all properties and its value. following code should work.
PropertyDescriptorCollection pc = TypeDescriptor.GetProperties(refdata);
foreach(PropertyDescriptor p in pc)
{
p.Name //get name of this property
p.GetValue(refdata) //get value of this property,
//note we pass the object into getvalue function
}
Friday, December 09, 2005
Wednesday, November 23, 2005
cookie doman
every cookie is saved with domain information, so cookie saved for www1.di.com will not be retrieved from next request of www3.di.com. To solve this issue, you need to specify the domain when save the cookie.
cookie.domain = ".di.com"
in this way, both www1.di.com and www3.di.com will correctly get the cookie value.
cookie.domain = ".di.com"
in this way, both www1.di.com and www3.di.com will correctly get the cookie value.
Friday, September 30, 2005
using C++ dll in C#
this article have thorough explaination of how to import unmanaged dll into .NET code and use it.
http://msdn.microsoft.com/msdnmag/issues/02/08/CQA/
using System.Runtime.InteropServices; // DllImport
public class Win32 {
[DllImport("User32.Dll")]
public static extern void SetWindowText(int h, String s);
}
http://msdn.microsoft.com/msdnmag/issues/02/08/CQA/
using System.Runtime.InteropServices; // DllImport
public class Win32 {
[DllImport("User32.Dll")]
public static extern void SetWindowText(int h, String s);
}
Thursday, September 15, 2005
loop webcontrols in a page, and disable them all
all though we can loop Page.Controls, but not all of them are webcontrols( such as textbox, label, and dropdownlist). For example, the very first control in Page.Controls is the web form itself.
So what we really want to do is: loop every level of controls, see if they are the right type we are looking for, such as textbox, label, and dropdownlist, and disable them one by one.
the function needs be recursive, because there might be a usercontrol or panel in a page that contains web controls.
void DisableControls(ControlCollection controls)
{
foreach(Control c in controls)
{
try
{
TextBox tb= (TextBox)c;
tb.Enabled = false;
}
catch
{}
try
{
ListBox lb= (ListBox)c;
lb.Enabled = false;
}
catch
{}
try
{
RadioButtonList rb= (RadioButtonList)c;
rb.Enabled = false;
}
catch
{}
try
{
DropDownList ddl= (DropDownList)c;
ddl.Enabled = false;
}
catch
{}
try
{
CheckBox chk = (CheckBox)c;
chk.Enabled = false;
}
catch
{}
try
{
DisableControls(c.Controls);
}
catch{}
}
}
So what we really want to do is: loop every level of controls, see if they are the right type we are looking for, such as textbox, label, and dropdownlist, and disable them one by one.
the function needs be recursive, because there might be a usercontrol or panel in a page that contains web controls.
void DisableControls(ControlCollection controls)
{
foreach(Control c in controls)
{
try
{
TextBox tb= (TextBox)c;
tb.Enabled = false;
}
catch
{}
try
{
ListBox lb= (ListBox)c;
lb.Enabled = false;
}
catch
{}
try
{
RadioButtonList rb= (RadioButtonList)c;
rb.Enabled = false;
}
catch
{}
try
{
DropDownList ddl= (DropDownList)c;
ddl.Enabled = false;
}
catch
{}
try
{
CheckBox chk = (CheckBox)c;
chk.Enabled = false;
}
catch
{}
try
{
DisableControls(c.Controls);
}
catch{}
}
}
add a blank entry to the databind dropdownlist
first of all, keep in mind that adding entry before databinding won't work at all. we should always add the blank entry after binding:
dpQuestion.DataSource = GetQuestions();
dpQuestion.DataTextField = "QSTN_DESC";
dpQuestion.DataValueField = "QSTN_ID";
dpQuestion.DataBind();
//add a blank entry at top
dpQuestion.Items.Insert(0,new ListItem("",""));
dpQuestion.DataTextField = "QSTN_DESC";
dpQuestion.DataValueField = "QSTN_ID";
dpQuestion.DataBind();
//add a blank entry at top
dpQuestion.Items.Insert(0,new ListItem("",""));
Monday, September 12, 2005
retain value of password filed when postback
use this code:
If(IsPostBack)
{
this.txtFedTaxID.Attributes["value"] = txtFedTaxID.Text;
this.txtFedTaxID2.Attributes["value"] = txtFedTaxID2.Text;
}
"txtFedTaxID.Text = txtFedTaxID.Text" won't work for the password field.
If(IsPostBack)
{
this.txtFedTaxID.Attributes["value"] = txtFedTaxID.Text;
this.txtFedTaxID2.Attributes["value"] = txtFedTaxID2.Text;
}
"txtFedTaxID.Text = txtFedTaxID.Text" won't work for the password field.
Wednesday, August 31, 2005
Regular Expression lookahead, VS bug?
use (?=) as positive look ahead, and (?!) as negative look ahead,
look ahead will not actually match any character, so the string pointer is still unchanged.
for example, I want to match a password in following criteria
(1). at least 7 to 8 long
(2). contain at least one special character @#$
(3). contain at least one digit
(?=.*\d)(?=.*[@#$]).{7,8}
(?=.*\d) will peek if there is at least one digit
(?=.*[@#$]) will peek if there is at least one special char
.{7,8} will check the length.
but unfortunately, I found that I can't use reg exp validator provided by VS, it won't work. Unless I put number and special char in the begining, for example: 13@pass, instead of pass@12
However, if I use a custom validator and pasted the same R.E. into the code behind of the server validator, it works perfectly. So I can easily draw a conclusion that R.E. in VS works totally differently in client side (RE validator) and server side (RE class).
is this a bug?
look ahead will not actually match any character, so the string pointer is still unchanged.
for example, I want to match a password in following criteria
(1). at least 7 to 8 long
(2). contain at least one special character @#$
(3). contain at least one digit
(?=.*\d)(?=.*[@#$]).{7,8}
(?=.*\d) will peek if there is at least one digit
(?=.*[@#$]) will peek if there is at least one special char
.{7,8} will check the length.
but unfortunately, I found that I can't use reg exp validator provided by VS, it won't work. Unless I put number and special char in the begining, for example: 13@pass, instead of pass@12
However, if I use a custom validator and pasted the same R.E. into the code behind of the server validator, it works perfectly. So I can easily draw a conclusion that R.E. in VS works totally differently in client side (RE validator) and server side (RE class).
is this a bug?
Monday, August 01, 2005
call external exe from asp.net
looks like a simple task, huh?
I have two applications, one is win app and the other is web app. I had no trouble to call a external PVCS command from win app, but I had HUGE trouble to do the same thing in my web app.
Rationale:
(1). PVCS commond need use windows authentication to establish connection to PVCS server
(2). .Net web application use a weak machine name to run Aspnet_wp.exe
(3). when external command is envoked from web app, it will use that weak name
(4). using impersonate won't help, cause impersonate only apply to web app itself, not external apps
Solution:
(1). change processmodel section in the machine.config, using windows' logon domain/username and its password
drawback:
(1) all web application running in this machine will use your window username and password, because you changed the machine.config
possible alternative
(1). using win32 API "CreateProcessWithLogonW"
or
(2). change configuration in PVCS so that it can take the default weak name of aspnet
still puzzled:
(1). where do I see who's in the owner of a process in windows task manager?
reference:
link
I have two applications, one is win app and the other is web app. I had no trouble to call a external PVCS command from win app, but I had HUGE trouble to do the same thing in my web app.
Rationale:
(1). PVCS commond need use windows authentication to establish connection to PVCS server
(2). .Net web application use a weak machine name to run Aspnet_wp.exe
(3). when external command is envoked from web app, it will use that weak name
(4). using impersonate won't help, cause impersonate only apply to web app itself, not external apps
Solution:
(1). change processmodel section in the machine.config, using windows' logon domain/username and its password
drawback:
(1) all web application running in this machine will use your window username and password, because you changed the machine.config
possible alternative
(1). using win32 API "CreateProcessWithLogonW"
or
(2). change configuration in PVCS so that it can take the default weak name of aspnet
still puzzled:
(1). where do I see who's in the owner of a process in windows task manager?
reference:
link
Thursday, July 28, 2005
don't forget ( and ) in sql query if using both AND & OR
//--------------- correct query
strSQL = "select download_agent from afc.agent where download_agent=agent_nbr and Agent_type='D' and download_agent = '"& sessiondata("strAgencyCode") &"' and (COMM_PRODUCTS = 'V' or COMM_PRODUCTS = 'A') with ur"
//incorrect query
strSQL = "select download_agent from afc.agent where download_agent=agent_nbr and Agent_type='D' and download_agent = '"& sessiondata("strAgencyCode") &"' and COMM_PRODUCTS = 'V' or COMM_PRODUCTS = 'A' with ur"
strSQL = "select download_agent from afc.agent where download_agent=agent_nbr and Agent_type='D' and download_agent = '"& sessiondata("strAgencyCode") &"' and (COMM_PRODUCTS = 'V' or COMM_PRODUCTS = 'A') with ur"
//incorrect query
strSQL = "select download_agent from afc.agent where download_agent=agent_nbr and Agent_type='D' and download_agent = '"& sessiondata("strAgencyCode") &"' and COMM_PRODUCTS = 'V' or COMM_PRODUCTS = 'A' with ur"
Wednesday, July 20, 2005
access datasource in Itembound (datagrid/repeater)
in the OnItemDataBound event handler, sometimes you want to access the datasource of a control. whether the datasource is a object, or just a field of a dataset, you can always access it using following code:
DataRowView drv = (DataRowView)e.Item.DataItem;
//then access the specific field
string str = drv["fieldname"].ToString();
DataRowView drv = (DataRowView)e.Item.DataItem;
//then access the specific field
string str = drv["fieldname"].ToString();
time to use Server.UrlEncode()
if passing some special characters in the query string, like # & <>, it will cause broswer to mis-interpretate them, so when constructing query string, you should use Server.UrlEncode()
example:
string qs = "formname="+ Server.UrlEncode(drv[from].tostring());
example:
string qs = "formname="+ Server.UrlEncode(drv[from].tostring());
Monday, April 25, 2005
get server name
When using "C:\WINDOWS\system32\drivers\etc" to edit host file, sometimes developers get confused what physical server they are browsering.
probably you need a server file in your web application, and that file should show which server you are on.
use "System.Environment.MachineName" instead of Request.URL.Server or anything else, because those request variable will not indicate the real server.
code snapit:
System.Environment.MachineName + " - " + Request.ServerVariables["LOCAL_ADDR"]
probably you need a server file in your web application, and that file should show which server you are on.
use "System.Environment.MachineName" instead of Request.URL.Server or anything else, because those request variable will not indicate the real server.
code snapit:
System.Environment.MachineName + " - " + Request.ServerVariables["LOCAL_ADDR"]
Friday, March 25, 2005
item filtering in datagrid
when you want to filter data in a pagging enabled datagrid, you need to make sure everytime you change the Datagrid.CurrentPageIndex after the data has been filtered and before you can Datagrid.DataBind();
/******************
example:
dgDefaultUsers.DataSource = users;
dgDefaultUsers.CurrentPageIndex = 0;
dgDefaultUsers.DataBind();
/************************************************
/******************
example:
dgDefaultUsers.DataSource = users;
dgDefaultUsers.CurrentPageIndex = 0;
dgDefaultUsers.DataBind();
/************************************************
Friday, February 11, 2005
web farm and machine key
when using web farm, because same domain name is associated with several different physical servers, if the web application implements form authentication and encryption, web.config in web application should manually specify machine key, because the automatic generated machine key in different servers are different. If no machine key is specified, the different automatic generated key will cause problem when user first encrypt his password in server 1 and next login at server 2, and it will cause the "Bad Data" exception.
web farm and machine key
when using web farm, because same domain name is associated with several different physical servers, if the web application implements form authentication and encryption, web.config in web application should manually specify machine key, because the automatic generated machine key in different servers are different. If no machine key is specified, the different automatic generated key will cause problem when user first encrypt his password in server 1 and next login at server 2, and it will cause the "Bad Data" exception.
Wednesday, January 26, 2005
complex javascript confirm
normally if you want to warn user before he click some button to delete or update something, you can use
Button.Attributes.Add("onclick","return confirm('Are you sure?')");
However, the javascript confirm function is very simple except you can modify some text of it. In some case, you need to perform some additional checking before you pop up the confirm dialog box. For example, in this web application, it only requires the confirm window pop up when the domain the user entered is equal to the user's domain, so you need some custumorized JS function to perform this checking and confirmation.
addWhite.Attributes.Add("onclick","return SameAddress_Confirm();");
where SameAddress_Confirm() is the JS function I wrote to do this:
function SameAddress_Confirm() {
var mydomain = document.all["hJS"].value;
var addWhiteEntry = document.all["addWhiteEntry"].value;
var addBlackEntry = document.all["addBlackEntry"].value;
addWhiteEntry = TrimString(addWhiteEntry).split('@')[1];
addBlackEntry = TrimString(addBlackEntry).split('@')[1];
var ifAdd;
if((mydomain == addBlackEntry)(mydomain==addWhiteEntry))
{ //show confirm message
ifAdd = !confirm("Adding your own email address or domain to this list can have negative results and actually increase the amount of unwanted messages (spam) your inbox receives significantly.\n\nPlease see the help section topic 'Managing your Allowed Senders lists' for specific details\n\nThis entry can still be added by clicking 'cancel' below.");
}
else
ifAdd = true;
return ifAdd;
}
Button.Attributes.Add("onclick","return confirm('Are you sure?')");
However, the javascript confirm function is very simple except you can modify some text of it. In some case, you need to perform some additional checking before you pop up the confirm dialog box. For example, in this web application, it only requires the confirm window pop up when the domain the user entered is equal to the user's domain, so you need some custumorized JS function to perform this checking and confirmation.
addWhite.Attributes.Add("onclick","return SameAddress_Confirm();");
where SameAddress_Confirm() is the JS function I wrote to do this:
function SameAddress_Confirm() {
var mydomain = document.all["hJS"].value;
var addWhiteEntry = document.all["addWhiteEntry"].value;
var addBlackEntry = document.all["addBlackEntry"].value;
addWhiteEntry = TrimString(addWhiteEntry).split('@')[1];
addBlackEntry = TrimString(addBlackEntry).split('@')[1];
var ifAdd;
if((mydomain == addBlackEntry)(mydomain==addWhiteEntry))
{ //show confirm message
ifAdd = !confirm("Adding your own email address or domain to this list can have negative results and actually increase the amount of unwanted messages (spam) your inbox receives significantly.\n\nPlease see the help section topic 'Managing your Allowed Senders lists' for specific details\n\nThis entry can still be added by clicking 'cancel' below.");
}
else
ifAdd = true;
return ifAdd;
}
Monday, January 24, 2005
Check if Cookies are enabled in one page
Put these javascript code in the header of the login.aspx page to dected if cookies are enalbed
/***************************************************************************************
/***************************************************************************************
Thursday, January 06, 2005
Switching Between HTTP and HTTPS Automatically
a very decent way of implementing http and https switch using web.config
http://www.codeproject.com/aspnet/WebPageSecurity.asp
http://www.codeproject.com/aspnet/WebPageSecurity.asp
Monday, January 03, 2005
form authentication
form authentication, 3 requirements
i. If user click “save password”, the password will always be saved in the cookie unless he click “logout”.
ii. Otherwise, user need to input username and password when login.
iii. If the user just close the browser, he should be log out from the system, and need to use password to login
implementation:
FormsAuthenticationTicket authTicket = new FormsAuthenticationTicket(1,
user.GID.ToString(), DateTime.Now,DateTime.Now.AddMinutes(1),
chkRemember.Checked, roles);
string encryptedTicket = FormsAuthentication.Encrypt(authTicket);
HttpCookie authCookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket);
if(chkRemember.Checked)
authCookie.Expires = DateTime.Now + (new TimeSpan(14,0,0,0));
Response.Cookies.Add(authCookie);
/********************************/
only if chkRemember.Checked, then set the logon cookie 2 weeks of validation.
i. If user click “save password”, the password will always be saved in the cookie unless he click “logout”.
ii. Otherwise, user need to input username and password when login.
iii. If the user just close the browser, he should be log out from the system, and need to use password to login
implementation:
FormsAuthenticationTicket authTicket = new FormsAuthenticationTicket(1,
user.GID.ToString(), DateTime.Now,DateTime.Now.AddMinutes(1),
chkRemember.Checked, roles);
string encryptedTicket = FormsAuthentication.Encrypt(authTicket);
HttpCookie authCookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket);
if(chkRemember.Checked)
authCookie.Expires = DateTime.Now + (new TimeSpan(14,0,0,0));
Response.Cookies.Add(authCookie);
/********************************/
only if chkRemember.Checked, then set the logon cookie 2 weeks of validation.
Subscribe to:
Posts (Atom)