Search the web
Sign In
New User? Sign Up
codesnips · Code Snippets
? Already a member? Sign in to Yahoo!

Yahoo! Groups Tips

Did you know...
Show off your group to the world. Share a photo of your group with us.

Best of Y! Groups

   Check them out and nominate your group.
Having problems with message search? Fill out this form to ensure your group is one of the first to be migrated to the new message search system.

Messages

  Messages Help
Advanced
Messages 19 - 48 of 48   Newest  |  < Newer  |  Older >  |  Oldest
Messages: Show Message Summaries   (Group by Topic) Sort by Date v  
#48 From: "Owais Anwer" <owais@...>
Date: Wed Jul 23, 2003 7:58 am
Subject: Re: Single Instance apps
owais@...
Send Email Send Email
 
The scenario you are talking about is base on different sessions. When a user log into a XP workstation it's session is created ,Means each user has it's own session now question is that how to make our application single instance when run on an user session , this is like that each INstant Integrator App has it's own session. If we take an example of MSN messanger each user session (user log in area) run an identical copy of application i.e each messanger run as a seperate application for each session..........................
 
 

 
Regards
 
Owais Anwer
Creative Chaos (Pvt.) Ltd.
"Managing Your Digital Risk"

www.csquareonline.com
Mobile +92 0333 2223203
Office +92 21 455 2414
Fax
+92 21 454 8226
The information in this Internet email is confidential and may be legally privileged. It is intended solely for the use of the addressee. Access to this Internet email by anyone else is unauthorised. If you are not the intended recipient, any disclosure, copying, distribution or any action taken or omitted to be taken in reliance on it, is prohibited and may be unlawful.
When addressed to our clients any opinions or advice contained in this Internet email will be subject to the terms and conditions expressed in any applicable laws governing Creative Chaos (pvt) Limited's terms of business.

The views expressed in this email are those of the sender only. Creative Chaos (pvt) Limited will be not responsible for, and will not be held liable for, the contents of this email or any attachments thereto.
 
----- Original Message -----
From: Faraz Beg
Sent: Wednesday, July 23, 2003 2:13 AM
Subject: RE: [codesnips] Single Instance apps

What I’m talking abt is the scenario in which multiple users (say a couple of them) log into an XP workstation and all have msn logged in… although there’s only one user active at a particular instance but still, the inactive user is logged into msn as away and receives all events including messages and alerts … I know it’s the same instance of the app but how does msn achieves this, that’s what I wanted to ask…

 

Mirza Faraz Beg

Senior Software Engineer

Creative Chaos (Pvt.) Ltd.
"Managing Your Digital Risk"
www.csquareonline.com

 

 

Office

+92 21 455 2414

Fax

+92 21 454 9867

Cell

+92 300 8295763

 

 

 

 

 

 

The information in this Internet email is confidential and may be legally privileged. It is intended solely for the use of the addressee. Access to this Internet email by anyone else is unauthorised. If you are not the intended recipient, any disclosure, copying, distribution or any action taken or omitted to be taken in reliance on it, is prohibited and may be unlawful.
When addressed to our clients any opinions or advice contained in this Internet email will be subject to the terms and conditions expressed in any applicable laws governing Creative Chaos (pvt) Limited's terms of business.
The views expressed in this email are those of the sender only. Creative Chaos (pvt) Limited will be not responsible for, and will not be held liable for, the contents of this email or any attachments thereto.

-----Original Message-----
From:
Nauman Leghari [mailto:laghari78@...]
Sent
:
Tuesday, July 22, 2003 8:50 PM
To: codesnips@yahoogroups.com
Subject: RE: [codesnips] Single Instance apps

 

I dont think so. You can run MSN messenger with Windows XP Messenger but you can't run two different instances for each application. They both are implemented as different applications. Correct me if I am wrong.

-----Original Message-----
From: Faraz Beg [mailto:baigsaab@...]
Sent:
Tuesday, July 22, 2003 7:16 AM
To: codesnips@yahoogroups.com
Subject: RE: [codesnips] Single Instance apps

Hmmm…

But still windows messenger that comes with XP, allows multiple users to use it at the same time (it may use the same thread I donno abt that…)

It shows different users their respective profiles, isn’t it? Any insight guys?

 

Looking forward …

 

Mirza Faraz Beg

Senior Software Engineer

Creative Chaos (Pvt.) Ltd.
"Managing Your Digital Risk"
www.csquareonline.com

 

 

Office

+92 21 455 2414

Fax

+92 21 454 9867

Cell

+92 300 8295763

 

 

 

 


To unsubscribe from this group, send an email to:
codesnips-unsubscribe@yahoogroups.com



Your use of Yahoo! Groups is subject to the Yahoo! Terms of Service.




To unsubscribe from this group, send an email to:
codesnips-unsubscribe@yahoogroups.com



Your use of Yahoo! Groups is subject to the Yahoo! Terms of Service.

#47 From: "fahad" <desperate_desperado@...>
Date: Wed Jul 23, 2003 6:24 am
Subject: Re: Single Instance apps
desperate_de...
Offline Offline
Send Email Send Email
 
friends,
 
i didnt CHECKED that code on the case(s) you guys specified... and i dont have resources to check this as well... if you have resources, you can check this... i have provided you tha code ... so just paste it compile and run...
 
i am waiting for your response.....
----- Original Message -----
From: Faraz Beg
Sent: Wednesday, July 23, 2003 2:13 AM
Subject: RE: [codesnips] Single Instance apps

What I’m talking abt is the scenario in which multiple users (say a couple of them) log into an XP workstation and all have msn logged in… although there’s only one user active at a particular instance but still, the inactive user is logged into msn as away and receives all events including messages and alerts … I know it’s the same instance of the app but how does msn achieves this, that’s what I wanted to ask…

 

Mirza Faraz Beg

Senior Software Engineer

Creative Chaos (Pvt.) Ltd.
"Managing Your Digital Risk"
www.csquareonline.com

 

 

Office

+92 21 455 2414

Fax

+92 21 454 9867

Cell

+92 300 8295763

 

 

 

 

 

 

The information in this Internet email is confidential and may be legally privileged. It is intended solely for the use of the addressee. Access to this Internet email by anyone else is unauthorised. If you are not the intended recipient, any disclosure, copying, distribution or any action taken or omitted to be taken in reliance on it, is prohibited and may be unlawful.
When addressed to our clients any opinions or advice contained in this Internet email will be subject to the terms and conditions expressed in any applicable laws governing Creative Chaos (pvt) Limited's terms of business.
The views expressed in this email are those of the sender only. Creative Chaos (pvt) Limited will be not responsible for, and will not be held liable for, the contents of this email or any attachments thereto.

-----Original Message-----
From:
Nauman Leghari [mailto:laghari78@...]
Sent
:
Tuesday, July 22, 2003 8:50 PM
To: codesnips@yahoogroups.com
Subject: RE: [codesnips] Single Instance apps

 

I dont think so. You can run MSN messenger with Windows XP Messenger but you can't run two different instances for each application. They both are implemented as different applications. Correct me if I am wrong.

-----Original Message-----
From: Faraz Beg [mailto:baigsaab@...]
Sent:
Tuesday, July 22, 2003 7:16 AM
To: codesnips@yahoogroups.com
Subject: RE: [codesnips] Single Instance apps

Hmmm…

But still windows messenger that comes with XP, allows multiple users to use it at the same time (it may use the same thread I donno abt that…)

It shows different users their respective profiles, isn’t it? Any insight guys?

 

Looking forward …

 

Mirza Faraz Beg

Senior Software Engineer

Creative Chaos (Pvt.) Ltd.
"Managing Your Digital Risk"
www.csquareonline.com

 

 

Office

+92 21 455 2414

Fax

+92 21 454 9867

Cell

+92 300 8295763

 

 

 

 


To unsubscribe from this group, send an email to:
codesnips-unsubscribe@yahoogroups.com



Your use of Yahoo! Groups is subject to the Yahoo! Terms of Service.




To unsubscribe from this group, send an email to:
codesnips-unsubscribe@yahoogroups.com



Your use of Yahoo! Groups is subject to the Yahoo! Terms of Service.

#46 From: "Faraz Beg" <baigsaab@...>
Date: Tue Jul 22, 2003 9:13 pm
Subject: RE: Single Instance apps
baigsaab22
Offline Offline
Send Email Send Email
 

What I’m talking abt is the scenario in which multiple users (say a couple of them) log into an XP workstation and all have msn logged in… although there’s only one user active at a particular instance but still, the inactive user is logged into msn as away and receives all events including messages and alerts … I know it’s the same instance of the app but how does msn achieves this, that’s what I wanted to ask…

 

Mirza Faraz Beg

Senior Software Engineer

Creative Chaos (Pvt.) Ltd.
"Managing Your Digital Risk"
www.csquareonline.com

 

 

Office

+92 21 455 2414

Fax

+92 21 454 9867

Cell

+92 300 8295763

 

 

 

 

 

 

The information in this Internet email is confidential and may be legally privileged. It is intended solely for the use of the addressee. Access to this Internet email by anyone else is unauthorised. If you are not the intended recipient, any disclosure, copying, distribution or any action taken or omitted to be taken in reliance on it, is prohibited and may be unlawful.
When addressed to our clients any opinions or advice contained in this Internet email will be subject to the terms and conditions expressed in any applicable laws governing Creative Chaos (pvt) Limited's terms of business.
The views expressed in this email are those of the sender only. Creative Chaos (pvt) Limited will be not responsible for, and will not be held liable for, the contents of this email or any attachments thereto.

-----Original Message-----
From:
Nauman Leghari [mailto:laghari78@...]
Sent
:
Tuesday, July 22, 2003 8:50 PM
To: codesnips@yahoogroups.com
Subject: RE: [codesnips] Single Instance apps

 

I dont think so. You can run MSN messenger with Windows XP Messenger but you can't run two different instances for each application. They both are implemented as different applications. Correct me if I am wrong.

-----Original Message-----
From: Faraz Beg [mailto:baigsaab@...]
Sent:
Tuesday, July 22, 2003 7:16 AM
To: codesnips@yahoogroups.com
Subject: RE: [codesnips] Single Instance apps

Hmmm…

But still windows messenger that comes with XP, allows multiple users to use it at the same time (it may use the same thread I donno abt that…)

It shows different users their respective profiles, isn’t it? Any insight guys?

 

Looking forward …

 

Mirza Faraz Beg

Senior Software Engineer

Creative Chaos (Pvt.) Ltd.
"Managing Your Digital Risk"
www.csquareonline.com

 

 

Office

+92 21 455 2414

Fax

+92 21 454 9867

Cell

+92 300 8295763

 

 

 

 


To unsubscribe from this group, send an email to:
codesnips-unsubscribe@yahoogroups.com



Your use of Yahoo! Groups is subject to the Yahoo! Terms of Service.



#45 From: "Nauman Leghari" <laghari78@...>
Date: Tue Jul 22, 2003 3:50 pm
Subject: RE: Single Instance apps
laghari78
Offline Offline
Send Email Send Email
 
I dont think so. You can run MSN messenger with Windows XP Messenger but you can't run two different instances for each application. They both are implemented as different applications. Correct me if I am wrong.
-----Original Message-----
From: Faraz Beg [mailto:baigsaab@...]
Sent: Tuesday, July 22, 2003 7:16 AM
To: codesnips@yahoogroups.com
Subject: RE: [codesnips] Single Instance apps

Hmmm…

But still windows messenger that comes with XP, allows multiple users to use it at the same time (it may use the same thread I donno abt that…)

It shows different users their respective profiles, isn’t it? Any insight guys?

 

Looking forward …

 

Mirza Faraz Beg

Senior Software Engineer

Creative Chaos (Pvt.) Ltd.
"Managing Your Digital Risk"
www.csquareonline.com

 

 

Office

+92 21 455 2414

Fax

+92 21 454 9867

Cell

+92 300 8295763

 

 

 

 


#44 From: "Owais Anwer" <owais@...>
Date: Tue Jul 22, 2003 10:28 am
Subject: Re: Single Instance apps
owais@...
Send Email Send Email
 
If we are using this code in our application and multiple users are logged in using remote desktop,Individual user cant be able to run multiple instance of our application
For example if user A and User B is Logged in to single machine
user A and B can both use application but User A and User B cant run multiple copies of the application
regards
 
Owais Anwer
Creative Chaos (Pvt.) Ltd.
"Managing Your Digital Risk"

www.csquareonline.com
Mobile +92 0333 2223203
Office +92 21 455 2414
Fax
+92 21 454 8226
The information in this Internet email is confidential and may be legally privileged. It is intended solely for the use of the addressee. Access to this Internet email by anyone else is unauthorised. If you are not the intended recipient, any disclosure, copying, distribution or any action taken or omitted to be taken in reliance on it, is prohibited and may be unlawful.
When addressed to our clients any opinions or advice contained in this Internet email will be subject to the terms and conditions expressed in any applicable laws governing Creative Chaos (pvt) Limited's terms of business.

The views expressed in this email are those of the sender only. Creative Chaos (pvt) Limited will be not responsible for, and will not be held liable for, the contents of this email or any attachments thereto.
 
----- Original Message -----
Sent: Monday, July 21, 2003 11:26 PM
Subject: RE: [codesnips] Single Instance apps

and I think that asim is talking about sessions, not processes. They both are altogether different things. The operating system also maintain a separate session for each logged-in user. In the case of Operating system sessions, (in my opinion) they are not shared. "Multiuser" capability is added as a facility to the operating system and It is an enhancement over existing OS which are single user.
 
The usability of the code that fahad sent is comparable with the functionality of Microsoft MSN Messenger which restricts itself to just one instance.
 
-----Original Message-----
From: fahad [mailto:desperate_desperado@...]
Sent: Monday, July 21, 2003 2:48 PM
To: codesnips@yahoogroups.com
Subject: Re: [codesnips] Single Instance apps

i think processes are managed by OS on machine leve not the at the user level in case of a remote desktop connection ...it will work if a user, say user A is logged in and invoke the Application at some time "Ta" which is greater than "Tb" (the time when user B invokes the same Application)... then user B will get the instance of the app that was invoked by user A...
 
it would be really a chance of
Ta = Tb...
so it will wUrk.... 99.9%
 
----- Original Message -----
From: Asim
Sent: Monday, July 21, 2003 5:01 PM
Subject: RE: [codesnips] Single Instance apps

assume that 2 users are logged in, on a single machine (through remote desktop connection), and both the users try to run an instance of the app, will this code wurk ??
 
Thanks,
Asim
-----Original Message-----
From: fahad [mailto:desperate_desperado@...]
Sent: Monday, July 21, 2003 3:46 PM
To: codesnips@yahoogroups.com
Subject: [codesnips] Single Instance apps

 
hi,
 
this is my first post to this group.... its about forcing your app to have only one instance running..
 
you need to import 2 dlls to find a window and to set focus to that window

/////////
[DllImport("User32",EntryPoint="FindWindow")]
private static extern IntPtr FindWindow(string lpClassName,string lpWindowName);

[DllImport("User32",EntryPoint="SetForegroundWindow")]
private static extern bool SetForegroundWindow(IntPtr hWnd);


[STAThread]
static void Main()
{
Process ThisProcess = Process.GetCurrentProcess();
Process [] AllProcesses = Process.GetProcessesByName(ThisProcess.ProcessName);                              

if (AllProcesses.Length > 1) // if the process is running
{
bool ret;          
IntPtr hWnd = FindWindow(null, "Form1");   //the caption of your window                 
if(hWnd != IntPtr.Zero)
    {
    ret = SetForegroundWindow(hWnd);  // give focus to this window
                //you can also use BringWindowToTop instead of this
     }                    
}

else
    {//run the new process

    Application.Run(new Form1());          
    }
}


To unsubscribe from this group, send an email to:
codesnips-unsubscribe@yahoogroups.com



Your use of Yahoo! Groups is subject to the Yahoo! Terms of Service.


To unsubscribe from this group, send an email to:
codesnips-unsubscribe@yahoogroups.com



Your use of Yahoo! Groups is subject to the Yahoo! Terms of Service.


To unsubscribe from this group, send an email to:
codesnips-unsubscribe@yahoogroups.com



Your use of Yahoo! Groups is subject to the Yahoo! Terms of Service.


To unsubscribe from this group, send an email to:
codesnips-unsubscribe@yahoogroups.com



Your use of Yahoo! Groups is subject to the Yahoo! Terms of Service.

#43 From: "Faraz Beg" <baigsaab@...>
Date: Tue Jul 22, 2003 6:16 am
Subject: RE: Single Instance apps
baigsaab22
Offline Offline
Send Email Send Email
 

Hmmm…

But still windows messenger that comes with XP, allows multiple users to use it at the same time (it may use the same thread I donno abt that…)

It shows different users their respective profiles, isn’t it? Any insight guys?

 

Looking forward …

 

Mirza Faraz Beg

Senior Software Engineer

Creative Chaos (Pvt.) Ltd.
"Managing Your Digital Risk"
www.csquareonline.com

 

 

Office

+92 21 455 2414

Fax

+92 21 454 9867

Cell

+92 300 8295763

 

 

 

 

 

 

The information in this Internet email is confidential and may be legally privileged. It is intended solely for the use of the addressee. Access to this Internet email by anyone else is unauthorised. If you are not the intended recipient, any disclosure, copying, distribution or any action taken or omitted to be taken in reliance on it, is prohibited and may be unlawful.
When addressed to our clients any opinions or advice contained in this Internet email will be subject to the terms and conditions expressed in any applicable laws governing Creative Chaos (pvt) Limited's terms of business.
The views expressed in this email are those of the sender only. Creative Chaos (pvt) Limited will be not responsible for, and will not be held liable for, the contents of this email or any attachments thereto.

-----Original Message-----
From:
Nauman Leghari [mailto:laghari78@...]
Sent
:
Monday, July 21, 2003 11:27 PM
To:
codesnips@yahoogroups.com
Subject: RE: [codesnips] Single Instance apps

 

and I think that asim is talking about sessions, not processes. They both are altogether different things. The operating system also maintain a separate session for each logged-in user. In the case of Operating system sessions, (in my opinion) they are not shared. "Multiuser" capability is added as a facility to the operating system and It is an enhancement over existing OS which are single user.

 

The usability of the code that fahad sent is comparable with the functionality of Microsoft MSN Messenger which restricts itself to just one instance.

 

-----Original Message-----
From:
fahad [mailto:desperate_desperado@...]
Sent:
Monday, July 21, 2003 2:48 PM
To: codesnips@yahoogroups.com
Subject: Re: [codesnips] Single Instance apps

i think processes are managed by OS on machine leve not the at the user level in case of a remote desktop connection ...it will work if a user, say user A is logged in and invoke the Application at some time "Ta" which is greater than "Tb" (the time when user B invokes the same Application)... then user B will get the instance of the app that was invoked by user A...

 

it would be really a chance of

Ta = Tb...

so it will wUrk.... 99.9%

 

----- Original Message -----

From: Asim

Sent: Monday, July 21, 2003 5:01 PM

Subject: RE: [codesnips] Single Instance apps

 

assume that 2 users are logged in, on a single machine (through remote desktop connection), and both the users try to run an instance of the app, will this code wurk ??

 

Thanks,

Asim

-----Original Message-----
From:
fahad [mailto:desperate_desperado@...]
Sent:
Monday, July 21, 2003 3:46 PM
To: codesnips@yahoogroups.com
Subject: [codesnips] Single Instance apps

 

hi,

 

this is my first post to this group.... its about forcing your app to have only one instance running..

 

you need to import 2 dlls to find a window and to set focus to that window


/////////
[DllImport("User32",EntryPoint="FindWindow")]
private static extern
IntPtr FindWindow(string lpClassName,string lpWindowName);

[DllImport("User32",EntryPoint="SetForegroundWindow")]
private static extern bool SetForegroundWindow(IntPtr hWnd);


[STAThread]
static void Main()
{
Process ThisProcess = Process.GetCurrentProcess();
Process [] AllProcesses = Process.GetProcessesByName(ThisProcess.ProcessName);                              

if (AllProcesses.Length > 1) // if the process is running
{
bool ret;          
IntPtr hWnd = FindWindow(null, "Form1");   //the caption of your window                 

if(hWnd != IntPtr.Zero)
    {
    ret = SetForegroundWindow(hWnd);  // give focus to this window

                //you can also use BringWindowToTop instead of this
     }                    
}

else
    {//run the new process

    Application.Run(new Form1());          
    }
}



To unsubscribe from this group, send an email to:
codesnips-unsubscribe@yahoogroups.com



Your use of Yahoo! Groups is subject to the Yahoo! Terms of Service.



To unsubscribe from this group, send an email to:
codesnips-unsubscribe@yahoogroups.com



Your use of Yahoo! Groups is subject to the Yahoo! Terms of Service.



To unsubscribe from this group, send an email to:
codesnips-unsubscribe@yahoogroups.com



Your use of Yahoo! Groups is subject to the Yahoo! Terms of Service.



To unsubscribe from this group, send an email to:
codesnips-unsubscribe@yahoogroups.com



Your use of Yahoo! Groups is subject to the Yahoo! Terms of Service.



#42 From: "Nauman Leghari" <laghari78@...>
Date: Mon Jul 21, 2003 6:27 pm
Subject: RE: Single Instance apps
laghari78
Offline Offline
Send Email Send Email
 
and I think that asim is talking about sessions, not processes. They both are altogether different things. The operating system also maintain a separate session for each logged-in user. In the case of Operating system sessions, (in my opinion) they are not shared. "Multiuser" capability is added as a facility to the operating system and It is an enhancement over existing OS which are single user.
 
The usability of the code that fahad sent is comparable with the functionality of Microsoft MSN Messenger which restricts itself to just one instance.
 
-----Original Message-----
From: fahad [mailto:desperate_desperado@...]
Sent: Monday, July 21, 2003 2:48 PM
To: codesnips@yahoogroups.com
Subject: Re: [codesnips] Single Instance apps

i think processes are managed by OS on machine leve not the at the user level in case of a remote desktop connection ...it will work if a user, say user A is logged in and invoke the Application at some time "Ta" which is greater than "Tb" (the time when user B invokes the same Application)... then user B will get the instance of the app that was invoked by user A...
 
it would be really a chance of
Ta = Tb...
so it will wUrk.... 99.9%
 
----- Original Message -----
From: Asim
Sent: Monday, July 21, 2003 5:01 PM
Subject: RE: [codesnips] Single Instance apps

assume that 2 users are logged in, on a single machine (through remote desktop connection), and both the users try to run an instance of the app, will this code wurk ??
 
Thanks,
Asim
-----Original Message-----
From: fahad [mailto:desperate_desperado@...]
Sent: Monday, July 21, 2003 3:46 PM
To: codesnips@yahoogroups.com
Subject: [codesnips] Single Instance apps

 
hi,
 
this is my first post to this group.... its about forcing your app to have only one instance running..
 
you need to import 2 dlls to find a window and to set focus to that window

/////////
[DllImport("User32",EntryPoint="FindWindow")]
private static extern IntPtr FindWindow(string lpClassName,string lpWindowName);

[DllImport("User32",EntryPoint="SetForegroundWindow")]
private static extern bool SetForegroundWindow(IntPtr hWnd);


[STAThread]
static void Main()
{
Process ThisProcess = Process.GetCurrentProcess();
Process [] AllProcesses = Process.GetProcessesByName(ThisProcess.ProcessName);                              

if (AllProcesses.Length > 1) // if the process is running
{
bool ret;          
IntPtr hWnd = FindWindow(null, "Form1");   //the caption of your window                 
if(hWnd != IntPtr.Zero)
    {
    ret = SetForegroundWindow(hWnd);  // give focus to this window
                //you can also use BringWindowToTop instead of this
     }                    
}

else
    {//run the new process

    Application.Run(new Form1());          
    }
}


To unsubscribe from this group, send an email to:
codesnips-unsubscribe@yahoogroups.com



Your use of Yahoo! Groups is subject to the Yahoo! Terms of Service.


To unsubscribe from this group, send an email to:
codesnips-unsubscribe@yahoogroups.com



Your use of Yahoo! Groups is subject to the Yahoo! Terms of Service.


To unsubscribe from this group, send an email to:
codesnips-unsubscribe@yahoogroups.com



Your use of Yahoo! Groups is subject to the Yahoo! Terms of Service.

#41 From: "Nauman Leghari" <laghari78@...>
Date: Mon Jul 21, 2003 6:26 pm
Subject: RE: Single Instance apps
laghari78
Offline Offline
Send Email Send Email
 
and I think that asim is talking about sessions, not processes. They both are altogether different things. The operating system also maintain a separate session for each logged-in user. In the case of Operating system sessions, (in my opinion) they are not shared. "Multiuser" capability is added as a facility to the operating system and It is an enhancement over existing OS which are single user.
 
The usability of the code that fahad sent is comparable with the functionality of Microsoft MSN Messenger which restricts itself to just one instance.
 
-----Original Message-----
From: fahad [mailto:desperate_desperado@...]
Sent: Monday, July 21, 2003 2:48 PM
To: codesnips@yahoogroups.com
Subject: Re: [codesnips] Single Instance apps

i think processes are managed by OS on machine leve not the at the user level in case of a remote desktop connection ...it will work if a user, say user A is logged in and invoke the Application at some time "Ta" which is greater than "Tb" (the time when user B invokes the same Application)... then user B will get the instance of the app that was invoked by user A...
 
it would be really a chance of
Ta = Tb...
so it will wUrk.... 99.9%
 
----- Original Message -----
From: Asim
Sent: Monday, July 21, 2003 5:01 PM
Subject: RE: [codesnips] Single Instance apps

assume that 2 users are logged in, on a single machine (through remote desktop connection), and both the users try to run an instance of the app, will this code wurk ??
 
Thanks,
Asim
-----Original Message-----
From: fahad [mailto:desperate_desperado@...]
Sent: Monday, July 21, 2003 3:46 PM
To: codesnips@yahoogroups.com
Subject: [codesnips] Single Instance apps

 
hi,
 
this is my first post to this group.... its about forcing your app to have only one instance running..
 
you need to import 2 dlls to find a window and to set focus to that window

/////////
[DllImport("User32",EntryPoint="FindWindow")]
private static extern IntPtr FindWindow(string lpClassName,string lpWindowName);

[DllImport("User32",EntryPoint="SetForegroundWindow")]
private static extern bool SetForegroundWindow(IntPtr hWnd);


[STAThread]
static void Main()
{
Process ThisProcess = Process.GetCurrentProcess();
Process [] AllProcesses = Process.GetProcessesByName(ThisProcess.ProcessName);                              

if (AllProcesses.Length > 1) // if the process is running
{
bool ret;          
IntPtr hWnd = FindWindow(null, "Form1");   //the caption of your window                 
if(hWnd != IntPtr.Zero)
    {
    ret = SetForegroundWindow(hWnd);  // give focus to this window
                //you can also use BringWindowToTop instead of this
     }                    
}

else
    {//run the new process

    Application.Run(new Form1());          
    }
}


To unsubscribe from this group, send an email to:
codesnips-unsubscribe@yahoogroups.com



Your use of Yahoo! Groups is subject to the Yahoo! Terms of Service.


To unsubscribe from this group, send an email to:
codesnips-unsubscribe@yahoogroups.com



Your use of Yahoo! Groups is subject to the Yahoo! Terms of Service.


To unsubscribe from this group, send an email to:
codesnips-unsubscribe@yahoogroups.com



Your use of Yahoo! Groups is subject to the Yahoo! Terms of Service.

#40 From: "fahad" <desperate_desperado@...>
Date: Mon Jul 21, 2003 1:47 pm
Subject: Re: Single Instance apps
desperate_de...
Offline Offline
Send Email Send Email
 
i think processes are managed by OS on machine leve not the at the user level in case of a remote desktop connection ...it will work if a user, say user A is logged in and invoke the Application at some time "Ta" which is greater than "Tb" (the time when user B invokes the same Application)... then user B will get the instance of the app that was invoked by user A...
 
it would be really a chance of
Ta = Tb...
so it will wUrk.... 99.9%
 
----- Original Message -----
From: Asim
Sent: Monday, July 21, 2003 5:01 PM
Subject: RE: [codesnips] Single Instance apps

assume that 2 users are logged in, on a single machine (through remote desktop connection), and both the users try to run an instance of the app, will this code wurk ??
 
Thanks,
Asim
-----Original Message-----
From: fahad [mailto:desperate_desperado@...]
Sent: Monday, July 21, 2003 3:46 PM
To: codesnips@yahoogroups.com
Subject: [codesnips] Single Instance apps

 
hi,
 
this is my first post to this group.... its about forcing your app to have only one instance running..
 
you need to import 2 dlls to find a window and to set focus to that window

/////////
[DllImport("User32",EntryPoint="FindWindow")]
private static extern IntPtr FindWindow(string lpClassName,string lpWindowName);

[DllImport("User32",EntryPoint="SetForegroundWindow")]
private static extern bool SetForegroundWindow(IntPtr hWnd);


[STAThread]
static void Main()
{
Process ThisProcess = Process.GetCurrentProcess();
Process [] AllProcesses = Process.GetProcessesByName(ThisProcess.ProcessName);                              

if (AllProcesses.Length > 1) // if the process is running
{
bool ret;          
IntPtr hWnd = FindWindow(null, "Form1");   //the caption of your window                 
if(hWnd != IntPtr.Zero)
    {
    ret = SetForegroundWindow(hWnd);  // give focus to this window
                //you can also use BringWindowToTop instead of this
     }                    
}

else
    {//run the new process

    Application.Run(new Form1());          
    }
}


To unsubscribe from this group, send an email to:
codesnips-unsubscribe@yahoogroups.com



Your use of Yahoo! Groups is subject to the Yahoo! Terms of Service.


To unsubscribe from this group, send an email to:
codesnips-unsubscribe@yahoogroups.com



Your use of Yahoo! Groups is subject to the Yahoo! Terms of Service.

#39 From: "Asim" <asimletters@...>
Date: Mon Jul 21, 2003 12:01 pm
Subject: RE: Single Instance apps
asimletters
Offline Offline
Send Email Send Email
 
assume that 2 users are logged in, on a single machine (through remote desktop connection), and both the users try to run an instance of the app, will this code wurk ??
 
Thanks,
Asim
-----Original Message-----
From: fahad [mailto:desperate_desperado@...]
Sent: Monday, July 21, 2003 3:46 PM
To: codesnips@yahoogroups.com
Subject: [codesnips] Single Instance apps

 
hi,
 
this is my first post to this group.... its about forcing your app to have only one instance running..
 
you need to import 2 dlls to find a window and to set focus to that window

/////////
[DllImport("User32",EntryPoint="FindWindow")]
private static extern IntPtr FindWindow(string lpClassName,string lpWindowName);

[DllImport("User32",EntryPoint="SetForegroundWindow")]
private static extern bool SetForegroundWindow(IntPtr hWnd);


[STAThread]
static void Main()
{
Process ThisProcess = Process.GetCurrentProcess();
Process [] AllProcesses = Process.GetProcessesByName(ThisProcess.ProcessName);                              

if (AllProcesses.Length > 1) // if the process is running
{
bool ret;          
IntPtr hWnd = FindWindow(null, "Form1");   //the caption of your window                 
if(hWnd != IntPtr.Zero)
    {
    ret = SetForegroundWindow(hWnd);  // give focus to this window
                //you can also use BringWindowToTop instead of this
     }                    
}

else
    {//run the new process

    Application.Run(new Form1());          
    }
}


To unsubscribe from this group, send an email to:
codesnips-unsubscribe@yahoogroups.com



Your use of Yahoo! Groups is subject to the Yahoo! Terms of Service.

#38 From: "fahad" <desperate_desperado@...>
Date: Mon Jul 21, 2003 10:46 am
Subject: Single Instance apps
desperate_de...
Offline Offline
Send Email Send Email
 
 
hi,
 
this is my first post to this group.... its about forcing your app to have only one instance running..
 
you need to import 2 dlls to find a window and to set focus to that window

/////////
[DllImport("User32",EntryPoint="FindWindow")]
private static extern IntPtr FindWindow(string lpClassName,string lpWindowName);

[DllImport("User32",EntryPoint="SetForegroundWindow")]
private static extern bool SetForegroundWindow(IntPtr hWnd);


[STAThread]
static void Main()
{
Process ThisProcess = Process.GetCurrentProcess();
Process [] AllProcesses = Process.GetProcessesByName(ThisProcess.ProcessName);                              

if (AllProcesses.Length > 1) // if the process is running
{
bool ret;          
IntPtr hWnd = FindWindow(null, "Form1");   //the caption of your window                 
if(hWnd != IntPtr.Zero)
    {
    ret = SetForegroundWindow(hWnd);  // give focus to this window
                //you can also use BringWindowToTop instead of this
     }                    
}

else
    {//run the new process

    Application.Run(new Form1());          
    }
}

#37 From: "Nauman Leghari" <laghari78@...>
Date: Mon May 19, 2003 6:51 am
Subject: [ASP.NET] Custom Error Pages in ASP.NET
laghari78
Offline Offline
Send Email Send Email
 

First, turn on custom error reporting in the web.config and name the file you will use as your default handler:

<!-- Web.Config -->
<configuration>
   <system.web>
     <compilation debug="true"/>
     <customErrors mode="On" defaultRedirect="
MyErrorHandler.aspx"/>
   </system.web>
</configuration>

At its simplest, that's all there is to it. Apologize to the user and provide some links back to what they were doing before the error. But what were they doing? What is the error? You might be disappointed that variations on the following don't work in MyErrorHandler.aspx:

<%@ Page Language="C#" %>
<script runat="server">

private void Page_Load( object src, EventArgs e ) {
   Exception objError = Server.GetLastError();
   lblMessage.Text=objError.Message;
   lblSource.Text=objError.Source;
   Server.ClearError();
}

</script>
<html><head><title>Server Error</title></head>
<body><form runat="server">
   <p><asp:label id="lblMessage" runat="server" /></p>
   <p><asp:label id="lblSource" runat="server" /></p>
</form></body></html>

The error is past tense by the time you hit the handler page. How do you find it? Keep reading.

The simplest thing to do is to catch and store the Exception inside the Application bag right in your global.asax (or a global.asax.cs codebehind):

<%@ Import Namespace="System.IO" %>
<script language="C#" runat="server">
 
protected void Application_Error( object src, EventArgs e ) {
   Exception objError = Server.GetLastError();
   this.Application.Add("lastException",objError);
}
 
</script>

And then retrieve and the display the Exception object's properties (Exception.Message, Exception.Source, Exception.StackTrace, or Exception.TargetSite.Name) inside MyErrorHandler.aspx (as named in your web.config).

private void Page_Load( object src, EventArgs e ) {
   Exception objError = Server.GetLastError();
   lblMessage.Text=objError.Message;
   lblSource.Text=objError.Source;
   Server.ClearError();
}
...

http://www.c-sharpcenter.com/asp.net/customerrors.htm

Advanced User Note: On a busy site, use of the Application object impedes scalability. Application objects are a late-bound kludge to help migrate from Classic ASP to .NET. Ideally you should grab the Exception properties into static fields in some sort of Global class which could then be accessed by the custom error page.

http://www.eggheadcafe.com/articles/20030211.asp

Caveat: Recognize that on a high traffic site which generates nearly simultaneous errors, since this method records the last error in the Application and not the last error in the Session, by the time the Custom Error page is displayed a user could conceivably get someone else's error message. Though not a common problem on most sites, it could potentially confuse whoever is debugging the problem.

A solution to this would be to write the error into a log right when it is raised and debug with the log. The article on error handling above covers writing to the Event Log.

 


#36 From: "Nauman Leghari" <laghari78@...>
Date: Sun May 18, 2003 3:47 pm
Subject: [ASP.NET] Multiple Forms in a ASPX Page
laghari78
Offline Offline
Send Email Send Email
 

http://msdn.microsoft.com/msdnmag/issues/03/05/CuttingEdge/default.aspx


#35 From: "Nauman Leghari" <laghari78@...>
Date: Sun May 18, 2003 3:46 pm
Subject: [C#] Stripping HTML tags from a given string
laghari78
Offline Offline
Send Email Send Email
 

The solution is quite simple:

1. Retrieve all the HTML tags using this pattern: <(.|\n)*?>

2. Replace them with an empty string and return the result

Here's a C# function that does this:

private string StripHTML(string htmlString)

{

//This pattern Matches everything found inside html tags;

//(.|\n) - > Look for any character or a new line

// *?  -> 0 or more occurences, and make a non-greedy search meaning

//That the match will stop at the first available '>' it sees, and not at the last one

//(if it stopped at the last one we could have overlooked

//nested HTML tags inside a bigger HTML tag..)

string pattern = @"<(.|\n)*?>";

 

return  Regex.Replace(htmlString,pattern,string.Empty);

}

Or with just one line of code:

string stripped = Regex.Replace(textBox1.Text,@"<(.|\n)*?>",string.Empty);

 


#34 From: "Nauman Leghari" <laghari78@...>
Date: Sun Apr 20, 2003 3:29 pm
Subject: [C#] Creating a Fully Editable DataGrid
laghari78
Offline Offline
Send Email Send Email
 

The Scenario

In this example I have written a simple WebForm to manage a list of contacts which I have stored in XML.  The requirements  are simply the ability to add new contacts and to be able to modify or delete existing contacts.  The user should be able to modify or delete multiple contacts at one time.  I have also allowed the user to sort their grid by the column of their choosing.

My example is written in C#.  If you prefer the VB version of this code, both version are available in the download.

Contacts.xml

The XML data file for this example is fairly simple and straight forward.  Due to the simplicity, I have not created a schema.

<?xml version="1.0" standalone="yes"?>
<Contacts>
  <Contact>
    <Email>myaddress@...</Email>
    <FirstName>John</FirstName>
    <LastName>Doe</LastName>
  </Contact>
  <Contact>
    <Email>youraddress@...</Email>
    <FirstName>Jane</FirstName>
    <LastName>Doe</LastName>
  </Contact>
</Contacts>

ContactList.aspx

Setting up the WebForm is simple as well.  I placed a new DataGrid onto my form and gave it four columns, one for each field plus one to contain the CheckBox for deleting a contact.  You will notice that the main thing I did here is created each column as a TemplateColumn.  This allowed me to put the TextBox and CheckBox objects into the ItemTemplate.  This is the trick to displaying something other than text in each row of the grid.  In addition you'll notice that I've used the FooterTemplate to make the addition of new contacts easy and (hopefully!) intuitive.

I've also included a single LinkButton which is used to save user modifications and deletions.  It is not, however, used to add new contacts.  That is done by the link button in the FooterTemplate of the last column.

<asp:datagrid id="dgContacts" runat="server" ShowFooter="True" AllowSorting="True" Forefont color="Black" GridLines="None" CellPadding="2" Backfont color="LightGoldenrodYellow" BorderWidth="1px" Borderfont color="Tan" Width="499px" AutoGenerateColumns="False" DataKeyField="Email">
  <SelectedItemStyle Forefont color="GhostWhite" Backfont color="DarkSlateBlue"></SelectedItemStyle>
  <AlternatingItemStyle Backfont color="PaleGoldenrod"></AlternatingItemStyle>
  <HeaderStyle Font-Bold="True" Backfont color="Tan"></HeaderStyle>
  <FooterStyle Backfont color="Tan"></FooterStyle>
  <Columns>
    <asp:TemplateColumn SortExpression="FirstName" HeaderText="First Name">
      <ItemTemplate>
        <asp:TextBox id=First runat="server" Width="109px" Text='<%# DataBinder.Eval(Container, "DataItem.FirstName") %>'>
        </asp:TextBox>
      </ItemTemplate>
      <FooterTemplate>
        <asp:TextBox id="NewFirst" runat="server" Width="109px"></asp:TextBox>
      </FooterTemplate>
    </asp:TemplateColumn>
    <asp:TemplateColumn SortExpression="LastName" HeaderText="Last Name">
      <ItemTemplate>
        <asp:TextBox id=Last runat="server" Width="109px" Text='<%# DataBinder.Eval(Container, "DataItem.LastName") %>'>
        </asp:TextBox>
      </ItemTemplate>
      <FooterTemplate>
        <asp:TextBox id="NewLast" runat="server" Width="109px"></asp:TextBox>
      </FooterTemplate>
    </asp:TemplateColumn>
    <asp:TemplateColumn SortExpression="Email" HeaderText="Email">
      <ItemTemplate>
        <asp:TextBox id=Email runat="server" Text='<%# DataBinder.Eval(Container, "DataItem.Email") %>'>
        </asp:TextBox>
      </ItemTemplate>
      <FooterTemplate>
        <asp:TextBox id="NewEmail" runat="server"></asp:TextBox>
      </FooterTemplate>
    </asp:TemplateColumn>
    <asp:TemplateColumn HeaderText="Delete Contact">
      <ItemStyle HorizontalAlign="Center"></ItemStyle>
      <ItemTemplate>
        <asp:CheckBox Runat="server" ID="chkDelete"></asp:CheckBox>
      </ItemTemplate>
      <FooterStyle HorizontalAlign="Center"></FooterStyle>
      <FooterTemplate>
        <asp:LinkButton Runat="server" Text="Add" CommandName="Add" ID="Linkbutton1" NAME="Linkbutton1"></asp:LinkButton>
      </FooterTemplate>
    </asp:TemplateColumn>
  </Columns>
</asp:datagrid>


ContactList.cs

Since I elected to store my data in an XML file, I have decided to use a DataSet for accessing it.  Since the DataSet object has the ReadXml and WriteXml methods it was a fairly logical choice.  My first step was to read in the XML.  As you can see from the code, I also added a the foundation to handle sorting.

private DataSet _dsContacts;
private string _sSort;

private void Page_Load(object sender, System.EventArgs e)
{
  // Load the XML file.
  _dsContacts = new DataSet();
  _dsContacts.ReadXml(Server.MapPath("Contacts.xml"));
  DataColumn[] dcPk = {_dsContacts.Tables["Contact"].Columns["Email"]};
  _dsContacts.Tables["Contact"].PrimaryKey = dcPk;

  if (!Page.IsPostBack )
  {
    // Only bind at this point if this is the first page request.
    BindContacts();
    _sSort = "FirstName";
  }
  else
  {
    // Read the sort order from the view state.
    _sSort = (string)ViewState["Sort"];
  }
}

Next I created the method used to bind the data to the grid, which includes the logic for sorting the data and a method to persist the XML back to the disk.

private void BindContacts()
{
  // Save the sort order to the view state.
  ViewState["Sort"] = _sSort;

 
// Bind the grid to the sorted data view.
  DataView dv = new DataView(_dsContacts.Tables["Contact"]);
  dv.Sort = _sSort;
  dgContacts.DataSource = dv;
  dgContacts.DataBind();
}

private
void SaveContacts()
{
  _dsContacts.WriteXml(Server.MapPath(
"Contacts.xml"));
}

The ItemCommand event is where new contacts are added to the list.  Note that I checked the CommandName argument for a value of Add.  This is the value that was set back in the ASPX page for the LinkButton in the FooterTemplate of the last column in the grid.

private void dgContacts_ItemCommand(object source , System.Web.UI.WebControls.DataGridCommandEventArgs e)
{
  // Add the new item to the dataset.  I use an array here for efficiency.
  if (e.CommandName == "Add")
  {
   
string[] sContact = {"", "", ""};
    sContact[0] = ((TextBox)e.Item.FindControl(
"NewEmail")).Text;
    sContact[1] = ((TextBox)e.Item.FindControl(
"NewFirst")).Text;
    sContact[2] = ((TextBox)e.Item.FindControl(
"NewLast")).Text;

    _dsContacts.Tables[
"Contact"].Rows.Add(sContact);

    SaveContacts();
  }

  BindContacts();
}

I will skip the SortCommand code since there are a lot of other articles out there that deal with sorting in much more detail.  If you download the code for this example it is included.

Finally I moved on to the OnClick event of the LinkButton on the form.  This is where I looped through the items in the DataGrid to perform any necessary deletes and updates.

private void btnUpdate_Click(object sender, System.EventArgs e)
{
  // Loop through the items in the datagrid.
  foreach (DataGridItem di in dgContacts.Items)
  {
   
// Make sure this is an item and not the header or footer.
    if (di.ItemType == ListItemType.Item || di.ItemType == ListItemType.AlternatingItem)
    {
     
// Get the current row for update or delete operations later.
      DataRow dr = _dsContacts.Tables["Contact"].Rows.Find(dgContacts.DataKeys[di.ItemIndex]);

     
// See if this one needs to be deleted.
      if (((CheckBox)di.FindControl("chkDelete")).Checked)
      {
        _dsContacts.Tables[
"Contact"].Rows.Remove(dr);
      }
     
else
      {
       
// Update the row instead.
        dr["Email"] = ((TextBox)di.FindControl("Email")).Text;
        dr[
"FirstName"] = ((TextBox)di.FindControl("First")).Text;
        dr[
"LastName"] = ((TextBox)di.FindControl("Last")).Text;
      }
    }
  }

  
// Save the changes if there are any.
   if (_dsContacts.HasChanges())
  {
    SaveContacts();
  }

  BindContacts();
}

Conclusion

I could have just as easily referenced the controls by their positions within the the Cells(x) of each DataGridItem.  The point is, there's more than one way to skin a cat and I'm sure that you can find some better ways to accomplish this task.  As you can see it's quite easy to edit entire data grids at one time.  This same approach will also work with paged grids with a little modification.


#33 From: "Nauman Leghari" <laghari78@...>
Date: Sun Apr 20, 2003 3:29 pm
Subject: [C#] Logging Errors Automatically in you ASP.NET Application
laghari78
Offline Offline
Send Email Send Email
 

As developers, we can only fix things if we know they're broken. I've been a part of several companies in which the users will encounter a fatal error on a web page and just close the browser and go home. That doesn't help anybody, especially me (as the developer) because even though the application went through several rounds of testing and bug fixing, two months down the road I could find myself in a meeting with a dozen people who suddenly bring up the fact that only two thirds of the application is useful because there are a bunch of problems that I didn't fix. In this article we'll implement automatic error logging so the development team knows about virtually every fatal error that is encountered in our ASP.NET application.

The web.config file has a section called <customErrors> that we can use to redirect the user to a nice looking page that we have designed to explain to them that there has been a problem. We can even specify different pages for each type of error (such as 404 - File Not Found). For now we'll redirect to a single generic page called DefaultErrorPage.aspx. To do this, we'll alter our web.config file.

<customErrors defaultRedirect="DefaultErrorPage.aspx" mode="on">
</customErrors>

DefaultErrorPage.aspx can show whatever you want to the user, so we won't be creating one in this article. Just make sure you add one to your project.

It is quite simple to cause a fatal error on web page on purpose. For our example let's choose a SqlException (from the System.Data.SqlClient namespace). To cause an exception to be thrown we'll attempt to open a connection to a database, but we'll purposely specify a database that does not exist. Add the following code to the Page_Load routine of your web form.

VB

Dim c As SqlConnection = New SqlConnection("server=MyServer;database=IncorrectDatabase;user id=MyUser;password=MyPassword")
c.Open()

C#

SqlConnection c = new SqlConnection("server=MyServer;database=IncorrectDatabase;user id=MyUser;password=MyPassword");
c.Open();

If you want you can replace the connection string above with one of your own, but the one provided should cause an exception to be thrown anyway.

Let's decide what we believe would be useful information to trap. Obviously we'll need a URL here. More specifically, we'll need a URL with all the QueryString parameters that were passed when the page error occurred. If this is an Intranet and we were using Integrated Windows Authentication we could also grab the AUTH_USER from the ServerVariables. Let's keep it simple and decide that we'll grab the Exception and the accompanying StackTrace. This will tell us exactly what error message would have been displayed to the user had we not implemented our own custom error page. It will also show us the most recent items in the stack trace (if available) so we can see what caused the error that we'll need to fix.

The next thing we'll need to do is edit the code behind global.asax to log our error. In a good software architecture we might pass the error logging functionality off to a class library that our enterprise uses, but for the sake of this article we'll just ignore best practices and show how automatic error logging can be done.

We should find a subroutine called Application_Error in global.asax.vb. This is where our automatic error logging actually takes place. Within this routine we could add code to save the details of the error to a database or pass the details to an object in our class library that might do more with the error, but for now we'll just send an email to Joe Programmer. Joe is in charge of development for the entire site. To send email we'll need to reference the System.Web.Mail namespace in our global.asax.cs or global.asax.vb file.

VB

Sub Application_Error(ByVal sender As Object, ByVal e As EventArgs)
    Dim msg As MailMessage = New MailMessage()
    SmtpMail.SmtpServer = "MyMailServer"
    msg.Body = "Error: " & Server.GetLastError().InnerException.ToString() & vbCrLf & vbCrLf & Request.Url
    msg.To = "joe@..."
    msg.From = "errors@..."
    msg.Subject = "Application Error"
    SmtpMail.Send(msg)
End Sub

C#

protected void Application_Error(Object sender, EventArgs e)
{
    MailMessage msg = new MailMessage();
    SmtpMail.SmtpServer = "MyMailServer";
    msg.Body = "Error: " + Server.GetLastError().InnerException.ToString() + "\n\n" + Request.Url;
    msg.To = "joe@...";
    msg.From = "errors@...";
    msg.Subject = "Application Error";
    SmtpMail.Send(msg);
}

Believe it or not that's all there is to it to implement a system in which every fatal error is brought to the attention of the person (or people) who have the responsibility of reviewing it and fixing it. As I said earlier, you'll most likely want to design a database table that would hold the URL, User, Stack Trace, Exception Text, and any other information that you might find useful. This would lend itself to a bug-tracking system in which each fatal error could be accounted for from the date it was encountered to the date the fix was deployed. We might also alter the email address in the example above to a mobile device email address so the people with the power to fix problems are notified as soon as possible.


#32 From: "Nauman Leghari" <laghari78@...>
Date: Sat Apr 19, 2003 2:41 pm
Subject: [PHP] Connecting to a MySQL database in Dreamweaver
laghari78
Offline Offline
Send Email Send Email
 
http://www.macromedia.com/support/dreamweaver/technotes.html

This TechNote describes a few of the important factors involved in
creating a successful MySQL database connection when using the PHP
server model in Dreamweaver. It will also cover some basic MySQL user
account settings. It's assumed that you have installed and configured
MySQL on a local or remote computer.

Errors will occur within Dreamweaver if each point listed below is not
completed correctly. A common error that can occur when testing a MySQL
connection in Dreamweaver is "An unidentified error has occurred."

  Configure a MySQL user account for the web application itself
  Create a PHP MySQL Site Definition in Dreamweaver
  Setup a MySQL database connection in Dreamweaver

Note: This TechNote is meant to be a basic getting started guide. You
should consult the MySQL documentation and other third-party resources
to tailor the MySQL account settings to your specific security
requirements. To download and install MySQL, visit the MySQL website or
consult some of the third-party MySQL websites listed in Dreamweaver
websites (TechNote 12607).

MySQL configuration
The default installation of the MySQL database system contains two
databases named mysql and test. The mysql database contains six tables
that store information about privileges. We will discuss two of these
tables: the user table and the db table.

The user table stores information about who can connect to the MySQL
server and whether the user has any global level privileges. Because
privileges in the user table affect all databases on the MySQL server,
usually administrators will have some Ys (yes) in the privilege fields
while most standard users have only Ns (no). The db table specifies the
databases on the MySQL server that users are allowed to access, and is
where most of the standard users' privileges are stored.

Note: There are many graphic interface utilities available to help
visually manage MySQL databases, however, this TechNote uses the native
MySQL command line client.

Whether you install MySQL on a UNIX, Windows or Mac OS X machine, the
command prompt window can be used to administer MySQL. In Windows, the
command prompt is opened by selecting Start > Programs > Command Prompt.
(On some systems, the Command Prompt may be located under Accessories in
the Start > Programs menu.)

Change to the mysql\bin directory by entering the following commands at
the command prompt:

   > cd\
> cd mysql\bin

During the MySQL installation, MySQL creates an account called root with
no password, which can be used to log into the database. It is highly
recommended that a password is assigned to this account since root has
full control over the MySQL databases. To assign the root account a
password run the following command, which will set the root password to
new-password. You should replace new-password with a password of your
choice that is harder to guess.

   > mysqladmin -u root password new-password

It is recommended that separate MySQL accounts are created for each PHP
web application. You can create as many MySQL accounts as you wish and
assign different rights and permissions to each account. Web application
users do not need the same level of privileges as the root account.

To create a separate user account for your web application, connect to
MySQL and log in with the superuser account using one of the following
methods. In the example below, the account with superuser privileges is
the root account. MySQL should prompt you to enter a password when you
press the Enter key:

   > mysql --user=root --password
                 or

   > mysql -uroot -p

Once logged into MySQL, you will create a user called dbuser (the name
is arbitrary) for the web application. Below, are four examples of ways
to set up this new user. In all four examples, a new user named dbuser
is created. The four privileges granted to this user are SELECT, INSERT,
UPDATE and DELETE on any table in the employees database(this database
will be referred to as emp in the following examples). The password
myPassword will be encrypted in the MySQL database.  In this example,
dbuser can only access the database from localhost.

GRANT SELECT, INSERT, UPDATE, DELETE ON emp.* TO dbuser@localhost
IDENTIFIED BY "myPassword";


  In this example, dbuser can only access the database from mySite.

GRANT SELECT, INSERT, UPDATE, DELETE ON emp.* TO dbuser@mySite
IDENTIFIED BY "myPassword";


  In this example, dbuser can only access the database from
mySite.myDomain.com.

GRANT SELECT, INSERT, UPDATE, DELETE ON emp.* TO
dbuser@... IDENTIFIED BY "myPassword";


  In this example, dbuser can access the database from any host.

GRANT SELECT, INSERT, UPDATE, DELETE ON emp.* TO dbuser@"%" IDENTIFIED
BY "myPassword";




After running the GRANT statement(s), switch from the emp database back
into the mysql database by running the following command:

>use mysql

Execute the following SQL statement to observe what changes have been
made to the db table in the main mysql database:  SELECT Host, Db, User,
Select_priv, Insert_priv, Update_priv, Delete_priv
FROM db
WHERE User='dbuser';


Here is how the db table will look if all of the GRANT statements listed
above are run: Host Db User Select_priv Insert_priv Update_priv
Delete_priv
localhost emp dbuser Y Y Y Y
mySite emp dbuser Y Y Y Y
mySite.
myDomain.com emp dbuser Y Y Y Y
% emp dbuser Y Y Y Y


Execute the following SQL statement to observe what changes have been
made to the user table in the main mysql database:

  SELECT Host, User, Select_priv, Insert_priv, Update_priv, Delete_priv
FROM user
WHERE User='dbuser';

Here is how the user table will look if all of the GRANT statements
above had been run: Host User Select_priv Insert_priv Update_priv
Delete_priv
localhost dbuser N N N N
mySite dbuser N N N N
mySite.
myDomain.com dbuser N N N N
% dbuser N N N N


Note: For security purposes, the dbuser account in the user table should
not be modified unless the account needs administrative rights similar
to the root or the MySQL administrator account. If these privileges are
granted, the dbuser will have access to the system database.

MySQL automatically reads the user and db tables when it starts, and
when GRANT and REVOKE statements are issued. If you make any manual
changes to the user and db tables, reload the tables to process the
changes using this command:

   > flush privileges;

Setting up the PHP / MySQL Site Definition in Dreamweaver
A successful connection to a MySQL database in Dreamweaver depends on
correct Site Definition entries when defining the site. Below, is a
sample PHP / MySQL Site Definition that uses a Linux PHP server running
on a machine identified as mySite.myDomain.com. MySQL is running on
another machine identified as mysql1.myDomain.com and Dreamweaver is
running on a local workstation. FTP is used to transfer files between
the workstation and the Linux web server.

  Local Info:

   Site Name: mySite
   Local Root Folder: C:\mySite\
  Remote Info:

   Access: FTP
   FTP Host: mySite.myDomain.com
   Host Directory: /htdocs/
   Login: webadmin
   Password: *********
  Testing Server:

   Server Model: PHP / MySQL
   Access: FTP
   FTP Host: mySite.myDomain.com
   Host Directory: /htdocs/
   Login: webadmin
   Password: *********
   URL Prefix: http://mySite.myDomain.com/

Create a MySQL database connection in Dreamweaver
Once the MySQL user account has been set up and the site has been
defined you can connect to your MySQL database in Dreamweaver. Using the
above settings, here are example settings for the MySQL Connection
dialog box in Dreamweaver:

Connection Name: choose a name (e.g. connEmp)
MySQL Server: mysql1.myDomain.com
User Name: dbuser
Password: myPassword
Database: enter the name of your database or click on the Select button
to choose from a list of MySQL databases running on the server.

Note: For the MySQL Server field you must enter localhost if PHP and
MySQL are running on the same machine.

MySQL utilities
There are third-party tools to help configure and manage a MySQL
database without having to know SQL. These tools are helpful to those
who prefer to work with databases through a visual interface rather than
a command line interface. These tools can be downloaded and installed on
the machine running the MySQL database or the local workstation. Some
popular tools include: PHPMyAdmin, MySQL Control Center (MyCC), EMS
MySQL Manager, urSQL, PremiumSoft MySQL Studio, and MySQLGUI.

Additional information
For more details on MySQL, please refer to the MySQL documentation or to
the third-party MySQL sites listed in Dreamweaver websites (TechNote
12607).

For more information on unidentified errors, please refer to
Unidentified error occurs when testing a PHP / MySQL connection
(TechNote 16515).

For general MySQL and PHP troubleshooting tips, please see Testing your
PHP application server (TechNote 16383).

#31 From: "Nauman Leghari" <laghari78@...>
Date: Tue Mar 18, 2003 8:37 am
Subject: [C#] Browsing and Selecting a Folder
laghari78
Offline Offline
Send Email Send Email
 
using System;
using System.Windows.Forms.Design;
 
public class MainClass
{
 public static void Main(string [] arg)
 {
  FolderNameEditor ed = new FolderNameEditor();
  string name = "";
  string folderName = (string)ed.EditValue(null, name);
  
  Console.WriteLine(folderName);
 }
 
}

#30 From: "Nauman Leghari" <laghari78@...>
Date: Sun Mar 9, 2003 9:27 am
Subject: [C#] Using XmlTextWriter to create an Xml file
laghari78
Offline Offline
Send Email Send Email
 
Using XmlTextWriter to write an Xml file
 
 
using System;
using System.Xml;
using System.Text;
 
public class MainClass
{
 public static void Main(string [] arg)
 {
  // To create an Xml file with the following format
  // <?xml version="1.0" encoding="Windows-1252" standalone="yes"?>
  // <directory>
  //   <files dir="c:\" />
  // </directory>
 
  XmlTextWriter xmlText = new XmlTextWriter("filename.xml", Encoding.Default);
 
  xmlText.Formatting = Formatting.Indented;
 
  xmlText.WriteStartDocument(true);
 
  // If you want to attach an Xsl file with the Xml then uncomment the following 2 lines
  // It actually adds the xml-stylesheet attribute
  // string xslText="type='text/xsl' href='../index.xsl'";
        // xmlText.WriteProcessingInstruction("xml-stylesheet", xslText);
 
  xmlText.WriteStartElement("directory"); // <directory>
 
  xmlText.WriteStartElement("files"); // <files>
 
  xmlText.WriteAttributeString("dir", "c:\\");
  
  xmlText.WriteEndElement(); // </files>
 
  xmlText.WriteEndElement(); // </directory>
 
  xmlText.WriteEndDocument();
 
  xmlText.Close();
 }
}

#29 From: "Nauman Leghari" <laghari78@...>
Date: Sat Mar 1, 2003 4:01 pm
Subject: [C#] PageCapturer Utility
laghari78
Offline Offline
Send Email Send Email
 
Intro:
The PageCapturer utility is used to download Web pages programmatically and save them onto hard disk.
 
File: PageCapturer.zip attached with this email.
 
Purpose:
I made this to help me organize the pages visited everyday into a separate directory. And through this way I can save each page automatically with out having to Save each file manually.
 
Feature Missing:
This utility only downloads the Text of the Web page, the images or other media linked is not downloaded.
 
ScreenShot:
 
 
Working:
You can either enter the link into the Link field and then press "Get Page" button or simply copy the url. The program checkes every 2 seconds for any url on the clip board. Currenly, only http:// and ftp:// files are supported.
 
When the page is downloaded completely, the link for the page is automatically added to the "List of Pages fetched today". The list is also saved as an xml file "index.xml" into each directory which is also loaded at the startup. The "View Index" button displays the "index.xml" file after transforming it with the xsl file "index.xsl". Whereas, the "View Page" button displays the selected page in the list. You can also view the page by double clicking the page on the list.
The code is simple and does not block from throwing any exception, therefore you might see some exceptions.
 
How-To Run:
Either load the solution into VS.NET and execute; or run the PageCapturer.exe in the bin\debug\ directory.
 
/regards,
Nauman Leghari
 
For any questions on this, email on laghari78@... :).

#28 From: "Nauman Leghari" <laghari78@...>
Date: Fri Feb 28, 2003 5:22 pm
Subject: [C#] Retrieve WebPage programmatically and Save in File
laghari78
Offline Offline
Send Email Send Email
 

// imports

using System;

using System.Net;

using System.IO;

using System.Text;

// capture webpage by using HttpWebRequest class and Save into file. File is saved in a separate directory for each day. Please check out the method to create directory daywise.

// create an object of HttpWebRequest

string link = www.microsoft.com;

Uri pageUri = new Uri(link);

HttpWebRequest pageRequest = (HttpWebRequest)WebRequest.Create(pageUri);

try

{

WebResponse pageRes = pageRequest.GetResponse();

StreamReader sr = new StreamReader(pageRes.GetResponseStream());

String pageText = sr.ReadToEnd();

SaveToFile( pageText );

}

catch(WebException we)

{

}

 

-----------------------------------------------------------------------------------------------------------

// SaveToFile function

-----------------------------------------------------------------------------------------------------------   

private void SaveToFile( string pageText )

{

// check whether the directory is present

string currDir = Directory.GetCurrentDirectory();

// getting current date

DateTime dt = DateTime.Now;

string todayDir = currDir + @"\" + dt.ToString("ddMMyyyy");

string indexPath = todayDir + @"\index.xml";

// check whether its there

if (!Directory.Exists(todayDir))

{

// create directory

Directory.CreateDirectory(todayDir);

// Write pageText to file

string pathName = todayDir + @"\WebPage.html";

StreamWriter writeFile = File.CreateText(pathName);

writeFile.Write(pageText);

writeFile.Close();

}

catch(Exception e)

{

}

 

} // End of SaveToFile function

 
// WARNING: Compiled by Outlook

#27 From: "Nauman Leghari" <laghari78@...>
Date: Fri Feb 28, 2003 5:11 pm
Subject: [C#] Retrieving Text on Clipboard
laghari78
Offline Offline
Send Email Send Email
 

// import

import System.Windows.Forms;

// get clipboard data and if any then show in MessageBox

// Retrieves the data from the clipboard.

IDataObject iData = Clipboard.GetDataObject();

// Determines whether the data is in text format.

if(iData.GetDataPresent(DataFormats.Text))

{   

        // do anything

        MessageBox.Show((String)iData.GetData(DataFormats.Text));

}

// See the DataFormats class for other types


#26 From: "Nauman Leghari" <laghari78@...>
Date: Fri Feb 28, 2003 5:08 pm
Subject: [C#] Opening a file with a Specific Application
laghari78
Offline Offline
Send Email Send Email
 

// Open an xml file into Internet Explorer

Process p = System.Diagnostics.Process.Start( "iexplore.exe" , "index.xml" );


#25 From: "Nauman Leghari" <laghari78@...>
Date: Tue Feb 4, 2003 8:51 pm
Subject: [C#] String Formatting
laghari78
Offline Offline
Send Email Send Email
 
How to do String formatting
...........................



private void Submit_Click(object sender, EventArgs e) {

try
{

string valueToConvert = Value.Text;

switch (FormatType.SelectedItem.Value)
{

// Number formats
case "Currency":
FormattedValue.Text = decimal.Parse(valueToConvert).ToString( "C5" );
//you can add a number to the end to specify precision
FormatExpression.Text = "decimal.Parse(valueToConvert).ToString( \"C5\"
)";
break;
case "Decimal":
FormattedValue.Text = decimal.Parse(valueToConvert).ToString( "D5" );
//you can add a number to the end to specify precision
FormatExpression.Text = "decimal.Parse(valueToConvert).ToString( \"D5\"
)";
break;
case "Scientific":
FormattedValue.Text = decimal.Parse(valueToConvert).ToString( "E" );
FormatExpression.Text = "decimal.Parse(valueToConvert).ToString( \"E\"
)";
break;
case "Fixed-point":
FormattedValue.Text = decimal.Parse(valueToConvert).ToString( "F5" );
//you can add a number to the end to specify precision
FormatExpression.Text = "decimal.Parse(valueToConvert).ToString( \"F5\"
)";
break;
case "General":
FormattedValue.Text = decimal.Parse(valueToConvert).ToString( "G" );
FormatExpression.Text = "decimal.Parse(valueToConvert).ToString( \"G\"
)";
break;
case "Number":
FormattedValue.Text = decimal.Parse(valueToConvert).ToString( "N" );
FormatExpression.Text = "decimal.Parse(valueToConvert).ToString( \"N\"
)";
break;
case "Percent":
FormattedValue.Text = decimal.Parse(valueToConvert).ToString( "P" );
FormatExpression.Text = "decimal.Parse(valueToConvert).ToString( \"P\"
)";
break;
case "Round-trip":
FormattedValue.Text = decimal.Parse(valueToConvert).ToString( "R" );
FormatExpression.Text = "decimal.Parse(valueToConvert).ToString( \"R\"
)";
break;
case "Hexadecimal":
FormattedValue.Text = decimal.Parse(valueToConvert).ToString( "X" );
FormatExpression.Text = "decimal.Parse(valueToConvert).ToString( \"X\"
)";
break;

// Date Formats
case "Short Date Pattern":
FormattedValue.Text = DateTime.Parse(valueToConvert).ToString( "d" );
FormatExpression.Text = "DateTime.Parse(valueToConvert).ToString( \"d\"
)";
break;
case "Long Date Pattern":
FormattedValue.Text = DateTime.Parse(valueToConvert).ToString( "D" );
FormatExpression.Text = "DateTime.Parse(valueToConvert).ToString( \"D\"
)";
break;
case "Short Time Pattern":
FormattedValue.Text = DateTime.Parse(valueToConvert).ToString( "t" );
FormatExpression.Text = "DateTime.Parse(valueToConvert).ToString( \"t\"
)";
break;
case "Long Time Pattern":
FormattedValue.Text = DateTime.Parse(valueToConvert).ToString( "T" );
FormatExpression.Text = "DateTime.Parse(valueToConvert).ToString( \"T\"
)";
break;
case "Full Date/Time Pattern (short time)":
FormattedValue.Text = DateTime.Parse(valueToConvert).ToString( "f" );
FormatExpression.Text = "DateTime.Parse(valueToConvert).ToString( \"f\"
)";
break;
case "Full Date/Time Pattern (long time)":
FormattedValue.Text = DateTime.Parse(valueToConvert).ToString( "F" );
FormatExpression.Text = "DateTime.Parse(valueToConvert).ToString( \"F\"
)";
break;
case "General Date/Time Pattern (short time)":
FormattedValue.Text = DateTime.Parse(valueToConvert).ToString( "g" );
FormatExpression.Text = "DateTime.Parse(valueToConvert).ToString( \"g\"
)";
break;
case "General Date/Time Pattern (long time)":
FormattedValue.Text = DateTime.Parse(valueToConvert).ToString( "G" );
FormatExpression.Text = "DateTime.Parse(valueToConvert).ToString( \"G\"
)";
break;
case "Month Day Pattern":
FormattedValue.Text = DateTime.Parse(valueToConvert).ToString( "M" );
FormatExpression.Text = "DateTime.Parse(valueToConvert).ToString( \"M\"
)";
break;
case "RFC1123 Pattern":
FormattedValue.Text = DateTime.Parse(valueToConvert).ToString( "R" );
FormatExpression.Text = "DateTime.Parse(valueToConvert).ToString( \"R\"
)";
break;
case "Sortable Date/Time Pattern; conforms to ISO 8601":
FormattedValue.Text = DateTime.Parse(valueToConvert).ToString( "s" );
FormatExpression.Text = "DateTime.Parse(valueToConvert).ToString( \"s\"
)";
break;
case "Universal Sortable Date/Time Pattern":
FormattedValue.Text = DateTime.Parse(valueToConvert).ToString( "u" );
FormatExpression.Text = "DateTime.Parse(valueToConvert).ToString( \"u\"
)";
break;
case "Universal Full Sortable Date/Time Pattern":
FormattedValue.Text = DateTime.Parse(valueToConvert).ToString( "U" );
FormatExpression.Text = "DateTime.Parse(valueToConvert).ToString( \"U\"
)";
break;
case "Year Month Pattern":
FormattedValue.Text = DateTime.Parse(valueToConvert).ToString( "Y" );
FormatExpression.Text = "DateTime.Parse(valueToConvert).ToString( \"Y\"
)";
break;
case "Custom Date Time":
FormattedValue.Text = DateTime.Now.ToString( "yyyy/mm/dd" );
FormatExpression.Text = "DateTime.Now.ToString( \"yyyy/mm/dd\" )";
break;

default:
FormattedValue.Text = Value.Text;
break;



}

}
catch (Exception Ex) {

FormattedValue.Text = ""+Ex.Message+"";
FormatExpression.Text = String.Empty;

}

}

#24 From: "Nauman Laghari" <laghari78@...>
Date: Tue Dec 3, 2002 5:54 pm
Subject: Using MSN Alerts
laghari78
Offline Offline
Send Email Send Email
 

What are MSN Alerts?

 

MSN Alerts Service is a part of Microsoft .NET My Services Initiative. It enables the service provider to reach its users through Instant Messages. Note that it will work on any type of devices, either mobile or desktops.

 

List some example applications?

 

1)      Event Management Application: Notifies the user instantly of the event it registers.

2)      Order Tracking Application: User is instantly notified if any change occurred in the order status.

Etc. etc.

 

So, where can you find the SDK? Licensing?

 

The MSN Alert SDK is downloaded for free from the following URL.

 

http://download.microsoft.com/download/.netalerts/install/5.01/nt5xp/en-us/installalertssdkserver.exe

 

It also contains necessary licensing agreement information as MSN Alerts service in the production setup is not free of cost.

 

Building our Hello World MSN Alert Application:

 

The following listing demonstrates a sample Console Application for MSN Alerts. For all the classes, properties and methods involved in the sample, consult the SDK documentation. Note that you need to Add Reference to the Microsoft Notification SDK Type Library (msnotify.dll). This COM Component is automatically registered when you install the Developer’s SDK.

 

<code>

 

using System;

using System.Reflection;

using System.Runtime.InteropServices;

 

// the following namespace is automatically added when you add a

// reference to the Microsoft Notifications SDK Type Library. Because the

// MSN Alerts subsystem is built using COM therefore we need the

// System.Runtime.InteropServices to access the COM objects through

// Managed Code

 

using MSNOTIFYLib;

 

namespace AlertSample

{

      class MainClass

      {

            static void SetNotificationValues(MsnNotificationClass Alert)

            {

 

                  // set notification values

                  Alert.ID = "1234";

                  Alert.MessageID = "0";

 

                  // this is also fixed with the demo

                  Alert.SiteID = "140001000";

 

                  // directory where the dev edition of the toolkit is installed

                  Alert.SiteURL = "http://localhost/MsAlertsSdkServer";

                 

                  // activates when the user clicks on the Alert window

                  Alert.ActionURL = "/action.asp";

 

                  // activates when the user clicks on the 'change' text on the Alert window

                  Alert.SubscribeURL = "/subscr.asp";

 

                  Alert.BodyLanguage = "1033";

 

                  // icon shown on the top left corner

                  Alert.BodyIcon = "/car.png";

 

                  // body of the alert message

                  Alert.Body = "<TEXT>Hello World</TEXT>";

 

 

            }

 

            static void Main(string[] args)

            {

                  //

                  // TODO: Add code to start application here

                  //

 

                  // creating the required objects

                  MsnNotificationClass Alert = new MsnNotificationClass();

                  NotificationTransportClass Transport = new NotificationTransportClass();

                  NotificationsUtilityClass Util = new NotificationsUtilityClass();

 

                  // setting the destination url

                  Transport.DestinationUrl = "http://localhost/MSAlertsSDKServer/MSAlertsSDKServer.dll";

 

                  // setting username and password

                  // these values are embedded with the sample toolkit

                  // therefore these are only for demo purposes

                  string userName = "Adventure Works";

                  string password = "password";

 

           

                  SetNotificationValues(Alert);

 

                  Console.WriteLine("Alerts Submission System Started");

           

// passport id, acquire using Passport Sign-in, dummy // in this case to pop-up messages locally.

 

                  Alert.ToPID = "0x01234567:0x89abcdef";

 

                  Console.WriteLine("XML:");

                  Console.WriteLine(Alert.GetSerialization());

 

                  Transport.SendNotification(1,userName,password,Alert,1);

 

                  Transport.DrainNotifications(0);

 

            }

      }

}

 

</code>

 

After running the sample application, we see the following pop-up appearing from the bottom-right corner of your desktop.

 

 

Conclusion:

 

MSN Alerts Service is an exciting way to develop client centric applications. Your imagination is the only limit here.


#23 From: "Nauman Laghari" <laghari78@...>
Date: Tue Dec 3, 2002 2:04 am
Subject: [LINK] ASP.NET Roadmap
laghari78
Offline Offline
Send Email Send Email
 
#22 From: "Asim" <asimletters@...>
Date: Tue Dec 3, 2002 1:27 am
Subject: 'other' numeric format specifiers
asimletters
Offline Offline
Send Email Send Email
 
Here is an example of advanced Numeric Format Specifier , according to exact position of numerals
 
' Change the number to Telephone number format
 
'///////////////
Dim Mynumber As Double = 1234567890

Dim MyString As String = Mynumber.ToString("(###) ### - ####")
 
'///////////////
and the output is (123) 456 – 7890
 
------------------------------------------------
Further Details of advanced Numeric Format Specifiers are following:
Format character Name Description
0 Zero placeholder If the value being formatted has a digit in the position where the '0' appears in the format string, then that digit is copied to the output string. The position of the leftmost '0' before the decimal point and the rightmost '0' after the decimal point determines the range of digits that are always present in the output string.
# Digit placeholder If the value being formatted has a digit in the position where the '#' appears in the format string, then that digit is copied to the output string. Otherwise, nothing is stored in that position in the output string. Note that this specifier never displays the '0' character if it is not a significant digit, even if '0' is the only digit in the string. It will display the '0' character if it is a significant digit in the number being displayed.
. Decimal point The first '.' character in the format string determines the location of the decimal separator in the formatted value; any additional '.' characters are ignored. The actual character used as the decimal separator is determined by the NumberDecimalSeparator property of the NumberFormatInfo object that controls formatting.
, Thousand separator and number scaling The ',' character serves two purposes. First, if the format string contains a ',' character between two digit placeholders (0 or #) and to the left of the decimal point if one is present, then the output will have thousand separators inserted between each group of three digits to the left of the decimal separator. The actual character used as the decimal separator in the output string is determined by the NumberGroupSeparator property of the current NumberFormatInfo object that controls formatting.

Second, if the format string contains one or more ',' characters immediately to the left of the decimal point, then the number will be divided by the number of ',' characters multiplied by 1000 before it is formatted. For example, the format string '0,,' will represent 100 million as simply 100. Use of the ',' character to indicate scaling does not include thousand separators in the formatted number. Thus, to scale a number by 1 million and insert thousand separators you would use the format string '#,##0,,'.

% Percentage placeholder The presence of a '%' character in a format string causes a number to be multiplied by 100 before it is formatted. The appropriate symbol is inserted in the number itself at the location where the '%' appears in the format string. The percent character used is dependent on the current NumberFormatInfo class.
E0

E+0

E-0

e0

e+0

e-0

Scientific notation If any of the strings 'E', 'E+', 'E-', 'e', 'e+', or 'e-' are present in the format string and are followed immediately by at least one '0' character, then the number is formatted using scientific notation with an 'E' or 'e' inserted between the number and the exponent. The number of '0' characters following the scientific notation indicator determines the minimum number of digits to output for the exponent. The 'E+' and 'e+' formats indicate that a sign character (plus or minus) should always precede the exponent. The 'E', 'E-', 'e', or 'e-' formats indicate that a sign character should only precede negative exponents.
\ Escape character In C# and the Managed Extensions for C++, the backslash character causes the next character in the format string to be interpreted as an escape sequence. It is used with traditional formatting sequences like "\n" (new line).

In some languages, the escape character itself must be preceded by an escape character when used as a literal. Otherwise, the compiler interprets the character as an escape sequence. Use the string "\\" to display "\".

Note that this escape character is not supported in Visual Basic; however, ControlChars provides the same functionality.

'ABC'

"ABC"

Literal string Characters enclosed in single or double quotes are copied to the output string literally, and do not affect formatting.
; Section separator The ';' character is used to separate sections for positive, negative, and zero numbers in the format string.
Other All other characters All other characters are copied to the output string as literals in the position they appear.
 
----------------------------------------------------------------------------------------------------------------------------------------------------
EXAMPLES :
 
Format Data type Value Output
##### Double 123 123
00000 Double 123 00123
(###) ### - #### Double 1234567890 (123) 456 – 7890
#.## Double 1.2 1.2
0.00 Double 1.2 1.20
00.00 Double 1.2 01.20
#,# Double 1234567890 1,234,567,890
#,, Double 1234567890 1235
#,,, Double 1234567890 1
#,##0,, Double 1234567890 1,235
#0.##% Double 0.086 8.6%
0.###E+0 Double 86000 8.6E+4
0.###E+000 Double 86000 8.6E+004
0.###E-000 Double 86000 8.6E004
[##-##-##] Double 123456 [12-34-56]
##;(##) Double 1234 1234
##;(##) Double -1234 (1234)


#21 From: "Asim" <asimletters@...>
Date: Tue Dec 3, 2002 1:17 am
Subject: 'common' Numeric Format
asimletters
Offline Offline
Send Email Send Email
 
Example of the most Common Decimal Numeric Format.
 
'Insert Commas after each thousand , with specified number of decimal precision.
 
'////////////////

Dim var As Decimal = 12454545.340456

txt_messages.Text = var.ToString("N8")  ' Where8 is the number of digits we want to display after decimal.

'////////////////

the Output is

12,454,545.34045600

In Output its clearly seen that our format specifier has inserted 2 0s to make the number of digits 8 after decimal AND also has inserted commas after Each Thousand.

----------------------------------------------------------------------------------

Further Format Specifier Details are following :

Format specifer Name Description
C or c Currency The number is converted to a string that represents a currency amount. The conversion is controlled by the currency format information of the NumberFormatInfo object used to format the number. The precision specifier indicates the desired number of decimal places. If the precision specifier is omitted, the default currency precision given by the NumberFormatInfo is used.
D or d Decimal This format is supported for integral types only. The number is converted to a string of decimal digits (0-9), prefixed by a minus sign if the number is negative. The precision specifier indicates the minimum number of digits desired in the resulting string. If required, the number is padded with zeros to its left to produce the number of digits given by the precision specifier.
E or e Scientific (exponential) The number is converted to a string of the form "-d.ddd…E+ddd" or "-d.ddd…e+ddd", where each 'd' indicates a digit (0-9). The string starts with a minus sign if the number is negative. One digit always precedes the decimal point. The precision specifier indicates the desired number of digits after the decimal point. If the precision specifier is omitted, a default of six digits after the decimal point is used. The case of the format specifier indicates whether to prefix the exponent with an 'E' or an 'e'. The exponent always consists of a plus or minus sign and a minimum of three digits. The exponent is padded with zeros to meet this minimum, if required.
F or f Fixed-point The number is converted to a string of the form "-ddd.ddd…" where each 'd' indicates a digit (0-9). The string starts with a minus sign if the number is negative. The precision specifier indicates the desired number of decimal places. If the precision specifier is omitted, the default numeric precision given by the NumberFormatInfo is used.
G or g General The number is converted to the most compact decimal form, using fixed or scientific notation. The precision specifier determines the number of significant digits in the resulting string. If the precision specifier is omitted, the number of significant digits is determined by the type of number being converted:
  • Int16 or UInt16: 5 digits
  • Int32 or UInt32: 10 digits
  • Int64 or UInt64: 19 digits
  • Single: 7 digits
  • Double: 15 digits
  • Decimal: 29 digits

Trailing zeros after the decimal point are removed, and the resulting string contains a decimal point only if required.

The resulting string uses fixed-point format if the exponent of the number (as produced by the 'E' format) is less than the number of significant digits, and greater than or equal to –4. Otherwise, the resulting string uses scientific format, and the case of the format specifier controls whether the format is prefixed with an 'E' or an 'e'.

N or n Number The number is converted to a string of the form "-d,ddd,ddd.ddd…", where each 'd' indicates a digit (0-9). The string starts with a minus sign if the number is negative. Thousand separators are inserted between each group of three digits to the left of the decimal point. The precision specifier indicates the desired number of decimal places. If the precision specifier is omitted, the default numeric precision given by the NumberFormatInfo is used.
P or p Percent The number is converted to a string that represents a percent as defined by the NumberFormatInfo.PercentNegativePattern property or the NumberFormatInfo.PercentPositivePattern property. If the number is negative, the string produced is defined by the PercentNegativePattern and starts with a minus sign. The converted number is multiplied by 100 in order to be presented as a percentage. The precision specifier indicates the desired number of decimal places. If the precision specifier is omitted, the default numeric precision given by NumberFormatInfo is used.
R or r Round-trip The round-trip specifier guarantees that a numeric value converted to a string will be parsed back into the same numeric value. When a numeric value is formatted using this specifier, it is first tested using the general format, with 15 spaces of precision for a Double and 7 spaces of precision for a Single. If the value is successfully parsed back to the same numeric value, then it is formatted using the general format specifer. However, if the value is not successfully parsed back to the same numeric value, then the value is formatted using 17 digits of precision for a Double and 9 digits of precision for a Single. Although a precision specifier can be appended to the round-trip format specifier, it is ignored. Round trips are given precedence over precision when using this specifier. This format is supported by floating-point types only.
X or x Hexadecimal The number is converted to a string of hexadecimal digits. The case of the format specifier indicates whether to use uppercase or lowercase characters for the hexadecimal digits greater than 9. For example, use 'X' to produce 'ABCDEF', and 'x' to produce 'abcdef'. The precision specifier indicates the minimum number of digits desired in the resulting string. If required, the number is padded with zeros to its left to produce the number of digits given by the precision specifier. This format is supported for integral types only.


#20 From: "Asim" <asimletters@...>
Date: Mon Dec 2, 2002 9:27 pm
Subject: Custom date time formats
asimletters
Offline Offline
Send Email Send Email
 
You Can easily Customize the display for your date time.
 
'/////////////////////////////////

Dim mydate As DateTime = DateTime.Now
Dim show_date As string

show_date= mydate.ToString("MMM dd,yyyy hh:mm:ss")

'/////////////////////////////////

Simply Pass the format as a parameter of overloaded method ToString.

Help For Format Specifier is following

 

Format specifiers Current culture Time zone Output
d, M en-US GMT 12, 4
d MMMM en-US GMT 12 April
12
dddd MMMM yy gg en-US GMT Thursday April 01 A.D.
h , m: s en-US GMT 6 , 13: 12
hh,mm:ss en-US GMT 06,13:12
HH-mm-ss-tt en-US GMT 06-13-12-AM
hh:mm, G\MT z      en-US GMT 05:13 GMT +0
hh:mm, G\MT z      en-US GMT +10:00 05:13 GMT +10
hh:mm, G\MT zzz en-US GMT 05:13 GMT +00:00
hh:mm, G\MT zzz en-US GMT –9:00 05:13 GMT -09:00

#19 From: "Asim" <asimletters@...>
Date: Mon Dec 2, 2002 8:38 pm
Subject: Create a File (Sequential)
asimletters
Offline Offline
Send Email Send Email
 
It is assumed that you have already placed these 2 controls on your winform:
1: TextBox (txt_data)
2: Button (btn_save)
 
Now create an on_click method for btn_save
 
'//////////////////////////////////////////////////////////////

Private Sub btn_save_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btn_save.Click

'Create a text file, and save contents of the textbox (txt_data.text) into the file

Dim output As FileStream

Dim filechooser As New SaveFileDialog()

Dim result As DialogResult = filechooser.ShowDialog

Dim filename As String

filechooser.CheckFileExists = False

If result = DialogResult.Cancel Then

Exit Sub

End If

filename = filechooser.FileName

output = New FileStream(filename, FileMode.Create, FileAccess.Write)

Dim data As [Byte]() = Encoding.ASCII.GetBytes(txt_data.Text)

output.Write(data, 0, data.Length)

output.Flush()

output = Nothing

End Sub

'//////////////////////////////////////////////////////////////


Messages 19 - 48 of 48   Newest  |  < Newer  |  Older >  |  Oldest
Advanced
Add to My Yahoo!      XML What's This?

Copyright © 2009 Yahoo! Inc. All rights reserved.
Privacy Policy - Terms of Service - Guidelines - Help