In .NET 2.0, Microsoft introduced the Web Site. This was the default way to create a web Project in Visual Studio 2005. In Visual Studio 2008, the Web Application has been restored as the default web Project in Visual Studio/.NET 3.x
The Web Site is a file/folder based Project structure. It is designed such that pages are not compiled until they are requested ("on demand"). The advantages to the Web Site are:
1) It is designed to accommodate non-.NET Applications
2) Deployment is as simple as copying files to the target server
3) Any portion of the Web Site can be updated without requiring recompilation of the entire Site.
The Web Application is a .dll-based Project structure. ASP.NET pages and supporting files are compiled into assemblies that are then deployed to the target server. Advantages of the Web Application are:
1) Precompiled files do not expose code to an attacker
2) Precompiled files run faster because they are binary data (the Microsoft Intermediate Language, or MSIL) executed by the CLR (Common Language Runtime)
3) References, assemblies, and other project dependencies are built in to the compiled site and automatically managed. They do not need to be manually deployed and/or registered in the Global Assembly Cache: deployment does this for you
If you are planning on using automated build and deployment, such as the Team Foundation Server Team Build engine, you will need to have your code in the form of a Web Application. If you have a Web Site, it will not properly compile as a Web Application would. However, all is not lost: it is possible to work around the issue by adding a Web Deployment Project to your Solution and then:
a) configuring the Web Deployment Project to precompile your code; and
b) configuring your Team Build definition to use the Web Deployment Project as its source for compilation.
https://msevents.microsoft.com/cui/WebCastEventDetails.aspx?culture=en-US&EventID=1032380764&CountryCode=US
ASP.NET MVC, C#, MS SQL Server, EF, MySql Server, Linq, Jquery, Java Script, Interview Questions. If you are looking for updates than kindly subscribe with this blog.
Saturday, March 3, 2012
Thursday, March 1, 2012
Linq Tutorial
Microsoft LINQ Tutorials
http://www.deitel.com/ResourceCenters/Programming/MicrosoftLINQ/Tutorials/tabid/2673/Default.aspx
Introducing C# 3 – Part 4 LINQ
http://www.programmersheaven.com/2/CSharp3-4
101 LINQ Samples
http://msdn.microsoft.com/en-us/vcsharp/aa336746.aspx
What is LinQ
http://www.dotnetspider.com/forum/173039-what-linq-net.aspx
Beginners Guides
http://www.progtalk.com/viewarticle.aspx?articleid=68
http://www.programmersheaven.com/2/CSharp3-4
http://dotnetslackers.com/articles/csharp/introducinglinq1.aspx
Using Linq
http://weblogs.asp.net/scottgu/archive/2006/05/14/446412.aspx
Step By Step Articles
http://www.codeproject.com/KB/linq/linqtutorial.aspx
http://www.codeproject.com/KB/linq/linqtutorial2.aspx
http://www.codeproject.com/KB/linq/linqtutorial3.aspx
http://www.deitel.com/ResourceCenters/Programming/MicrosoftLINQ/Tutorials/tabid/2673/Default.aspx
Introducing C# 3 – Part 4 LINQ
http://www.programmersheaven.com/2/CSharp3-4
101 LINQ Samples
http://msdn.microsoft.com/en-us/vcsharp/aa336746.aspx
What is LinQ
http://www.dotnetspider.com/forum/173039-what-linq-net.aspx
Beginners Guides
http://www.progtalk.com/viewarticle.aspx?articleid=68
http://www.programmersheaven.com/2/CSharp3-4
http://dotnetslackers.com/articles/csharp/introducinglinq1.aspx
Using Linq
http://weblogs.asp.net/scottgu/archive/2006/05/14/446412.aspx
Step By Step Articles
http://www.codeproject.com/KB/linq/linqtutorial.aspx
http://www.codeproject.com/KB/linq/linqtutorial2.aspx
http://www.codeproject.com/KB/linq/linqtutorial3.aspx
Sunday, February 12, 2012
Javascript Alert Message from code behind in ASP.NET
public static void ShowAlertMessage(string error)
{
Page page = HttpContext.Current.Handler as Page;
if (page != null)
{
error = error.Replace("'", "\'");
ScriptManager.RegisterStartupScript(page, page.GetType(), "err_msg", "alert('" + error + "');", true);
}
}
{
Page page = HttpContext.Current.Handler as Page;
if (page != null)
{
error = error.Replace("'", "\'");
ScriptManager.RegisterStartupScript(page, page.GetType(), "err_msg", "alert('" + error + "');", true);
}
}
Thursday, January 12, 2012
Friday, January 6, 2012
Thursday, January 5, 2012
Wednesday, December 7, 2011
Does the HTMLEditor control raise any client-side events?
The HTML Editor has three modes: Design, HTML Text and preview mode.
Design mode is in an IFrame. HTML Text is prensented in a TextArea and preview mode is in another Iframe. The code rendered about these three modes is as below.
iframe
id="editor1_ctl02_ctl00" name="editor1_ctl02_ctl00" marginheight="0" marginwidth="0" frameborder="0" src="javascript:false;" style="height:100%;width:100%;display:none;border-width:0px;">
/iframe>
textarea
id="editor1_ctl02_ctl01" class="ajax__htmleditor_htmlpanel_default" style="height:100%;width:100%;display:none;">
/textarea>
iframe
id="editor1_ctl02_ctl02" name="editor1_ctl02_ctl02" marginheight="0" marginwidth="0" frameborder="0" src="javascript:false;" style="height:100%;width:100%;display:none;border-width:0px;">
/iframe>
In design mode, we can use the following JavaScript to append a callback function in onKeypress event.
script type="text/javascript">
var count = 0;
function pageLoad() {
$get('editor1_ctl02_ctl00').contentWindow.document.body.onkeypress = function() {
count++;
$get('cc').innerHTML = "you input " + count + "charactors";
};
}
/script>
As a same way, you can append another keypress event on TextArea and preview IFrame.
Design mode is in an IFrame. HTML Text is prensented in a TextArea and preview mode is in another Iframe. The code rendered about these three modes is as below.
iframe
id="editor1_ctl02_ctl00" name="editor1_ctl02_ctl00" marginheight="0" marginwidth="0" frameborder="0" src="javascript:false;" style="height:100%;width:100%;display:none;border-width:0px;">
/iframe>
textarea
id="editor1_ctl02_ctl01" class="ajax__htmleditor_htmlpanel_default" style="height:100%;width:100%;display:none;">
/textarea>
iframe
id="editor1_ctl02_ctl02" name="editor1_ctl02_ctl02" marginheight="0" marginwidth="0" frameborder="0" src="javascript:false;" style="height:100%;width:100%;display:none;border-width:0px;">
/iframe>
In design mode, we can use the following JavaScript to append a callback function in onKeypress event.
script type="text/javascript">
var count = 0;
function pageLoad() {
$get('editor1_ctl02_ctl00').contentWindow.document.body.onkeypress = function() {
count++;
$get('cc').innerHTML = "you input " + count + "charactors";
};
}
/script>
As a same way, you can append another keypress event on TextArea and preview IFrame.
Why some links appear in a new tab, others in a new window?
Originally, it was made to resolve problems on IE8 32 bits when you use a 32 bits OS. I changed "%ProgramFiles(x86)%" var, and now my issue is resolved for IE8 32 bits on my Windows 7 64 bits. Please try it, and tell me if everything work for you.
For Win 7 64 bits :
1 - Create a new notepad document and paste this text :
@echo off
echo.
echo IEREREG Version 1.07 for IE8 27.03.2009
echo by Kai Schaetzl http://iefaq.info
echo installs and registers (if suitable) all DLLs known to be used by IE8.
echo should only take a few seconds, but please be patient
echo.
REM ******************************
echo registering IE files
REM IE files (= part of setup)
regsvr32 /s /i browseui.dll
REM regsvr32 /s /i browseui.dll,NI (unnecessary)
regsvr32 /s corpol.dll
regsvr32 /s dxtmsft.dll
regsvr32 /s dxtrans.dll
REM simple HTML Mail API
regsvr32 /s "%ProgramFiles(x86)%\internet explorer\hmmapi.dll"
REM group policy snap-in
regsvr32 /s ieaksie.dll
REM smart screen
regsvr32 /s ieapfltr.dll
REM ieak branding
regsvr32 /s iedkcs32.dll
REM dev tools
regsvr32 /s "%ProgramFiles(x86)%\internet explorer\iedvtool.dll"
regsvr32 /s iepeers.dll
REM Symptom: IE8 closes immediately on launch, missing from IE7
regsvr32 /s "%ProgramFiles(x86)%\internet explorer\ieproxy.dll"
REM no install point anymore
REM regsvr32 /s /i iesetup.dll
REM no reg point anymore
REM regsvr32 /s imgutil.dll
regsvr32 /s /i /n inetcpl.cpl
REM no install point anymore
REM regsvr32 /s /i inseng.dll
regsvr32 /s jscript.dll
REM license manager
regsvr32 /s licmgr10.dll
REM regsvr32 /s msapsspc.dll
REM regsvr32 /s mshta.exe
REM VS debugger
regsvr32 /s msdbg2.dll
REM no install point anymore
REM regsvr32 /s /i mshtml.dll
regsvr32 /s mshtmled.dll
regsvr32 /s msident.dll
REM no reg point anymore
REM regsvr32 /s msrating.dll
REM multimedia timer
regsvr32 /s mstime.dll
REM no install point anymore
REM regsvr32 /s /i occache.dll
REM process debug manager
regsvr32 /s "%ProgramFiles(x86)%\internet explorer\pdm.dll"
REM no reg point anymore
REM regsvr32 /s pngfilt.dll
REM regsvr32 /s /i setupwbv.dll (not there anymore!)
regsvr32 /s tdc.ocx
regsvr32 /s /i urlmon.dll
REM regsvr32 /s /i urlmon.dll,NI,HKLM
regsvr32 /s vbscript.dll
REM VML renderer
regsvr32 /s "%CommonProgramFiles%\microsoft shared\vgx\vgx.dll"
REM no install point anymore
REM regsvr32 /s /i webcheck.dll
regsvr32 /s /i /n wininet.dll
REM ******************************
echo registering system files
REM additional system dlls known to be used by IE
REM added 11.05.2006 Symptom: Add-Ons-Manager menu entry is present but nothing happens
regsvr32 /s extmgr.dll
REM added 12.05.2006 Symptom: Javascript links don't work (Robin Walker) .NET hub file
regsvr32 /s mscoree.dll
REM added 23.03.2009 Symptom: Find on this page is blank
regsvr32 /s oleacc.dll
REM added 24.03.2009 Symptom: Printing problems, open in new window
regsvr32 /s ole32.dll
REM mscorier.dll
REM mscories.dll
REM Symptom: open in new tab/window not working
regsvr32 /s actxprxy.dll
regsvr32 /s asctrls.ocx
regsvr32 /s cdfview.dll
regsvr32 /s comcat.dll
regsvr32 /s /i /n comctl32.dll
regsvr32 /s cryptdlg.dll
regsvr32 /s /i /n digest.dll
regsvr32 /s dispex.dll
regsvr32 /s hlink.dll
regsvr32 /s mlang.dll
regsvr32 /s mobsync.dll
regsvr32 /s /i msieftp.dll
REM regsvr32 /s msnsspc.dll #no entry point
regsvr32 /s msr2c.dll
regsvr32 /s msxml.dll
regsvr32 /s oleaut32.dll
REM regsvr32 /s plugin.ocx #no entry point
regsvr32 /s proctexe.ocx
REM plus DllRegisterServerEx ExA ExW ... ?
regsvr32 /s /i scrobj.dll
REM shdocvw.dll hasn't been updated for IE7 and IE8, it still registers itself for the Windows Internet Controls
regsvr32 /s /i shdocvw.dll
regsvr32 /s sendmail.dll
REM ******************************
REM PKI/crypto functionality
REM initpki can take very long to run and is rarely a problem
REM if there are problems with crypto, SSL, certificates
REM remove the three following REMs from the lines
REM echo We are almost done except one crypto file
REM echo but this will take very long, be patient!
REM regsvr32 /s /i:A initpki.dll
REM ******************************
REM tabbed browser, do at the end, why originally with /n ?
regsvr32 /s /i ieframe.dll
REM ******************************
echo correcting bugs in the registry
REM do some corrective work
REM Symptom: new tabs page cannot display content because it cannot access the controls (added 27. 3.2009)
REM This is a result of a bug in shdocvw.dll (see above), probably only on Windows XP
reg add "HKCR\TypeLib\{EAB22AC0-30C1-11CF-A7EB-0000C05BAE0B}\1.1\0\win32" /ve /t REG_SZ /d %systemroot%\system32\ieframe.dll /f
REM ******************************
echo all tasks have been finished
echo.
pause
2 - Close all your IE windows and processes.
3 - Save your document on your Desktop by example, with the .bat extension. Right-click on it, and select "Run as administrator".
4 - Test if this tip resolved your issue by openning IE. If you use a Windows 32 bits version, please replace %ProgramFiles(x86)% by %ProgramFiles% in your .bat file.
For Win 7 64 bits :
1 - Create a new notepad document and paste this text :
@echo off
echo.
echo IEREREG Version 1.07 for IE8 27.03.2009
echo by Kai Schaetzl http://iefaq.info
echo installs and registers (if suitable) all DLLs known to be used by IE8.
echo should only take a few seconds, but please be patient
echo.
REM ******************************
echo registering IE files
REM IE files (= part of setup)
regsvr32 /s /i browseui.dll
REM regsvr32 /s /i browseui.dll,NI (unnecessary)
regsvr32 /s corpol.dll
regsvr32 /s dxtmsft.dll
regsvr32 /s dxtrans.dll
REM simple HTML Mail API
regsvr32 /s "%ProgramFiles(x86)%\internet explorer\hmmapi.dll"
REM group policy snap-in
regsvr32 /s ieaksie.dll
REM smart screen
regsvr32 /s ieapfltr.dll
REM ieak branding
regsvr32 /s iedkcs32.dll
REM dev tools
regsvr32 /s "%ProgramFiles(x86)%\internet explorer\iedvtool.dll"
regsvr32 /s iepeers.dll
REM Symptom: IE8 closes immediately on launch, missing from IE7
regsvr32 /s "%ProgramFiles(x86)%\internet explorer\ieproxy.dll"
REM no install point anymore
REM regsvr32 /s /i iesetup.dll
REM no reg point anymore
REM regsvr32 /s imgutil.dll
regsvr32 /s /i /n inetcpl.cpl
REM no install point anymore
REM regsvr32 /s /i inseng.dll
regsvr32 /s jscript.dll
REM license manager
regsvr32 /s licmgr10.dll
REM regsvr32 /s msapsspc.dll
REM regsvr32 /s mshta.exe
REM VS debugger
regsvr32 /s msdbg2.dll
REM no install point anymore
REM regsvr32 /s /i mshtml.dll
regsvr32 /s mshtmled.dll
regsvr32 /s msident.dll
REM no reg point anymore
REM regsvr32 /s msrating.dll
REM multimedia timer
regsvr32 /s mstime.dll
REM no install point anymore
REM regsvr32 /s /i occache.dll
REM process debug manager
regsvr32 /s "%ProgramFiles(x86)%\internet explorer\pdm.dll"
REM no reg point anymore
REM regsvr32 /s pngfilt.dll
REM regsvr32 /s /i setupwbv.dll (not there anymore!)
regsvr32 /s tdc.ocx
regsvr32 /s /i urlmon.dll
REM regsvr32 /s /i urlmon.dll,NI,HKLM
regsvr32 /s vbscript.dll
REM VML renderer
regsvr32 /s "%CommonProgramFiles%\microsoft shared\vgx\vgx.dll"
REM no install point anymore
REM regsvr32 /s /i webcheck.dll
regsvr32 /s /i /n wininet.dll
REM ******************************
echo registering system files
REM additional system dlls known to be used by IE
REM added 11.05.2006 Symptom: Add-Ons-Manager menu entry is present but nothing happens
regsvr32 /s extmgr.dll
REM added 12.05.2006 Symptom: Javascript links don't work (Robin Walker) .NET hub file
regsvr32 /s mscoree.dll
REM added 23.03.2009 Symptom: Find on this page is blank
regsvr32 /s oleacc.dll
REM added 24.03.2009 Symptom: Printing problems, open in new window
regsvr32 /s ole32.dll
REM mscorier.dll
REM mscories.dll
REM Symptom: open in new tab/window not working
regsvr32 /s actxprxy.dll
regsvr32 /s asctrls.ocx
regsvr32 /s cdfview.dll
regsvr32 /s comcat.dll
regsvr32 /s /i /n comctl32.dll
regsvr32 /s cryptdlg.dll
regsvr32 /s /i /n digest.dll
regsvr32 /s dispex.dll
regsvr32 /s hlink.dll
regsvr32 /s mlang.dll
regsvr32 /s mobsync.dll
regsvr32 /s /i msieftp.dll
REM regsvr32 /s msnsspc.dll #no entry point
regsvr32 /s msr2c.dll
regsvr32 /s msxml.dll
regsvr32 /s oleaut32.dll
REM regsvr32 /s plugin.ocx #no entry point
regsvr32 /s proctexe.ocx
REM plus DllRegisterServerEx ExA ExW ... ?
regsvr32 /s /i scrobj.dll
REM shdocvw.dll hasn't been updated for IE7 and IE8, it still registers itself for the Windows Internet Controls
regsvr32 /s /i shdocvw.dll
regsvr32 /s sendmail.dll
REM ******************************
REM PKI/crypto functionality
REM initpki can take very long to run and is rarely a problem
REM if there are problems with crypto, SSL, certificates
REM remove the three following REMs from the lines
REM echo We are almost done except one crypto file
REM echo but this will take very long, be patient!
REM regsvr32 /s /i:A initpki.dll
REM ******************************
REM tabbed browser, do at the end, why originally with /n ?
regsvr32 /s /i ieframe.dll
REM ******************************
echo correcting bugs in the registry
REM do some corrective work
REM Symptom: new tabs page cannot display content because it cannot access the controls (added 27. 3.2009)
REM This is a result of a bug in shdocvw.dll (see above), probably only on Windows XP
reg add "HKCR\TypeLib\{EAB22AC0-30C1-11CF-A7EB-0000C05BAE0B}\1.1\0\win32" /ve /t REG_SZ /d %systemroot%\system32\ieframe.dll /f
REM ******************************
echo all tasks have been finished
echo.
pause
2 - Close all your IE windows and processes.
3 - Save your document on your Desktop by example, with the .bat extension. Right-click on it, and select "Run as administrator".
4 - Test if this tip resolved your issue by openning IE. If you use a Windows 32 bits version, please replace %ProgramFiles(x86)% by %ProgramFiles% in your .bat file.
Wednesday, November 2, 2011
Securing ASP.Net Pages - Forms Authentication - C# and .Net 4
ASP.Net has a built-in feature named Forms Authentication that allows a developer to easily secure certain areas of a web site. In this post I'm going to build a simple authentication sample using C# and ASP.Net 4.0 (still in beta as of the posting date).
Security settings with ASP.Net is configured from within the web.config file. This is a standard ASCII file, with an XML format, that is located in the root of your web application. Here is a sample web.config file:
configuration>
system.web>
authenticationmode="Forms">
formsname="TestAuthCookie"loginUrl="login.aspx"timeout="30">
credentialspasswordFormat="Clear">
username="user1"password="pass1"/>
username="user2"password="pass2"/>
>
>
>
authorization>
denyusers="?"/>
>
compilationtargetFramework="4.0"/>
pagescontrolRenderingCompatibilityVersion="3.5"clientIDMode="AutoID"/>
>
>
Here is the complete source of the sample login.aspx page:
div>
Username:
asp:TextBox ID="txtUsername" runat="server">:TextBox>
Password:
asp:TextBox ID="txtPassword" runat="server">:TextBox>
asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Login" />
asp:Label ID="lblStatus" runat="server" Text="Please login">:Label>
/div>
And here is the complete source of the login.aspx.cs file:
using System;
using System.Web.UI.WebControls;
using System.Web.Security;
public partial class Default3 : System.Web.UI.Page
{
protected void Button1_Click(object sender, EventArgs e)
{
if (FormsAuthentication.Authenticate(txtUsername.Text, txtPassword.Text))
{
lblStatus.Text = ("Welcome " + txtUsername.Text);
FormsAuthentication.RedirectFromLoginPage(txtUsername.Text, true);
}
else
{
lblStatus.Text = "Invalid login!";
}
}
}
Security settings with ASP.Net is configured from within the web.config file. This is a standard ASCII file, with an XML format, that is located in the root of your web application. Here is a sample web.config file:
configuration>
system.web>
authenticationmode="Forms">
formsname="TestAuthCookie"loginUrl="login.aspx"timeout="30">
credentialspasswordFormat="Clear">
username="user1"password="pass1"/>
username="user2"password="pass2"/>
>
>
>
authorization>
denyusers="?"/>
>
compilationtargetFramework="4.0"/>
pagescontrolRenderingCompatibilityVersion="3.5"clientIDMode="AutoID"/>
>
>
Here is the complete source of the sample login.aspx page:
div>
Username:
asp:TextBox ID="txtUsername" runat="server">:TextBox>
Password:
asp:TextBox ID="txtPassword" runat="server">:TextBox>
asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Login" />
asp:Label ID="lblStatus" runat="server" Text="Please login">:Label>
/div>
And here is the complete source of the login.aspx.cs file:
using System;
using System.Web.UI.WebControls;
using System.Web.Security;
public partial class Default3 : System.Web.UI.Page
{
protected void Button1_Click(object sender, EventArgs e)
{
if (FormsAuthentication.Authenticate(txtUsername.Text, txtPassword.Text))
{
lblStatus.Text = ("Welcome " + txtUsername.Text);
FormsAuthentication.RedirectFromLoginPage(txtUsername.Text, true);
}
else
{
lblStatus.Text = "Invalid login!";
}
}
}
Tuesday, October 11, 2011
How to read/write cookies in asp.net
Writing Cookies
Response.Cookies["userName"].Value = "patrick";
Response.Cookies["userName"].Expires = DateTime.Now.AddDays(1);
HttpCookie aCookie = new HttpCookie("lastVisit");
aCookie.Value = DateTime.Now.ToString();
aCookie.Expires = DateTime.Now.AddDays(1);
Response.Cookies.Add(aCookie);
Reading Cookies:
if(Request.Cookies["userName"] != null)
Label1.Text = Server.HtmlEncode(Request.Cookies["userName"].Value);
if(Request.Cookies["userName"] != null)
{
HttpCookie aCookie = Request.Cookies["userName"];
Label1.Text = Server.HtmlEncode(aCookie.Value);
}
Below link will give you full detailed information about cookies
http://msdn.microsoft.com/en-us/library/ms178194.aspx
Response.Cookies["userName"].Value = "patrick";
Response.Cookies["userName"].Expires = DateTime.Now.AddDays(1);
HttpCookie aCookie = new HttpCookie("lastVisit");
aCookie.Value = DateTime.Now.ToString();
aCookie.Expires = DateTime.Now.AddDays(1);
Response.Cookies.Add(aCookie);
Reading Cookies:
if(Request.Cookies["userName"] != null)
Label1.Text = Server.HtmlEncode(Request.Cookies["userName"].Value);
if(Request.Cookies["userName"] != null)
{
HttpCookie aCookie = Request.Cookies["userName"];
Label1.Text = Server.HtmlEncode(aCookie.Value);
}
Below link will give you full detailed information about cookies
http://msdn.microsoft.com/en-us/library/ms178194.aspx
Sunday, September 25, 2011
Difference between Web.Config and Machine.Config File
Two types of configuration files supported by ASP.Net.
Configuration files are used to control and manage the behavior of a web application.
i) Machine.config
ii)Web.config
Difference between Machine.Config and Web.Config
Machine.Config:
i) This is automatically installed when you install Visual Studio. Net.
ii) This is also called machine level configuration file.
iii)Only one machine.config file exists on a server.
iv) This file is at the highest level in the configuration hierarchy.
Web.Config:
i) This is automatically created when you create an ASP.Net web application project.
ii) This is also called application level configuration file.
iii)This file inherits setting from the machine.config
Configuration files are used to control and manage the behavior of a web application.
i) Machine.config
ii)Web.config
Difference between Machine.Config and Web.Config
Machine.Config:
i) This is automatically installed when you install Visual Studio. Net.
ii) This is also called machine level configuration file.
iii)Only one machine.config file exists on a server.
iv) This file is at the highest level in the configuration hierarchy.
Web.Config:
i) This is automatically created when you create an ASP.Net web application project.
ii) This is also called application level configuration file.
iii)This file inherits setting from the machine.config
Friday, September 9, 2011
Restricting access to page or directory in ASP.NET
You have to use Forms Authentication.
http://support.microsoft.com/kb/301240
How to subtract 1 from a orginal count in an ASP.NET gridview
I have a gridview that contains a count (whic is Quantity) were i have a button that adds a row under the orginal row and i need the sub row's count (Quantity) to subtract one from the orgianl row Quantity.
EX: Before button click
Orgianl row = 3
After click
Orginal row = 2
Subrow = 1
Code:
ASP.NET
// FUNCTION : Adds a new subrow
protected void gvParent_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName.Equals("btn_AddRow", StringComparison.OrdinalIgnoreCase))
{
// Get the row that was clicked (index 0. Meaning that 0 is 1, 1 is 2 and so on)
// Objects can be null, Int32s cannot not.
// Int16 = 2 bytes long (short)
// Int32 = 4 bytes long (int)
// Int64 = 8 bytes long (long)
int i = Convert.ToInt32(e.CommandArgument);
// create a DataTable based off the view state
DataTable dataTable = (DataTable)ViewState["gvParent"];
for (int part = 0; part < dataTable.Rows.Count; part++) { int oldQuantity = Convert.ToInt32(dataTable.Rows[i]["Quantity"]); string partNumber = dataTable.Rows[i]["ProductDescription"].ToString(); string description = dataTable.Rows[i]["Description"].ToString(); string dateOrdered = dataTable.Rows[i]["GTRI_DateSubmittedtoPurchasing"].ToString(); string estShipDate = dataTable.Rows[i]["Gtri_EstShipDate"].ToString(); string actualShipDate = dataTable.Rows[i]["Gtri_ActualShipDate"].ToString(); string trackingNumb = dataTable.Rows[i]["GTRI_TrackingNumbers"].ToString(); string serialNumb = dataTable.Rows[i]["Gtri_SerialNumber"].ToString(); int oldQuantitySubtract = Convert.ToInt32(dataTable.Rows[part]["Quantity"]); string curentPartNumbers = dataTable.Rows[part]["ProductDescription"].ToString(); string currentDescription = dataTable.Rows[part]["Description"].ToString(); string currentDateOrdered = dataTable.Rows[part]["GTRI_DateSubmittedtoPurchasing"].ToString(); string currentEstShipDate = dataTable.Rows[part]["Gtri_EstShipDate"].ToString(); string currentActualShipDate = dataTable.Rows[part]["Gtri_ActualShipDate"].ToString(); string currentTrackingNumb = dataTable.Rows[part]["GTRI_TrackingNumbers"].ToString(); string currentSerialNumb = dataTable.Rows[part]["Gtri_SerialNumber"].ToString(); if (partNumber.Equals(curentPartNumbers, StringComparison.OrdinalIgnoreCase) && oldQuantitySubtract > 1)
{
dataTable.Rows[part]["Quantity"] = oldQuantitySubtract - 1;
// Instert a new row at a specific index
DataRow dtAdd = dataTable.NewRow();
for (int k = 0; k < dataTable.Columns.Count; k++)
dtAdd[k] = dataTable.Rows[part][k];
dataTable.Rows.InsertAt(dtAdd, i + 1);
break;
//dataTable.Rows.Add(dtAdd);
}
}
// Rebind the data
gvParent.DataSource = dataTable;
gvParent.DataBind();
}
}
EX: Before button click
Orgianl row = 3
After click
Orginal row = 2
Subrow = 1
Code:
ASP.NET
// FUNCTION : Adds a new subrow
protected void gvParent_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName.Equals("btn_AddRow", StringComparison.OrdinalIgnoreCase))
{
// Get the row that was clicked (index 0. Meaning that 0 is 1, 1 is 2 and so on)
// Objects can be null, Int32s cannot not.
// Int16 = 2 bytes long (short)
// Int32 = 4 bytes long (int)
// Int64 = 8 bytes long (long)
int i = Convert.ToInt32(e.CommandArgument);
// create a DataTable based off the view state
DataTable dataTable = (DataTable)ViewState["gvParent"];
for (int part = 0; part < dataTable.Rows.Count; part++) { int oldQuantity = Convert.ToInt32(dataTable.Rows[i]["Quantity"]); string partNumber = dataTable.Rows[i]["ProductDescription"].ToString(); string description = dataTable.Rows[i]["Description"].ToString(); string dateOrdered = dataTable.Rows[i]["GTRI_DateSubmittedtoPurchasing"].ToString(); string estShipDate = dataTable.Rows[i]["Gtri_EstShipDate"].ToString(); string actualShipDate = dataTable.Rows[i]["Gtri_ActualShipDate"].ToString(); string trackingNumb = dataTable.Rows[i]["GTRI_TrackingNumbers"].ToString(); string serialNumb = dataTable.Rows[i]["Gtri_SerialNumber"].ToString(); int oldQuantitySubtract = Convert.ToInt32(dataTable.Rows[part]["Quantity"]); string curentPartNumbers = dataTable.Rows[part]["ProductDescription"].ToString(); string currentDescription = dataTable.Rows[part]["Description"].ToString(); string currentDateOrdered = dataTable.Rows[part]["GTRI_DateSubmittedtoPurchasing"].ToString(); string currentEstShipDate = dataTable.Rows[part]["Gtri_EstShipDate"].ToString(); string currentActualShipDate = dataTable.Rows[part]["Gtri_ActualShipDate"].ToString(); string currentTrackingNumb = dataTable.Rows[part]["GTRI_TrackingNumbers"].ToString(); string currentSerialNumb = dataTable.Rows[part]["Gtri_SerialNumber"].ToString(); if (partNumber.Equals(curentPartNumbers, StringComparison.OrdinalIgnoreCase) && oldQuantitySubtract > 1)
{
dataTable.Rows[part]["Quantity"] = oldQuantitySubtract - 1;
// Instert a new row at a specific index
DataRow dtAdd = dataTable.NewRow();
for (int k = 0; k < dataTable.Columns.Count; k++)
dtAdd[k] = dataTable.Rows[part][k];
dataTable.Rows.InsertAt(dtAdd, i + 1);
break;
//dataTable.Rows.Add(dtAdd);
}
}
// Rebind the data
gvParent.DataSource = dataTable;
gvParent.DataBind();
}
}
What are "Expression Trees" in C# ?
URL explains Expression Trees with examples in C# and VB.
http://msdn.microsoft.com/en-us/library/bb397951.aspx
http://msdn.microsoft.com/en-us/library/bb397951.aspx
Integrating ASP.NET MVC 3 into existing upgraded ASP.NET 4 Web Forms applications
http://www.hanselman.com/blog/IntegratingASPNETMVC3IntoExistingUpgradedASPNET4WebFormsApplications.aspx
As per above article I follow the steps to integrate WebApp with MVC application. I am successfully integrated MVC project into WebApp(C#) and also VB.NET MVC and VB.NET WebApp also I am able to successfully integrated.
The problem is If I choose WebApp as VB.NET project, and integrated with C# MVC project. In this case the request is not routing to corresponding MVC files.
What could be the reason not routing to MVC. Do we need to plug some extra dlls?
As per above article I follow the steps to integrate WebApp with MVC application. I am successfully integrated MVC project into WebApp(C#) and also VB.NET MVC and VB.NET WebApp also I am able to successfully integrated.
The problem is If I choose WebApp as VB.NET project, and integrated with C# MVC project. In this case the request is not routing to corresponding MVC files.
What could be the reason not routing to MVC. Do we need to plug some extra dlls?
How to access values of dynamically created TextBoxes
If one adds controls dynamically to a page and wants to get their information after PostBack, one needs to recreate these elements after the PostBack. Let's consider the following idea: First you create some controls:
for(int i=0;i<10;i++) {
TextBox objBox = new TextBox();
objBox.ID = "objBox" + i.ToString();
this.Page.Controls.Add(objBox);
}
After PostBack, you want to retrieve the text entered in the third TextBox. If you try this:
String strText = objBox2.Text;
you'll receive an exception. Why? Because the boxes have not been created again and the local variable objBox2 simply not exists.
How to retrieve the Box?
You'll need to recreate the box by using the code above. Then, you may try to get its value by using the following code:
TextBox objBox2;
objBox2 = this.Page.FindControl("objBox2") as TextBox;
if(objBox2 != null)
Response.Write(objBox2.Text);
for(int i=0;i<10;i++) {
TextBox objBox = new TextBox();
objBox.ID = "objBox" + i.ToString();
this.Page.Controls.Add(objBox);
}
After PostBack, you want to retrieve the text entered in the third TextBox. If you try this:
String strText = objBox2.Text;
you'll receive an exception. Why? Because the boxes have not been created again and the local variable objBox2 simply not exists.
How to retrieve the Box?
You'll need to recreate the box by using the code above. Then, you may try to get its value by using the following code:
TextBox objBox2;
objBox2 = this.Page.FindControl("objBox2") as TextBox;
if(objBox2 != null)
Response.Write(objBox2.Text);
Sunday, July 10, 2011
SQL Server 2008 Designer Behavior Change: Saving Changes Not Permitted
Warning Message:
Saving changes is not permitted. The changes you have made require the following tables to be dropped and re-created. You have either made changes to a table that can't be re-created or enabled the option Prevent saving changes that require the table to be re-created.
This is by design and can be quickly fixed in Management Studio by unchecking a property. To fix this in Management Studio, go to Tools -> Options then go to the Designer Page and uncheck "Prevent saving changes that require table re-creation"
Saving changes is not permitted. The changes you have made require the following tables to be dropped and re-created. You have either made changes to a table that can't be re-created or enabled the option Prevent saving changes that require the table to be re-created.
This is by design and can be quickly fixed in Management Studio by unchecking a property. To fix this in Management Studio, go to Tools -> Options then go to the Designer Page and uncheck "Prevent saving changes that require table re-creation"
Sunday, June 19, 2011
C# - How to detect all IP addresses from a LAN?
string strHostName = string.Empty;
cmbIPAddress.Items.Clear();
// Getting Ip address of local machine...
// First get the host name of local machine.
strHostName = Dns.GetHostName();
// Then using host name, get the IP address list..
IPHostEntry ipEntry = Dns.GetHostByName(strHostName);
IPAddress[] iparrAddr = ipEntry.AddressList;
if (iparrAddr.Length > 0)
{
for (int intLoop = 0; intLoop < iparrAddr.Length; intLoop++)
cmbIPAddress.Items.Add(iparrAddr[intLoop].ToString());
}
cmbIPAddress.Items.Clear();
// Getting Ip address of local machine...
// First get the host name of local machine.
strHostName = Dns.GetHostName();
// Then using host name, get the IP address list..
IPHostEntry ipEntry = Dns.GetHostByName(strHostName);
IPAddress[] iparrAddr = ipEntry.AddressList;
if (iparrAddr.Length > 0)
{
for (int intLoop = 0; intLoop < iparrAddr.Length; intLoop++)
cmbIPAddress.Items.Add(iparrAddr[intLoop].ToString());
}
Tuesday, May 24, 2011
Difference between Detach/Attach and Restore/BackUp a DB
Transact-SQL BACKUP/RESTORE is the normal method for database backup and
recovery. Databases can be backed up while online. The backup file size is
usually smaller than the database files since only used pages are backed up.
Also, in the FULL or BULK_LOGGED recovery model, you can reduce potential
data loss by performing transaction log backups.
Detaching a database removes the database from SQL Server while leaving the
physical database files intact. This allows you to rename or move the
physical files and then re-attach. Although one could perform cold backups
using this technique, detach/attach isn't really intended to be used as a
backup/recovery process.
Commonly it is recommended that you use BACKUP/RESTORE for disaster recovery (DR) scenario and copying data from one location to another. But this is not absolute, sometimes for a very large database, if you want to move it from one location to another, backup/restore process may spend a lot of time which you do not like, in this case, detaching/attaching a database is a better way since you can attach a workable database very fast. But you need to aware that detaching a database will bring it offline for a short time and detaching/attaching does not provide DR function.
For more information about detaching and attaching databases, you can refer to:
Detaching and Attaching Databases
http://technet.microsoft.com/en-us/library/ms190794.aspx
recovery. Databases can be backed up while online. The backup file size is
usually smaller than the database files since only used pages are backed up.
Also, in the FULL or BULK_LOGGED recovery model, you can reduce potential
data loss by performing transaction log backups.
Detaching a database removes the database from SQL Server while leaving the
physical database files intact. This allows you to rename or move the
physical files and then re-attach. Although one could perform cold backups
using this technique, detach/attach isn't really intended to be used as a
backup/recovery process.
Commonly it is recommended that you use BACKUP/RESTORE for disaster recovery (DR) scenario and copying data from one location to another. But this is not absolute, sometimes for a very large database, if you want to move it from one location to another, backup/restore process may spend a lot of time which you do not like, in this case, detaching/attaching a database is a better way since you can attach a workable database very fast. But you need to aware that detaching a database will bring it offline for a short time and detaching/attaching does not provide DR function.
For more information about detaching and attaching databases, you can refer to:
Detaching and Attaching Databases
http://technet.microsoft.com/en-us/library/ms190794.aspx
Wednesday, May 18, 2011
How To Get Web Site Thumbnail Image In ASP.NET
Overview
One very common requirement of many web applications is to display a thumbnail image of a web site. A typical example is to provide a link to a dynamic website displaying its current thumbnail image, or displaying images of websites with their links as a result of search (I love to see it on Google). Microsoft .NET Framework 2.0 makes it quite easier to do it in a ASP.NET application.
Background
In order to generate image of a web page, first we need to load the web page to get their html code, and then this html needs to be rendered in a web browser. After that, a screen shot can be taken easily. I think there is no easier way to do this. Before .NET framework 2.0 it was quite difficult to use a web browser in C# or VB.NET because we either have to use COM+ interoperability or third party controls which becomes headache later.
WebBrowser control in .NET framework 2.0
In .NET framework 2.0 we have a new Windows Forms WebBrowser control which is a wrapper around old shwdoc.dll. All you really need to do is to drop a WebBrowser control from your Toolbox on your form in .NET framework 2.0.
If you have not used WebBrowser control yet, it's quite easy to use and very consistent with other Windows Forms controls. Some important methods of WebBrowser control are.
public bool GoBack();
public bool GoForward();
public void GoHome();
public void GoSearch();
public void Navigate(Uri url);
public void DrawToBitmap(Bitmap bitmap, Rectangle targetBounds);
These methods are self explanatory with their names like Navigate function which redirects browser to provided URL. It also has a number of useful overloads. The DrawToBitmap (inherited from Control) draws the current image of WebBrowser to the provided bitmap.
Using WebBrowser control in ASP.NET 2.0
The Solution
Let's start to implement the solution which we discussed above. First we will define a static method to get the web site thumbnail image.
public static Bitmap GetWebSiteThumbnail(string Url, int BrowserWidth, int BrowserHeight, int ThumbnailWidth, int ThumbnailHeight)
{
WebsiteThumbnailImage thumbnailGenerator = new WebsiteThumbnailImage(Url, BrowserWidth, BrowserHeight, ThumbnailWidth, ThumbnailHeight);
return thumbnailGenerator.GenerateWebSiteThumbnailImage();
}
The WebsiteThumbnailImage class will have a public method named GenerateWebSiteThumbnailImage which will generate the website thumbnail image in a separate STA thread and wait for the thread to exit. In this case, I decided to Join method of Thread class to block the initial calling thread until the bitmap is actually available, and then return the generated web site thumbnail.
public Bitmap GenerateWebSiteThumbnailImage()
{
Thread m_thread = new Thread(new ThreadStart(_GenerateWebSiteThumbnailImage));
m_thread.SetApartmentState(ApartmentState.STA);
m_thread.Start();
m_thread.Join();
return m_Bitmap;
}
The _GenerateWebSiteThumbnailImage will create a WebBrowser control object and navigate to the provided Url. We also register for the DocumentCompleted event of the web browser control to take screen shot of the web page. To pass the flow to the other controls we need to perform a method call to Application.DoEvents(); and wait for the completion of the navigation until the browser state changes to Complete in a loop.
private void _GenerateWebSiteThumbnailImage()
{
WebBrowser m_WebBrowser = new WebBrowser();
m_WebBrowser.ScrollBarsEnabled = false;
m_WebBrowser.Navigate(m_Url);
m_WebBrowser.DocumentCompleted += new WebBrowserDocument
CompletedEventHandler(WebBrowser_DocumentCompleted);
while (m_WebBrowser.ReadyState != WebBrowserReadyState.Complete)
Application.DoEvents();
m_WebBrowser.Dispose();
}
The DocumentCompleted event will be fired when the navigation is completed and the browser is ready for screen shot. We will get screen shot using DrawToBitmap method as described previously which will return the bitmap of the web browser. Then the thumbnail image is generated using GetThumbnailImage method of Bitmap class passing it the required thumbnail image width and height.
private void WebBrowser_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
WebBrowser m_WebBrowser = (WebBrowser)sender;
m_WebBrowser.ClientSize = new Size(this.m_BrowserWidth, this.m_BrowserHeight);
m_WebBrowser.ScrollBarsEnabled = false;
m_Bitmap = new Bitmap(m_WebBrowser.Bounds.Width, m_WebBrowser.Bounds.Height);
m_WebBrowser.BringToFront();
m_WebBrowser.DrawToBitmap(m_Bitmap, m_WebBrowser.Bounds);
m_Bitmap = (Bitmap)m_Bitmap.GetThumbnailImage(m_ThumbnailWidth, m_ThumbnailHeight, null, IntPtr.Zero);
}
One more example here : http://www.codeproject.com/KB/aspnet/Website_URL_Screenshot.aspx
One very common requirement of many web applications is to display a thumbnail image of a web site. A typical example is to provide a link to a dynamic website displaying its current thumbnail image, or displaying images of websites with their links as a result of search (I love to see it on Google). Microsoft .NET Framework 2.0 makes it quite easier to do it in a ASP.NET application.
Background
In order to generate image of a web page, first we need to load the web page to get their html code, and then this html needs to be rendered in a web browser. After that, a screen shot can be taken easily. I think there is no easier way to do this. Before .NET framework 2.0 it was quite difficult to use a web browser in C# or VB.NET because we either have to use COM+ interoperability or third party controls which becomes headache later.
WebBrowser control in .NET framework 2.0
In .NET framework 2.0 we have a new Windows Forms WebBrowser control which is a wrapper around old shwdoc.dll. All you really need to do is to drop a WebBrowser control from your Toolbox on your form in .NET framework 2.0.
If you have not used WebBrowser control yet, it's quite easy to use and very consistent with other Windows Forms controls. Some important methods of WebBrowser control are.
public bool GoBack();
public bool GoForward();
public void GoHome();
public void GoSearch();
public void Navigate(Uri url);
public void DrawToBitmap(Bitmap bitmap, Rectangle targetBounds);
These methods are self explanatory with their names like Navigate function which redirects browser to provided URL. It also has a number of useful overloads. The DrawToBitmap (inherited from Control) draws the current image of WebBrowser to the provided bitmap.
Using WebBrowser control in ASP.NET 2.0
The Solution
Let's start to implement the solution which we discussed above. First we will define a static method to get the web site thumbnail image.
public static Bitmap GetWebSiteThumbnail(string Url, int BrowserWidth, int BrowserHeight, int ThumbnailWidth, int ThumbnailHeight)
{
WebsiteThumbnailImage thumbnailGenerator = new WebsiteThumbnailImage(Url, BrowserWidth, BrowserHeight, ThumbnailWidth, ThumbnailHeight);
return thumbnailGenerator.GenerateWebSiteThumbnailImage();
}
The WebsiteThumbnailImage class will have a public method named GenerateWebSiteThumbnailImage which will generate the website thumbnail image in a separate STA thread and wait for the thread to exit. In this case, I decided to Join method of Thread class to block the initial calling thread until the bitmap is actually available, and then return the generated web site thumbnail.
public Bitmap GenerateWebSiteThumbnailImage()
{
Thread m_thread = new Thread(new ThreadStart(_GenerateWebSiteThumbnailImage));
m_thread.SetApartmentState(ApartmentState.STA);
m_thread.Start();
m_thread.Join();
return m_Bitmap;
}
The _GenerateWebSiteThumbnailImage will create a WebBrowser control object and navigate to the provided Url. We also register for the DocumentCompleted event of the web browser control to take screen shot of the web page. To pass the flow to the other controls we need to perform a method call to Application.DoEvents(); and wait for the completion of the navigation until the browser state changes to Complete in a loop.
private void _GenerateWebSiteThumbnailImage()
{
WebBrowser m_WebBrowser = new WebBrowser();
m_WebBrowser.ScrollBarsEnabled = false;
m_WebBrowser.Navigate(m_Url);
m_WebBrowser.DocumentCompleted += new WebBrowserDocument
CompletedEventHandler(WebBrowser_DocumentCompleted);
while (m_WebBrowser.ReadyState != WebBrowserReadyState.Complete)
Application.DoEvents();
m_WebBrowser.Dispose();
}
The DocumentCompleted event will be fired when the navigation is completed and the browser is ready for screen shot. We will get screen shot using DrawToBitmap method as described previously which will return the bitmap of the web browser. Then the thumbnail image is generated using GetThumbnailImage method of Bitmap class passing it the required thumbnail image width and height.
private void WebBrowser_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
WebBrowser m_WebBrowser = (WebBrowser)sender;
m_WebBrowser.ClientSize = new Size(this.m_BrowserWidth, this.m_BrowserHeight);
m_WebBrowser.ScrollBarsEnabled = false;
m_Bitmap = new Bitmap(m_WebBrowser.Bounds.Width, m_WebBrowser.Bounds.Height);
m_WebBrowser.BringToFront();
m_WebBrowser.DrawToBitmap(m_Bitmap, m_WebBrowser.Bounds);
m_Bitmap = (Bitmap)m_Bitmap.GetThumbnailImage(m_ThumbnailWidth, m_ThumbnailHeight, null, IntPtr.Zero);
}
One more example here : http://www.codeproject.com/KB/aspnet/Website_URL_Screenshot.aspx
Tuesday, May 3, 2011
Edit in desktop application with DataGridView
private void DataGridView_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
if (e.ColumnIndex == 0)
{
string s = DataGridView.Rows[e.RowIndex].Cells[1].FormattedValue.ToString();
srno = Convert.ToInt16(s);
FormName objFrm = new FormName(s);
objFrm.MdiParent = this.MdiParent;
objFrm.Show();
}
}
//Into the New Form
public FormName(string id)
{
uid = id;
i = Convert.ToInt16(id);
InitializeComponent();
}
//Get Detail As per id
public void GetDetail()
{
string detail = "SELECT fieldname1,fieldname2 FROM TableName where PrimaryKeyField = "+id+"";
DataSet ds = new DataSet();
ds = (DataSet)prm.RetriveData(detail);
}
//RetriveData Function
public object RetriveData(string query)
{
// If you have sql connection use SqlConnection
OleDbConnection con = new OleDbConnection(constr);
OleDbDataAdapter drap = new OleDbDataAdapter(query, con);
con.Open();
DataSet ds = new DataSet();
drap.Fill(ds);
con.Close();
return ds;
}
{
if (e.ColumnIndex == 0)
{
string s = DataGridView.Rows[e.RowIndex].Cells[1].FormattedValue.ToString();
srno = Convert.ToInt16(s);
FormName objFrm = new FormName(s);
objFrm.MdiParent = this.MdiParent;
objFrm.Show();
}
}
//Into the New Form
public FormName(string id)
{
uid = id;
i = Convert.ToInt16(id);
InitializeComponent();
}
//Get Detail As per id
public void GetDetail()
{
string detail = "SELECT fieldname1,fieldname2 FROM TableName where PrimaryKeyField = "+id+"";
DataSet ds = new DataSet();
ds = (DataSet)prm.RetriveData(detail);
}
//RetriveData Function
public object RetriveData(string query)
{
// If you have sql connection use SqlConnection
OleDbConnection con = new OleDbConnection(constr);
OleDbDataAdapter drap = new OleDbDataAdapter(query, con);
con.Open();
DataSet ds = new DataSet();
drap.Fill(ds);
con.Close();
return ds;
}
Thursday, March 17, 2011
Run a .sql script file in C#
using System.Data.SqlClient;
using System.IO;
using Microsoft.SqlServer.Management.Common;
using Microsoft.SqlServer.Management.Smo;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
string sqlConnectionString = "Data Source=(local);Initial Catalog=AdventureWorks;Integrated Security=True";
FileInfo file = new FileInfo("C:\\myscript.sql");
string script = file.OpenText().ReadToEnd();
SqlConnection conn = new SqlConnection(sqlConnectionString);
Server server = new Server(new ServerConnection(conn));
server.ConnectionContext.ExecuteNonQuery(script);
}
}
}
using System.IO;
using Microsoft.SqlServer.Management.Common;
using Microsoft.SqlServer.Management.Smo;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
string sqlConnectionString = "Data Source=(local);Initial Catalog=AdventureWorks;Integrated Security=True";
FileInfo file = new FileInfo("C:\\myscript.sql");
string script = file.OpenText().ReadToEnd();
SqlConnection conn = new SqlConnection(sqlConnectionString);
Server server = new Server(new ServerConnection(conn));
server.ConnectionContext.ExecuteNonQuery(script);
}
}
}
Tuesday, March 15, 2011
.Net to Oracle Connectivity using ODBC .NET
You can use the new ODBC .NET Data Provider that works with the ODBC Oracle7.x driver or higher. You need to have MDAC 2.6 or later installed and then download ODBC .NET from the MS Web Site http://msdn.microsoft.com/downloads/default.asp?url=/code/sample.asp?url=/msdn-files/027/001/668/msdncompositedoc.xml&frame=true. MDAC (Microsoft Data Access Component) 2.7 contains core component, including the Microsoft SQL server and Oracle OLE Database provider and ODBC driver. Insta ...You can use the new ODBC .NET Data Provider that works with the ODBC Oracle7.x driver or higher. You need to have MDAC 2.6 or later installed and then download ODBC .NET from the MS Web Site http://msdn.microsoft.com/downloads/default.asp?url=/code/sample.asp?url=/msdn-files/027/001/668/msdncompositedoc.xml&frame=true. MDAC (Microsoft Data Access Component) 2.7 contains core component, including the Microsoft SQL server and Oracle OLE Database provider and ODBC driver. Install ODBC .NET from the MS Web Site http://msdn.microsoft.com/downloads/default.asp?URL=/downloads/sample.asp?url=/msdn-files/027/001/943/msdncompositedoc.xml Create a DSN, using either Microsoft ODBC for Oracle or Oracle supplied Driver if the Oracle client software is loaded. here for eq. TrailDSN. While creating DSN give user name along with passward for eq. scott/tiger.
using Microsoft
.Data.Odbc;
private void Form1_Load(object sender, System.EventArgs e)
{
try
{
OdbcConnection myconnection= new OdbcConnection ("DSN=TrialDSN");
OdbcDataAdapter myda = new OdbcDataAdapter ("Select * from EMP", myconnection);
DataSet ds= new DataSet ();
myda.Fill(ds, "Table");
dataGrid1.DataSource = ds ;
}
catch(Exception ex)
{
MessageBox.Show (ex.Message );
}
}
using Microsoft
.Data.Odbc;
private void Form1_Load(object sender, System.EventArgs e)
{
try
{
OdbcConnection myconnection= new OdbcConnection ("DSN=TrialDSN");
OdbcDataAdapter myda = new OdbcDataAdapter ("Select * from EMP", myconnection);
DataSet ds= new DataSet ();
myda.Fill(ds, "Table");
dataGrid1.DataSource = ds ;
}
catch(Exception ex)
{
MessageBox.Show (ex.Message );
}
}
Thursday, February 17, 2011
Storing Binary Data to Database using ASP.NET 2.0
http://www.beansoftware.com/ASP.NET-Tutorials/Binary-Files-To-Database.aspx
Friday, January 28, 2011
Login - check database if user exists... (c#)
I have managed to do the following...
string connectionString = "datasource=localhost;username=xxx;password=xxx;database=xxx";
MySqlConnection mySqlConnection = new MySqlConnection(connectionString);
string selectString =
"SELECT username, password " +
"FROM forum_members " +
"WHERE username = '" + frmUsername.Text + "' AND password = '" + frmPassword.Text + "'";
MySqlCommand mySqlCommand = new MySqlCommand(selectString, mySqlConnection);
mySqlConnection.Open();
String strResult = String.Empty;
strResult = (String)mySqlCommand.ExecuteScalar();
mySqlConnection.Close();
if (strResult.Length == 0)
{
Label1.Text = "INCORRECT USER/PASS!"
//could redirect to register page
} else {
Label1.Text = "YOU ARE LOGGED IN!";
//set loggin in sessions variables
}
string connectionString = "datasource=localhost;username=xxx;password=xxx;database=xxx";
MySqlConnection mySqlConnection = new MySqlConnection(connectionString);
string selectString =
"SELECT username, password " +
"FROM forum_members " +
"WHERE username = '" + frmUsername.Text + "' AND password = '" + frmPassword.Text + "'";
MySqlCommand mySqlCommand = new MySqlCommand(selectString, mySqlConnection);
mySqlConnection.Open();
String strResult = String.Empty;
strResult = (String)mySqlCommand.ExecuteScalar();
mySqlConnection.Close();
if (strResult.Length == 0)
{
Label1.Text = "INCORRECT USER/PASS!"
//could redirect to register page
} else {
Label1.Text = "YOU ARE LOGGED IN!";
//set loggin in sessions variables
}
Tuesday, January 18, 2011
Getting input from keyboard
When you type on the keyboard the keystrokes go to a particular application, the active application.
The active application receives the input from the keyboard. This means the application has input focus.
There are two events for a key on a keyboard, when the key is pressed and when it is released. No it's not a single event as you might expect if you have no prior programming experience, in shooter games for example when you keep the forward key pressed (KeyDown) the player goes forward, and when it isn't pressed (KeyUp) the player stays put.
The event that occurs when the key is pressed is called KeyPress. It occurs between KeyDown and KeyUp, and therefore acts similar to KeyDown.
Similar to the way we handle OnPaint and other events we also handle the OnKeyDown event (because we want the event to occur when the key is pressed and not when it is released) by overriding it.
Try the code below and test it. You will understand the role of each property.
protected override void OnKeyDown(KeyEventArgs keyEvent)
{
// Gets the key code
lblKeyCode.Text = "KeyCode: " + keyEvent.KeyCode.ToString();
// Gets the key data; recognizes combination of keys
lblKeyData.Text = "KeyData: " + keyEvent.KeyData.ToString();
// Integer representation of KeyData
lblKeyValue.Text = "KeyValue: " + keyEvent.KeyValue.ToString();
// Returns true if Alt is pressed
lblAlt.Text = "Alt: " + keyEvent.Alt.ToString();
// Returns true if Ctrl is pressed
lblCtrl.Text = "Ctrl: " + keyEvent.Control.ToString();
// Returns true if Shift is pressed
lblShift.Text = "Shift: " + keyEvent.Shift.ToString();
}
How do I find out when the user presses a specific key?
As you probably imagine, this will be easily accomplished using 'if'.
if (keyEvent.KeyCode == Keys.A)
{
MessageBox.Show("'A' was pressed.");
}
Probably most beginners would be tempted to do this:
if (keyEvent.KeyCode == "A")
....
which is definitely incorrect because we can't compare System.Windows.Forms.Keys to a string.
Also note that in the example we are using 'keyEvent.KeyCode', that means that even if we have other shift keys pressed (Alt, Ctrl, Shift, Windows...) simultaneous with A, the if condition returns true because it doesn't recognize key combinations.
If we want to ignore key combinations (Alt+A, Ctrl+Shift+A), etc. we need to use 'keyEvent.KeyData' of course:
if (keyEvent.KeyData == Keys.A)
{
MessageBox.Show("'A', and only A, was pressed.");
}
When you right click on a file in Windows Explorer and you have the Shift key pressed you get the additional 'Open with...' item in the menu. This and many others are cases when you need to use the mouse button together with the keyboard.
The following code will change the background color of the form only if the form is clicked while the Ctrl key on the keyboard is pressed. If the Ctrl key is unpressed and the form is clicked nothing happens.
private void Form1_Click(object sender, System.EventArgs e)
{
Keys modKey = Control.ModifierKeys;
if(modKey == Keys.Control)
{
this.BackColor = Color.Yellow;
}
}
If you have further questions feel free to ask them and also check the following pages at MSDN:
KeyUp Event
KeyPress Event
KeyDown Event
The active application receives the input from the keyboard. This means the application has input focus.
There are two events for a key on a keyboard, when the key is pressed and when it is released. No it's not a single event as you might expect if you have no prior programming experience, in shooter games for example when you keep the forward key pressed (KeyDown) the player goes forward, and when it isn't pressed (KeyUp) the player stays put.
The event that occurs when the key is pressed is called KeyPress. It occurs between KeyDown and KeyUp, and therefore acts similar to KeyDown.
Similar to the way we handle OnPaint and other events we also handle the OnKeyDown event (because we want the event to occur when the key is pressed and not when it is released) by overriding it.
Try the code below and test it. You will understand the role of each property.
protected override void OnKeyDown(KeyEventArgs keyEvent)
{
// Gets the key code
lblKeyCode.Text = "KeyCode: " + keyEvent.KeyCode.ToString();
// Gets the key data; recognizes combination of keys
lblKeyData.Text = "KeyData: " + keyEvent.KeyData.ToString();
// Integer representation of KeyData
lblKeyValue.Text = "KeyValue: " + keyEvent.KeyValue.ToString();
// Returns true if Alt is pressed
lblAlt.Text = "Alt: " + keyEvent.Alt.ToString();
// Returns true if Ctrl is pressed
lblCtrl.Text = "Ctrl: " + keyEvent.Control.ToString();
// Returns true if Shift is pressed
lblShift.Text = "Shift: " + keyEvent.Shift.ToString();
}
How do I find out when the user presses a specific key?
As you probably imagine, this will be easily accomplished using 'if'.
if (keyEvent.KeyCode == Keys.A)
{
MessageBox.Show("'A' was pressed.");
}
Probably most beginners would be tempted to do this:
if (keyEvent.KeyCode == "A")
....
which is definitely incorrect because we can't compare System.Windows.Forms.Keys to a string.
Also note that in the example we are using 'keyEvent.KeyCode', that means that even if we have other shift keys pressed (Alt, Ctrl, Shift, Windows...) simultaneous with A, the if condition returns true because it doesn't recognize key combinations.
If we want to ignore key combinations (Alt+A, Ctrl+Shift+A), etc. we need to use 'keyEvent.KeyData' of course:
if (keyEvent.KeyData == Keys.A)
{
MessageBox.Show("'A', and only A, was pressed.");
}
When you right click on a file in Windows Explorer and you have the Shift key pressed you get the additional 'Open with...' item in the menu. This and many others are cases when you need to use the mouse button together with the keyboard.
The following code will change the background color of the form only if the form is clicked while the Ctrl key on the keyboard is pressed. If the Ctrl key is unpressed and the form is clicked nothing happens.
private void Form1_Click(object sender, System.EventArgs e)
{
Keys modKey = Control.ModifierKeys;
if(modKey == Keys.Control)
{
this.BackColor = Color.Yellow;
}
}
If you have further questions feel free to ask them and also check the following pages at MSDN:
KeyUp Event
KeyPress Event
KeyDown Event
Sunday, January 9, 2011
ASP.NET C# Session Variable
You can make changes in the web.config. You can give the location path i.e the pages to whom u want to apply the security. Ex.
1) In first case the page can be accessed by everyone.
// Allow ALL users to visit the CreatingUserAccounts.aspx //
location path="CreatingUserAccounts.aspx">
system.web>
authorization>
allow users="*" />
/authorization>
/system.web>
/location>
2) in this case only admin can access the page
// Allow ADMIN users to visit the hello.aspx
location path="hello.aspx">
system.web>
authorization>
allow roles="ADMIN' />
deny users="*" />
/authorization>
/system.web>
/location>
OR
On the every page you need to check the authorization according to the page logic
ex:
On every page call this
if (session[loggeduser] !=null)
{
DataSet dsUser=(DataSet)session[loggeduser];
if (dsUser !=null && dsUser.Tables.Count>0 && dsUser.Tables[0] !=null && dsUser.Tables[0].Rows.Count>0)
{
if (dsUser.Table[0].Rows[0]["UserType"]=="SuperAdmin")
{
//your page logic here
}
if (dsUser.Table[0].Rows[0]["UserType"]=="Admin")
{
//your page logic here
}
}
}
1) In first case the page can be accessed by everyone.
// Allow ALL users to visit the CreatingUserAccounts.aspx //
location path="CreatingUserAccounts.aspx">
system.web>
authorization>
allow users="*" />
/authorization>
/system.web>
/location>
2) in this case only admin can access the page
// Allow ADMIN users to visit the hello.aspx
location path="hello.aspx">
system.web>
authorization>
allow roles="ADMIN' />
deny users="*" />
/authorization>
/system.web>
/location>
OR
On the every page you need to check the authorization according to the page logic
ex:
On every page call this
if (session[loggeduser] !=null)
{
DataSet dsUser=(DataSet)session[loggeduser];
if (dsUser !=null && dsUser.Tables.Count>0 && dsUser.Tables[0] !=null && dsUser.Tables[0].Rows.Count>0)
{
if (dsUser.Table[0].Rows[0]["UserType"]=="SuperAdmin")
{
//your page logic here
}
if (dsUser.Table[0].Rows[0]["UserType"]=="Admin")
{
//your page logic here
}
}
}
Friday, December 31, 2010
What is the difference between String and string in C#
string :
------
The string type represents a sequence of zero or more Unicode characters. string is an alias for String in the .NET Framework.
'string' is the intrinsic C# datatype, and is an alias for the system provided type "System.String". The C# specification states that as a matter of style the keyword ('string') is preferred over the full system type name (System.String, or String).
Although string is a reference type, the equality operators (== and !=) are defined to compare the values of string objects, not references. This makes testing for string equality more intuitive. For example:
String :
------
A String object is called immutable (read-only) because its value cannot be modified once it has been created. Methods that appear to modify a String object actually return a new String object that contains the modification. If it is necessary to modify the actual contents of a string-like object
Difference between string & String :
---------- ------- ------ - ------
the string is usually used for declaration while String is used for accessing static string methods
we can use 'string' do declare fields, properties etc that use the predefined type 'string', since the C# specification tells me this is good style.
we can use 'String' to use system-defined methods, such as String.Compare etc. They are originally defined on 'System.String', not 'string'. 'string' is just an alias in this case.
we can also use 'String' or 'System.Int32' when communicating with other system, especially if they are CLR-compliant. I.e. - if I get data from elsewhere, I'd deserialize it into a System.Int32 rather than an 'int', if the origin by definition was something else than a C# system.
------
The string type represents a sequence of zero or more Unicode characters. string is an alias for String in the .NET Framework.
'string' is the intrinsic C# datatype, and is an alias for the system provided type "System.String". The C# specification states that as a matter of style the keyword ('string') is preferred over the full system type name (System.String, or String).
Although string is a reference type, the equality operators (== and !=) are defined to compare the values of string objects, not references. This makes testing for string equality more intuitive. For example:
String :
------
A String object is called immutable (read-only) because its value cannot be modified once it has been created. Methods that appear to modify a String object actually return a new String object that contains the modification. If it is necessary to modify the actual contents of a string-like object
Difference between string & String :
---------- ------- ------ - ------
the string is usually used for declaration while String is used for accessing static string methods
we can use 'string' do declare fields, properties etc that use the predefined type 'string', since the C# specification tells me this is good style.
we can use 'String' to use system-defined methods, such as String.Compare etc. They are originally defined on 'System.String', not 'string'. 'string' is just an alias in this case.
we can also use 'String' or 'System.Int32' when communicating with other system, especially if they are CLR-compliant. I.e. - if I get data from elsewhere, I'd deserialize it into a System.Int32 rather than an 'int', if the origin by definition was something else than a C# system.
Wednesday, December 29, 2010
Default text disappear from textbox with javascript
//form action="http://www.domain.com" method="post">
//input type="text" size="25" value="Enter Your Default Text Here" onFocus="if(this.value == 'Enter Your Default Text Here') {this.value = '';}" //onBlur="if (this.value == '') {this.value = 'Enter Your Default Text Here';}" />
//input type=submit value=Submit>
///FORM>
//input type="text" size="25" value="Enter Your Default Text Here" onFocus="if(this.value == 'Enter Your Default Text Here') {this.value = '';}" //onBlur="if (this.value == '') {this.value = 'Enter Your Default Text Here';}" />
//input type=submit value=Submit>
///FORM>
Monday, December 27, 2010
Javascript Open a Window Full Size (Mazimized)
function f_open_window_max( aURL, aWinName )
{
var wOpen;
var sOptions;
sOptions = 'status=yes,menubar=yes,scrollbars=yes,resizable=yes,toolbar=yes';
sOptions = sOptions + ',width=' + (screen.availWidth - 10).toString();
sOptions = sOptions + ',height=' + (screen.availHeight - 122).toString();
sOptions = sOptions + ',screenX=0,screenY=0,left=0,top=0';
wOpen = window.open( '', aWinName, sOptions );
wOpen.location = aURL;
wOpen.focus();
wOpen.moveTo( 0, 0 );
wOpen.resizeTo( screen.availWidth, screen.availHeight );
return wOpen;
}
{
var wOpen;
var sOptions;
sOptions = 'status=yes,menubar=yes,scrollbars=yes,resizable=yes,toolbar=yes';
sOptions = sOptions + ',width=' + (screen.availWidth - 10).toString();
sOptions = sOptions + ',height=' + (screen.availHeight - 122).toString();
sOptions = sOptions + ',screenX=0,screenY=0,left=0,top=0';
wOpen = window.open( '', aWinName, sOptions );
wOpen.location = aURL;
wOpen.focus();
wOpen.moveTo( 0, 0 );
wOpen.resizeTo( screen.availWidth, screen.availHeight );
return wOpen;
}
Thursday, December 23, 2010
Javascript function for horizontal center align in asp.net
function SetDivPosition(tbl,hgt)
{
document.getElementById(tbl).style.height = ((document.body.clientHeight - hgt)/2) + "px";
}
//Call this function into the OnLoad() and OnResize() event of body tag.
{
document.getElementById(tbl).style.height = ((document.body.clientHeight - hgt)/2) + "px";
}
//Call this function into the OnLoad() and OnResize() event of body tag.
Wednesday, December 15, 2010
Difference between Website and Web Application in ASP.NET
Web site in Visual Studio 2005:
A web site is just a group of all files in a folder and sub folders. There is no project file. All files under the specific folder - including your word documents, text files, images etc are part of the web site.
You have to deploy all files including source files (unless you pre compile them) to the server. Files are compiled dynamically during run time.
To create a "web site", you need to use the menu File > New > Website
You will have the option to choose either one of the following location types:
# File System - Allows you to choose a folder to put all the files.
# Http - Allows you to choose a virtual directory to put the files.
# FTP - Allows you to choose an ftp location.
In any of the above cases, no project file is created automatically. Visual Studio considers all files under the folder are part of the web site.
There will be no single assembly created and you will nto see a "Bin" folder.
The benefits of this model is, you do not need a project file or virtual directory to open a project. It is very handy when you share or download code from the internet. You just need to copy the downloaded code into a folder and you are ready to go!
Web Application Project in Visual Studio 2005:
Microsoft introduced the "web site" concept where all files under a web site are part of the site, hoping that the development community is going to love that. In fact, this is very usefull to share code.
However, they did not consider millions of existing web applications where people are comfortable with the "project" based application. Also, there were lot of web applications where several un wanted files were kept under the web site folder. So, the new model did not work well for them.
When people started screaming, Microsoft came up with the answer. On April 7, 2006, they announced "Visual Studio 2005 Web Application Projects" as an Add-On to Visual Studio 2005. This Add-On will allow you to create and use web applications just like the way it used to be in Visual Studio 2003.
The Visual Studio 2005 Web Application Project model uses the same project, build and compilation method as the Visual Studio .NET 2003 web project model.
All code files within the project are compiled into a single assembly that is built and copied in the Bin directory.
All files contained within the project are defined within a project file (as well as the assembly references and other project meta-data settings). Files under the web's file-system root that are not defined in the project file are not considered part of the web project.
A web site is just a group of all files in a folder and sub folders. There is no project file. All files under the specific folder - including your word documents, text files, images etc are part of the web site.
You have to deploy all files including source files (unless you pre compile them) to the server. Files are compiled dynamically during run time.
To create a "web site", you need to use the menu File > New > Website
You will have the option to choose either one of the following location types:
# File System - Allows you to choose a folder to put all the files.
# Http - Allows you to choose a virtual directory to put the files.
# FTP - Allows you to choose an ftp location.
In any of the above cases, no project file is created automatically. Visual Studio considers all files under the folder are part of the web site.
There will be no single assembly created and you will nto see a "Bin" folder.
The benefits of this model is, you do not need a project file or virtual directory to open a project. It is very handy when you share or download code from the internet. You just need to copy the downloaded code into a folder and you are ready to go!
Web Application Project in Visual Studio 2005:
Microsoft introduced the "web site" concept where all files under a web site are part of the site, hoping that the development community is going to love that. In fact, this is very usefull to share code.
However, they did not consider millions of existing web applications where people are comfortable with the "project" based application. Also, there were lot of web applications where several un wanted files were kept under the web site folder. So, the new model did not work well for them.
When people started screaming, Microsoft came up with the answer. On April 7, 2006, they announced "Visual Studio 2005 Web Application Projects" as an Add-On to Visual Studio 2005. This Add-On will allow you to create and use web applications just like the way it used to be in Visual Studio 2003.
The Visual Studio 2005 Web Application Project model uses the same project, build and compilation method as the Visual Studio .NET 2003 web project model.
All code files within the project are compiled into a single assembly that is built and copied in the Bin directory.
All files contained within the project are defined within a project file (as well as the assembly references and other project meta-data settings). Files under the web's file-system root that are not defined in the project file are not considered part of the web project.
Saturday, November 27, 2010
Friday, November 19, 2010
How To Change The Screen Resolution in C#
All programmers are facing common problem is how to change screen Resolution dynamically. In .Net 2005 it's very easy to change the screen resolution. Here We will explain you how can we get the Screen resolution and how we will change the resolution at dynamically and while unloading the page it will come as it was before. In dot net we can access the values of user's screen resolution through the Resolution class. It also affects all running (and minimized) programs.
Page_Load Function
Screen Srn = Screen.PrimaryScreen;
tempHeight = Srn.Bounds.Width;
tempWidth = Srn.Bounds.Height;
Page.ClientScript.RegisterStartupScript
(this.GetType(), "Error", "");
//if you want Automatically Change res.at page load.
//please uncomment this code.
if (tempHeight == 600)//if the system is 800*600 Res.then change to
{
FixHeight = 768;
FixWidth = 1024;
Resolution.CResolution ChangeRes =
new Resolution.CResolution(FixHeight, FixWidth);
}
Change Resoultion in C# switch (cboRes.SelectedValue.ToString())
{
case "800*600":
FixHeight = 800;
FixWidth = 600;
Resolution.CResolution ChangeRes600 =
new Resolution.CResolution(FixHeight, FixWidth);
break;
case "1024*768":
FixHeight = 1024;
FixWidth = 768;
Resolution.CResolution ChangeRes768 =
new Resolution.CResolution(FixHeight, FixWidth);
break;
case "1280*1024":How To Change The Screen Resolution in C#
FixHeight = 1280;
FixWidth = 1024;
Resolution.CResolution ChangeRes1024 =
new Resolution.CResolution(FixHeight, FixWidth);
break;
}
Page_Load Function
Screen Srn = Screen.PrimaryScreen;
tempHeight = Srn.Bounds.Width;
tempWidth = Srn.Bounds.Height;
Page.ClientScript.RegisterStartupScript
(this.GetType(), "Error", "");
//if you want Automatically Change res.at page load.
//please uncomment this code.
if (tempHeight == 600)//if the system is 800*600 Res.then change to
{
FixHeight = 768;
FixWidth = 1024;
Resolution.CResolution ChangeRes =
new Resolution.CResolution(FixHeight, FixWidth);
}
Change Resoultion in C# switch (cboRes.SelectedValue.ToString())
{
case "800*600":
FixHeight = 800;
FixWidth = 600;
Resolution.CResolution ChangeRes600 =
new Resolution.CResolution(FixHeight, FixWidth);
break;
case "1024*768":
FixHeight = 1024;
FixWidth = 768;
Resolution.CResolution ChangeRes768 =
new Resolution.CResolution(FixHeight, FixWidth);
break;
case "1280*1024":How To Change The Screen Resolution in C#
FixHeight = 1280;
FixWidth = 1024;
Resolution.CResolution ChangeRes1024 =
new Resolution.CResolution(FixHeight, FixWidth);
break;
}
Tuesday, November 16, 2010
How to close active child form into the MDI application
Form[] charr = this.MdiChildren;
foreach (Form chform in charr)
chform.Close();
foreach (Form chform in charr)
chform.Close();
String Format for DateTime in C#
String Format for DateTime [C#]
This example shows how to format DateTime using String.Format method. All formatting can be done also using DateTime.ToString method.
Custom DateTime Formatting
There are following custom format specifiers y (year), M (month), d (day), h (hour 12), H (hour 24), m (minute), s (second), f (second fraction), F (second fraction, trailing zeroes are trimmed), t (P.M or A.M) and z (time zone).
Following examples demonstrate how are the format specifiers rewritten to the output.
[C#]
// create date time 2008-03-09 16:05:07.123
DateTime dt = new DateTime(2008, 3, 9, 16, 5, 7, 123);
String.Format("{0:y yy yyy yyyy}", dt); // "8 08 008 2008" year
String.Format("{0:M MM MMM MMMM}", dt); // "3 03 Mar March" month
String.Format("{0:d dd ddd dddd}", dt); // "9 09 Sun Sunday" day
String.Format("{0:h hh H HH}", dt); // "4 04 16 16" hour 12/24
String.Format("{0:m mm}", dt); // "5 05" minute
String.Format("{0:s ss}", dt); // "7 07" second
String.Format("{0:f ff fff ffff}", dt); // "1 12 123 1230" sec.fraction
String.Format("{0:F FF FFF FFFF}", dt); // "1 12 123 123" without zeroes
String.Format("{0:t tt}", dt); // "P PM" A.M. or P.M.
String.Format("{0:z zz zzz}", dt); // "-6 -06 -06:00" time zone
You can use also date separator / (slash) and time sepatator : (colon). These characters will be rewritten to characters defined in the current DateTimeFormatInfo.DateSeparator and DateTimeFormatInfo.TimeSeparator.
[C#]
// date separator in german culture is "." (so "/" changes to ".")
String.Format("{0:d/M/yyyy HH:mm:ss}", dt); // "9/3/2008 16:05:07" - english (en-US)
String.Format("{0:d/M/yyyy HH:mm:ss}", dt); // "9.3.2008 16:05:07" - german (de-DE)
Here are some examples of custom date and time formatting:
[C#]
// month/day numbers without/with leading zeroes
String.Format("{0:M/d/yyyy}", dt); // "3/9/2008"
String.Format("{0:MM/dd/yyyy}", dt); // "03/09/2008"
// day/month names
String.Format("{0:ddd, MMM d, yyyy}", dt); // "Sun, Mar 9, 2008"
String.Format("{0:dddd, MMMM d, yyyy}", dt); // "Sunday, March 9, 2008"
// two/four digit year
String.Format("{0:MM/dd/yy}", dt); // "03/09/08"
String.Format("{0:MM/dd/yyyy}", dt); // "03/09/2008"
Standard DateTime Formatting
In DateTimeFormatInfo there are defined standard patterns for the current culture. For example property ShortTimePattern is string that contains value h:mm tt for en-US culture and value HH:mm for de-DE culture.
Following table shows patterns defined in DateTimeFormatInfo and their values for en-US culture. First column contains format specifiers for the String.Format method.
Specifier DateTimeFormatInfo property Pattern value (for en-US culture)
t ShortTimePattern h:mm tt
d ShortDatePattern M/d/yyyy
T LongTimePattern h:mm:ss tt
D LongDatePattern dddd, MMMM dd, yyyy
f (combination of D and t) dddd, MMMM dd, yyyy h:mm tt
F FullDateTimePattern dddd, MMMM dd, yyyy h:mm:ss tt
g (combination of d and t) M/d/yyyy h:mm tt
G (combination of d and T) M/d/yyyy h:mm:ss tt
m, M MonthDayPattern MMMM dd
y, Y YearMonthPattern MMMM, yyyy
r, R RFC1123Pattern ddd, dd MMM yyyy HH':'mm':'ss 'GMT' (*)
s SortableDateTimePattern yyyy'-'MM'-'dd'T'HH':'mm':'ss (*)
u UniversalSortableDateTimePattern yyyy'-'MM'-'dd HH':'mm':'ss'Z' (*)
(*) = culture independent
Following examples show usage of standard format specifiers in String.Format method and the resulting output.
[C#]
String.Format("{0:t}", dt); // "4:05 PM" ShortTime
String.Format("{0:d}", dt); // "3/9/2008" ShortDate
String.Format("{0:T}", dt); // "4:05:07 PM" LongTime
String.Format("{0:D}", dt); // "Sunday, March 09, 2008" LongDate
String.Format("{0:f}", dt); // "Sunday, March 09, 2008 4:05 PM" LongDate+ShortTime
String.Format("{0:F}", dt); // "Sunday, March 09, 2008 4:05:07 PM" FullDateTime
String.Format("{0:g}", dt); // "3/9/2008 4:05 PM" ShortDate+ShortTime
String.Format("{0:G}", dt); // "3/9/2008 4:05:07 PM" ShortDate+LongTime
String.Format("{0:m}", dt); // "March 09" MonthDay
String.Format("{0:y}", dt); // "March, 2008" YearMonth
String.Format("{0:r}", dt); // "Sun, 09 Mar 2008 16:05:07 GMT" RFC1123
String.Format("{0:s}", dt); // "2008-03-09T16:05:07" SortableDateTime
String.Format("{0:u}", dt); // "2008-03-09 16:05:07Z" UniversalSortableDateTime
This example shows how to format DateTime using String.Format method. All formatting can be done also using DateTime.ToString method.
Custom DateTime Formatting
There are following custom format specifiers y (year), M (month), d (day), h (hour 12), H (hour 24), m (minute), s (second), f (second fraction), F (second fraction, trailing zeroes are trimmed), t (P.M or A.M) and z (time zone).
Following examples demonstrate how are the format specifiers rewritten to the output.
[C#]
// create date time 2008-03-09 16:05:07.123
DateTime dt = new DateTime(2008, 3, 9, 16, 5, 7, 123);
String.Format("{0:y yy yyy yyyy}", dt); // "8 08 008 2008" year
String.Format("{0:M MM MMM MMMM}", dt); // "3 03 Mar March" month
String.Format("{0:d dd ddd dddd}", dt); // "9 09 Sun Sunday" day
String.Format("{0:h hh H HH}", dt); // "4 04 16 16" hour 12/24
String.Format("{0:m mm}", dt); // "5 05" minute
String.Format("{0:s ss}", dt); // "7 07" second
String.Format("{0:f ff fff ffff}", dt); // "1 12 123 1230" sec.fraction
String.Format("{0:F FF FFF FFFF}", dt); // "1 12 123 123" without zeroes
String.Format("{0:t tt}", dt); // "P PM" A.M. or P.M.
String.Format("{0:z zz zzz}", dt); // "-6 -06 -06:00" time zone
You can use also date separator / (slash) and time sepatator : (colon). These characters will be rewritten to characters defined in the current DateTimeFormatInfo.DateSeparator and DateTimeFormatInfo.TimeSeparator.
[C#]
// date separator in german culture is "." (so "/" changes to ".")
String.Format("{0:d/M/yyyy HH:mm:ss}", dt); // "9/3/2008 16:05:07" - english (en-US)
String.Format("{0:d/M/yyyy HH:mm:ss}", dt); // "9.3.2008 16:05:07" - german (de-DE)
Here are some examples of custom date and time formatting:
[C#]
// month/day numbers without/with leading zeroes
String.Format("{0:M/d/yyyy}", dt); // "3/9/2008"
String.Format("{0:MM/dd/yyyy}", dt); // "03/09/2008"
// day/month names
String.Format("{0:ddd, MMM d, yyyy}", dt); // "Sun, Mar 9, 2008"
String.Format("{0:dddd, MMMM d, yyyy}", dt); // "Sunday, March 9, 2008"
// two/four digit year
String.Format("{0:MM/dd/yy}", dt); // "03/09/08"
String.Format("{0:MM/dd/yyyy}", dt); // "03/09/2008"
Standard DateTime Formatting
In DateTimeFormatInfo there are defined standard patterns for the current culture. For example property ShortTimePattern is string that contains value h:mm tt for en-US culture and value HH:mm for de-DE culture.
Following table shows patterns defined in DateTimeFormatInfo and their values for en-US culture. First column contains format specifiers for the String.Format method.
Specifier DateTimeFormatInfo property Pattern value (for en-US culture)
t ShortTimePattern h:mm tt
d ShortDatePattern M/d/yyyy
T LongTimePattern h:mm:ss tt
D LongDatePattern dddd, MMMM dd, yyyy
f (combination of D and t) dddd, MMMM dd, yyyy h:mm tt
F FullDateTimePattern dddd, MMMM dd, yyyy h:mm:ss tt
g (combination of d and t) M/d/yyyy h:mm tt
G (combination of d and T) M/d/yyyy h:mm:ss tt
m, M MonthDayPattern MMMM dd
y, Y YearMonthPattern MMMM, yyyy
r, R RFC1123Pattern ddd, dd MMM yyyy HH':'mm':'ss 'GMT' (*)
s SortableDateTimePattern yyyy'-'MM'-'dd'T'HH':'mm':'ss (*)
u UniversalSortableDateTimePattern yyyy'-'MM'-'dd HH':'mm':'ss'Z' (*)
(*) = culture independent
Following examples show usage of standard format specifiers in String.Format method and the resulting output.
[C#]
String.Format("{0:t}", dt); // "4:05 PM" ShortTime
String.Format("{0:d}", dt); // "3/9/2008" ShortDate
String.Format("{0:T}", dt); // "4:05:07 PM" LongTime
String.Format("{0:D}", dt); // "Sunday, March 09, 2008" LongDate
String.Format("{0:f}", dt); // "Sunday, March 09, 2008 4:05 PM" LongDate+ShortTime
String.Format("{0:F}", dt); // "Sunday, March 09, 2008 4:05:07 PM" FullDateTime
String.Format("{0:g}", dt); // "3/9/2008 4:05 PM" ShortDate+ShortTime
String.Format("{0:G}", dt); // "3/9/2008 4:05:07 PM" ShortDate+LongTime
String.Format("{0:m}", dt); // "March 09" MonthDay
String.Format("{0:y}", dt); // "March, 2008" YearMonth
String.Format("{0:r}", dt); // "Sun, 09 Mar 2008 16:05:07 GMT" RFC1123
String.Format("{0:s}", dt); // "2008-03-09T16:05:07" SortableDateTime
String.Format("{0:u}", dt); // "2008-03-09 16:05:07Z" UniversalSortableDateTime
Monday, November 15, 2010
Drawing a transparent button in C# winforms
public class ImageButton : ButtonBase, IButtonControl
{
public ImageButton()
{
this.SetStyle(
ControlStyles.SupportsTransparentBackColor |
ControlStyles.OptimizedDoubleBuffer |
ControlStyles.AllPaintingInWmPaint |
ControlStyles.ResizeRedraw |
ControlStyles.UserPaint, true);
this.BackColor = Color.Transparent;
}
protected override void OnPaint(PaintEventArgs pevent)
{
Graphics g = pevent.Graphics;
g.FillRectangle(Brushes.Transparent, this.ClientRectangle);
g.DrawRectangle(Pens.Black, this.ClientRectangle);
}
// rest of class here...
}
{
public ImageButton()
{
this.SetStyle(
ControlStyles.SupportsTransparentBackColor |
ControlStyles.OptimizedDoubleBuffer |
ControlStyles.AllPaintingInWmPaint |
ControlStyles.ResizeRedraw |
ControlStyles.UserPaint, true);
this.BackColor = Color.Transparent;
}
protected override void OnPaint(PaintEventArgs pevent)
{
Graphics g = pevent.Graphics;
g.FillRectangle(Brushes.Transparent, this.ClientRectangle);
g.DrawRectangle(Pens.Black, this.ClientRectangle);
}
// rest of class here...
}
Thursday, July 8, 2010
open a new browser window in Windows Forms
private void tsmGoogle_Click(object sender, EventArgs e)
{
System.Diagnostics.Process proc = new System.Diagnostics.Process();
proc.StartInfo.FileName = "iexplore";
proc.StartInfo.Arguments = "http://www.google.com/";
proc.Start();
}
{
System.Diagnostics.Process proc = new System.Diagnostics.Process();
proc.StartInfo.FileName = "iexplore";
proc.StartInfo.Arguments = "http://www.google.com/";
proc.Start();
}
Tuesday, July 6, 2010
Import and Export data from SQL Server 2005 to XL Sheet
For uploading the data from Excel Sheet to SQL Server and viceversa, we need to create a linked server in SQL Server.
Expample linked server creation:
Before you executing the below command the excel sheet should be created in the specified path and it should contain the name of the columns.
EXEC sp_addlinkedserver 'ExcelSource2',
'Jet 4.0',
'Microsoft.Jet.OLEDB.4.0',
'C:\Srinivas\Vdirectory\Testing\Marks.xls',
NULL,
'Excel 5.0'
Once you executed above query it will crate linked server in SQL Server 2005.
The following are the Query from sending the data from Excel sheet to SQL Server 2005.
INSERT INTO emp SELECT * from OPENROWSET('Microsoft.Jet.OLEDB.4.0',
'Excel 8.0;Database=C:\text.xls','SELECT * FROM [sheet1$]')
The following query is for sending the data from SQL Server 2005 to Excel Sheet.
insert into OPENROWSET('Microsoft.Jet.OLEDB.4.0',
'Excel 8.0;Database=c:\text.xls;',
'SELECT * FROM [sheet1$]') select * from emp
Expample linked server creation:
Before you executing the below command the excel sheet should be created in the specified path and it should contain the name of the columns.
EXEC sp_addlinkedserver 'ExcelSource2',
'Jet 4.0',
'Microsoft.Jet.OLEDB.4.0',
'C:\Srinivas\Vdirectory\Testing\Marks.xls',
NULL,
'Excel 5.0'
Once you executed above query it will crate linked server in SQL Server 2005.
The following are the Query from sending the data from Excel sheet to SQL Server 2005.
INSERT INTO emp SELECT * from OPENROWSET('Microsoft.Jet.OLEDB.4.0',
'Excel 8.0;Database=C:\text.xls','SELECT * FROM [sheet1$]')
The following query is for sending the data from SQL Server 2005 to Excel Sheet.
insert into OPENROWSET('Microsoft.Jet.OLEDB.4.0',
'Excel 8.0;Database=c:\text.xls;',
'SELECT * FROM [sheet1$]') select * from emp
Tuesday, June 29, 2010
ASP.NET – Function to Fill Month, Date and Year into Dropdown lists
public void fillMonthList(DropDownList ddlList)
{
ddlList.Items.Add(new ListItem("Month", "Month"));
ddlList.SelectedIndex = 0;
DateTime month = Convert.ToDateTime("1/1/2000");
for (int intLoop = 0; intLoop < 12; intLoop++)
{
DateTime NextMont = month.AddMonths(intLoop);
//ddlList.Items.Add(new ListItem(NextMont.ToString("MMMM"), NextMont.Month.ToString()));
ddlList.Items.Add(new ListItem(NextMont.ToString("MMMM"), NextMont.ToString("MMMM")));
}
}
public void fillDayList(DropDownList ddlList)
{
ddlList.Items.Add(new ListItem("Day", "Day"));
ddlList.SelectedIndex = 0;
int totalDays = DateTime.DaysInMonth(DateTime.Now.Year, DateTime.Now.Month);
for (int intLoop = 1; intLoop <= totalDays; intLoop++)
{
ddlList.Items.Add(new ListItem(intLoop.ToString(), intLoop.ToString()));
}
}
public void fillYearList(DropDownList ddlList)
{
ddlList.Items.Add(new ListItem("Year", "Year"));
ddlList.SelectedIndex = 0;
int intYearName = 1900;
for (int intLoop = intYearName; intLoop <= Convert.ToInt32(DateTime.Now.Year); intLoop++)
{
ddlList.Items.Add(new ListItem(intLoop.ToString(), intLoop.ToString()));
}
}
{
ddlList.Items.Add(new ListItem("Month", "Month"));
ddlList.SelectedIndex = 0;
DateTime month = Convert.ToDateTime("1/1/2000");
for (int intLoop = 0; intLoop < 12; intLoop++)
{
DateTime NextMont = month.AddMonths(intLoop);
//ddlList.Items.Add(new ListItem(NextMont.ToString("MMMM"), NextMont.Month.ToString()));
ddlList.Items.Add(new ListItem(NextMont.ToString("MMMM"), NextMont.ToString("MMMM")));
}
}
public void fillDayList(DropDownList ddlList)
{
ddlList.Items.Add(new ListItem("Day", "Day"));
ddlList.SelectedIndex = 0;
int totalDays = DateTime.DaysInMonth(DateTime.Now.Year, DateTime.Now.Month);
for (int intLoop = 1; intLoop <= totalDays; intLoop++)
{
ddlList.Items.Add(new ListItem(intLoop.ToString(), intLoop.ToString()));
}
}
public void fillYearList(DropDownList ddlList)
{
ddlList.Items.Add(new ListItem("Year", "Year"));
ddlList.SelectedIndex = 0;
int intYearName = 1900;
for (int intLoop = intYearName; intLoop <= Convert.ToInt32(DateTime.Now.Year); intLoop++)
{
ddlList.Items.Add(new ListItem(intLoop.ToString(), intLoop.ToString()));
}
}
Thursday, June 10, 2010
How to configure VPN in Windows XP
VPN Overview
A VPN is a private network created over a public one. It’s done with encryption, this way, your data is encapsulated and secure in transit – this creates the ‘virtual’ tunnel. A VPN is a method of connecting to a private network by a public network like the Internet. An internet connection in a company is common. An Internet connection in a Home is common too. With both of these, you could create an encrypted tunnel between them and pass traffic, safely - securely.
If you want to create a VPN connection you will have to use encryption to make sure that others cannot intercept the data in transit while traversing the Internet. Windows XP provides a certain level of security by using Point-to-Point Tunneling Protocol (PPTP) or Layer Two Tunneling Protocol (L2TP). They are both considered tunneling protocols – simply because they create that virtual tunnel just discussed, by applying encryption.
Configure a VPN with XP
If you want to configure a VPN connection from a Windows XP client computer you only need what comes with the Operating System itself, it's all built right in. To set up a connection to a VPN, do the following:
1. On the computer that is running Windows XP, confirm that the connection to the Internet is correctly configured.
• You can try to browse the internet
• Ping a known host on the Internet, like yahoo.com, something that isn’t blocking ICMP
2. Click Start, and then click Control Panel.
3. In Control Panel, double click Network Connections
4. Click Create a new connection in the Network Tasks task pad
5. In the Network Connection Wizard, click Next.
6. Click Connect to the network at my workplace, and then click Next.
7. Click Virtual Private Network connection, and then click Next.
8. If you are prompted, you need to select whether you will use a dialup connection or if you have a dedicated connection to the Internet either via Cable, DSL, T1, Satellite, etc. Click Next.
9. Type a host name, IP or any other description you would like to appear in the Network Connections area. You can change this later if you want. Click Next.
10. Type the host name or the Internet Protocol (IP) address of the computer that you want to connect to, and then click Next.
11. You may be asked if you want to use a Smart Card or not.
12. You are just about done, the rest of the screens just verify your connection, click Next.
13. Click to select the Add a shortcut to this connection to my desktop check box if you want one, if not, then leave it unchecked and click finish.
14. You are now done making your connection, but by default, it may try to connect. You can either try the connection now if you know its valid, if not, then just close it down for now.
15. In the Network Connections window, right-click the new connection and select properties. Let’s take a look at how you can customize this connection before it’s used.
16. The first tab you will see if the General Tab. This only covers the name of the connection, which you can also rename from the Network Connection dialog box by right clicking the connection and selecting to rename it. You can also configure a First connect, which means that Windows can connect the public network (like the Internet) before starting to attempt the ‘VPN’ connection. This is a perfect example as to when you would have configured the dialup connection; this would have been the first thing that you would have to do. It's simple, you have to be connected to the Internet first before you can encrypt and send data over it. This setting makes sure that this is a reality for you.
17. The next tab is the Options Tab. It is The Options tab has a lot you can configure in it. For one, you have the option to connect to a Windows Domain, if you select this check box (unchecked by default), then your VPN client will request Windows logon domain information while starting to work up the VPN connection. Also, you have options here for redialing. Redial attempts are configured here if you are using a dial up connection to get to the Internet. It is very handy to redial if the line is dropped as dropped lines are very common.
18. The next tab is the Security Tab. This is where you would configure basic security for the VPN client. This is where you would set any advanced IPSec configurations other security protocols as well as requiring encryption and credentials.
19. The next tab is the Networking Tab. This is where you can select what networking items are used by this VPN connection.
20. The Last tab is the Advanced Tab. This is where you can configure options for configuring a firewall, and/or sharing.
Connecting to Corporate
Now that you have your XP VPN client all set up and ready, the next step is to attempt a connection to the Remote Access or VPN server set up at the corporate office. To use the connection follow these simple steps. To open the client again, go back to the Network Connections dialog box.
1. One you are in the Network Connection dialog box, double-click, or right click and select ‘Connect’ from the menu – this will initiate the connection to the corporate office.
2. Type your user name and password, and then click Connect. Properties bring you back to what we just discussed in this article, all the global settings for the VPN client you are using.
3. To disconnect from a VPN connection, right-click the icon for the connection, and then click “Disconnect”
Summary
In this article we covered the basics of building a VPN connection using Windows XP. This is very handy when you have a VPN device but don’t have the ‘client’ that may come with it. If the VPN Server doesn’t use highly proprietary protocols, then you can use the XP client to connect with. In a future article I will get into the nuts and bolts of both IPSec and more detail on how to configure the advanced options in the Security tab of this client.
678: The remote computer did not respond.
930: The authentication server did not respond to authentication requests in a timely fashion.
800: Unable to establish the VPN connection.
623: The system could not find the phone book entry for this connection.
720: A connection to the remote computer could not be established.
More on : http://www.windowsecurity.com/articles/Configure-VPN-Connection-Windows-XP.html
A VPN is a private network created over a public one. It’s done with encryption, this way, your data is encapsulated and secure in transit – this creates the ‘virtual’ tunnel. A VPN is a method of connecting to a private network by a public network like the Internet. An internet connection in a company is common. An Internet connection in a Home is common too. With both of these, you could create an encrypted tunnel between them and pass traffic, safely - securely.
If you want to create a VPN connection you will have to use encryption to make sure that others cannot intercept the data in transit while traversing the Internet. Windows XP provides a certain level of security by using Point-to-Point Tunneling Protocol (PPTP) or Layer Two Tunneling Protocol (L2TP). They are both considered tunneling protocols – simply because they create that virtual tunnel just discussed, by applying encryption.
Configure a VPN with XP
If you want to configure a VPN connection from a Windows XP client computer you only need what comes with the Operating System itself, it's all built right in. To set up a connection to a VPN, do the following:
1. On the computer that is running Windows XP, confirm that the connection to the Internet is correctly configured.
• You can try to browse the internet
• Ping a known host on the Internet, like yahoo.com, something that isn’t blocking ICMP
2. Click Start, and then click Control Panel.
3. In Control Panel, double click Network Connections
4. Click Create a new connection in the Network Tasks task pad
5. In the Network Connection Wizard, click Next.
6. Click Connect to the network at my workplace, and then click Next.
7. Click Virtual Private Network connection, and then click Next.
8. If you are prompted, you need to select whether you will use a dialup connection or if you have a dedicated connection to the Internet either via Cable, DSL, T1, Satellite, etc. Click Next.
9. Type a host name, IP or any other description you would like to appear in the Network Connections area. You can change this later if you want. Click Next.
10. Type the host name or the Internet Protocol (IP) address of the computer that you want to connect to, and then click Next.
11. You may be asked if you want to use a Smart Card or not.
12. You are just about done, the rest of the screens just verify your connection, click Next.
13. Click to select the Add a shortcut to this connection to my desktop check box if you want one, if not, then leave it unchecked and click finish.
14. You are now done making your connection, but by default, it may try to connect. You can either try the connection now if you know its valid, if not, then just close it down for now.
15. In the Network Connections window, right-click the new connection and select properties. Let’s take a look at how you can customize this connection before it’s used.
16. The first tab you will see if the General Tab. This only covers the name of the connection, which you can also rename from the Network Connection dialog box by right clicking the connection and selecting to rename it. You can also configure a First connect, which means that Windows can connect the public network (like the Internet) before starting to attempt the ‘VPN’ connection. This is a perfect example as to when you would have configured the dialup connection; this would have been the first thing that you would have to do. It's simple, you have to be connected to the Internet first before you can encrypt and send data over it. This setting makes sure that this is a reality for you.
17. The next tab is the Options Tab. It is The Options tab has a lot you can configure in it. For one, you have the option to connect to a Windows Domain, if you select this check box (unchecked by default), then your VPN client will request Windows logon domain information while starting to work up the VPN connection. Also, you have options here for redialing. Redial attempts are configured here if you are using a dial up connection to get to the Internet. It is very handy to redial if the line is dropped as dropped lines are very common.
18. The next tab is the Security Tab. This is where you would configure basic security for the VPN client. This is where you would set any advanced IPSec configurations other security protocols as well as requiring encryption and credentials.
19. The next tab is the Networking Tab. This is where you can select what networking items are used by this VPN connection.
20. The Last tab is the Advanced Tab. This is where you can configure options for configuring a firewall, and/or sharing.
Connecting to Corporate
Now that you have your XP VPN client all set up and ready, the next step is to attempt a connection to the Remote Access or VPN server set up at the corporate office. To use the connection follow these simple steps. To open the client again, go back to the Network Connections dialog box.
1. One you are in the Network Connection dialog box, double-click, or right click and select ‘Connect’ from the menu – this will initiate the connection to the corporate office.
2. Type your user name and password, and then click Connect. Properties bring you back to what we just discussed in this article, all the global settings for the VPN client you are using.
3. To disconnect from a VPN connection, right-click the icon for the connection, and then click “Disconnect”
Summary
In this article we covered the basics of building a VPN connection using Windows XP. This is very handy when you have a VPN device but don’t have the ‘client’ that may come with it. If the VPN Server doesn’t use highly proprietary protocols, then you can use the XP client to connect with. In a future article I will get into the nuts and bolts of both IPSec and more detail on how to configure the advanced options in the Security tab of this client.
678: The remote computer did not respond.
930: The authentication server did not respond to authentication requests in a timely fashion.
800: Unable to establish the VPN connection.
623: The system could not find the phone book entry for this connection.
720: A connection to the remote computer could not be established.
More on : http://www.windowsecurity.com/articles/Configure-VPN-Connection-Windows-XP.html
Saturday, April 10, 2010
What is Polymorphism?
* Polymorphism is one of the primary characteristics (concept) of object-oriented programming.
* Poly means many and morph means form. Thus, polymorphism refers to being able to use many forms of a type without regard to the details.
* Polymorphism is the characteristic of being able to assign a different meaning specifically, to allow an entity such as a variable, a function, or an object to have more than one form.
* Polymorphism is the ability to process objects differently depending on their data types.
* Polymorphism is the ability to redefine methods for derived classes.
Types of Polymorphism
* Compile time Polymorphism
* Run time Polymorphism
Compile time Polymorphism
* Compile time Polymorphism also known as method overloading
* Method overloading means having two or more methods with the same name but with different signatures
Example of Compile time polymorphism
public class Calculations
{
public int add(int x, int y)
{
return x+y;
}
public int add(int x, int y, int z)
{
return x+y+z;
}
}
Run time Polymorphism
* Run time Polymorphism also known as method overriding
* Method overriding means having two or more methods with the same name , same signature but with different implementation
Example of Run time Polymorphism
class Circle
{
public int radius = 0;
public double getArea()
{
return 3.14 * radius * radius
}
}
class Sphere
{
public double getArea()
{
return 4 * 3.14 * radius * radius
}
}
* Poly means many and morph means form. Thus, polymorphism refers to being able to use many forms of a type without regard to the details.
* Polymorphism is the characteristic of being able to assign a different meaning specifically, to allow an entity such as a variable, a function, or an object to have more than one form.
* Polymorphism is the ability to process objects differently depending on their data types.
* Polymorphism is the ability to redefine methods for derived classes.
Types of Polymorphism
* Compile time Polymorphism
* Run time Polymorphism
Compile time Polymorphism
* Compile time Polymorphism also known as method overloading
* Method overloading means having two or more methods with the same name but with different signatures
Example of Compile time polymorphism
public class Calculations
{
public int add(int x, int y)
{
return x+y;
}
public int add(int x, int y, int z)
{
return x+y+z;
}
}
Run time Polymorphism
* Run time Polymorphism also known as method overriding
* Method overriding means having two or more methods with the same name , same signature but with different implementation
Example of Run time Polymorphism
class Circle
{
public int radius = 0;
public double getArea()
{
return 3.14 * radius * radius
}
}
class Sphere
{
public double getArea()
{
return 4 * 3.14 * radius * radius
}
}
Monday, March 22, 2010
How to use Java Applet into the ASP.NET page
//First download xpiinstall.exe and install into your system.
applet code="JavaFile.class" width="100%" codebase="CodePath" height="40" archive="JavaFile.jar">
param value="CodePath" name="url" />
param value="" name="dataurl" />
/applet>*/
applet code="JavaFile.class" width="100%" codebase="CodePath" height="40" archive="JavaFile.jar">
param value="CodePath" name="url" />
param value="" name="dataurl" />
/applet>*/
Friday, March 12, 2010
How to create dynamically LinkButton with Literal Control in ASP.NET
Step 1 : First take following control into the .aspx page.
asp:UpdatePanel id="up1" runat="server">
contenttemplate>
asp:Literal ID="lt1" Text="" runat="server">
asp:PlaceHolder ID="ph1" runat="server">
/asp:PlaceHolder>
/contenttemplate>
/asp:UpdatePanel>
Step 2 :
string query = query for fill the dataset;
DataSet ds = new DataSet();
ds = pass the query to retrive data;
int i = 0;
LinkButton lt = new LinkButton();
for (i = 0; i < ds.Tables[0].Rows.Count; i++)
{
lt = new LinkButton();
lt.ID = "link" + i.ToString();
lt.Text = ds.Tables[0].Rows[i].ItemArray[1].ToString();
ph1.Controls.Add(lt);
ph1.Controls.Add(new LiteralControl("
"));
}
asp:UpdatePanel id="up1" runat="server">
contenttemplate>
asp:Literal ID="lt1" Text="" runat="server">
asp:PlaceHolder ID="ph1" runat="server">
/asp:PlaceHolder>
/contenttemplate>
/asp:UpdatePanel>
Step 2 :
string query = query for fill the dataset;
DataSet ds = new DataSet();
ds = pass the query to retrive data;
int i = 0;
LinkButton lt = new LinkButton();
for (i = 0; i < ds.Tables[0].Rows.Count; i++)
{
lt = new LinkButton();
lt.ID = "link" + i.ToString();
lt.Text = ds.Tables[0].Rows[i].ItemArray[1].ToString();
ph1.Controls.Add(lt);
ph1.Controls.Add(new LiteralControl("
"));
}
Thursday, March 11, 2010
How to use Ajax : CollapsiblePanelExtender in ASP.NET
//It is simple method, Other properties will be set which you want
Step 1: Take one panel and all the content you want to collapse put into this panel.
Step 2: Set the Collapsed Property true.
Step 3: ExpandControlID/CollapseControlID : The Controls that will expand or collapse the panel on a click, respectively. If these values are the same, the panel will automatically toggle its state on each click.
Step 4: TargetControlID is PanelID
Step 5: Select Panel and Set the Property SuppressPostBack="True"
Step 1: Take one panel and all the content you want to collapse put into this panel.
Step 2: Set the Collapsed Property true.
Step 3: ExpandControlID/CollapseControlID : The Controls that will expand or collapse the panel on a click, respectively. If these values are the same, the panel will automatically toggle its state on each click.
Step 4: TargetControlID is PanelID
Step 5: Select Panel and Set the Property SuppressPostBack="True"
How to use Ajax : Hovermenu Extender in ASP.NET
// It is a simple method, Other properties set by you which you want
Step 1. Take the control that the extender is targeting.When the mouse cursor is over this control,the hover menu popup will be displayed.
Step 2. Take one panel to display when mouse is over the target control
Step 3. Set the following properties:
TargetControlID = "ID of the panel or control which display when mouse is over the target control"
PopupControlID = "ID of the control that the extender is targeting"
PopupPosition = Left (Default), Right, Top, Bottom, Center.
Step 1. Take the control that the extender is targeting.When the mouse cursor is over this control,the hover menu popup will be displayed.
Step 2. Take one panel to display when mouse is over the target control
Step 3. Set the following properties:
TargetControlID = "ID of the panel or control which display when mouse is over the target control"
PopupControlID = "ID of the control that the extender is targeting"
PopupPosition = Left (Default), Right, Top, Bottom, Center.
Wednesday, March 3, 2010
Web Application : How to upload multiple images at a time
//First add image control into the web form how many you want to upload images at a time
//Add one button
//Write the below code into the button_click event
if (FileUpload1.HasFile)
{
string imagefile = FileUpload1.FileName;
if (CheckFileType(imagefile) == true)
{
Random rndob = new Random();
int db = rndob.Next(1, 100);
filename = System.IO.Path.GetFileNameWithoutExtension(imagefile) + db.ToString() + System.IO.Path.GetExtension(imagefile);
String FilePath = "images/" + filename;
FileUpload1.SaveAs(Server.MapPath(FilePath));
objimg.ImageName = filename;
Image1();
if (Session["imagecount"].ToString() == "1")
{
Img1.ImageUrl = FilePath;
ViewState["img1"] = FilePath;
}
else if (Session["imagecount"].ToString() == "2")
{
Img1.ImageUrl = ViewState["img1"].ToString();
Img2.ImageUrl = FilePath;
ViewState["img2"] = FilePath;
}
else if (Session["imagecount"].ToString() == "3")
{
Img1.ImageUrl = ViewState["img1"].ToString();
Img2.ImageUrl = ViewState["img2"].ToString();
Img3.ImageUrl = FilePath;
ViewState["img3"] = FilePath;
}
else if (Session["imagecount"].ToString() == "4")
{
Img1.ImageUrl = ViewState["img1"].ToString();
Img2.ImageUrl = ViewState["img2"].ToString();
Img3.ImageUrl = ViewState["img3"].ToString();
Img4.ImageUrl = FilePath;
ViewState["img4"] = FilePath;
}
else if (Session["imagecount"].ToString() == "5")
{
Img1.ImageUrl = ViewState["img1"].ToString();
Img2.ImageUrl = ViewState["img2"].ToString();
Img3.ImageUrl = ViewState["img3"].ToString();
Img4.ImageUrl = ViewState["img4"].ToString();
Img5.ImageUrl = FilePath;
ViewState["img5"] = FilePath;
}
}
}
//execption handling
else
{
lblErrMsg.Visible = true;
lblErrMsg.Text = "";
lblErrMsg.Text = "please select a file";
}
}
//if file extension belongs to these list then only allowed
public bool CheckFileType(string filename)
{
string ext;
ext = System.IO.Path.GetExtension(filename);
switch (ext.ToLower())
{
case ".gif":
return true;
case ".jpeg":
return true;
case ".jpg":
return true;
case ".bmp":
return true;
case ".png":
return true;
default:
return false;
}
}
//Add one button
//Write the below code into the button_click event
if (FileUpload1.HasFile)
{
string imagefile = FileUpload1.FileName;
if (CheckFileType(imagefile) == true)
{
Random rndob = new Random();
int db = rndob.Next(1, 100);
filename = System.IO.Path.GetFileNameWithoutExtension(imagefile) + db.ToString() + System.IO.Path.GetExtension(imagefile);
String FilePath = "images/" + filename;
FileUpload1.SaveAs(Server.MapPath(FilePath));
objimg.ImageName = filename;
Image1();
if (Session["imagecount"].ToString() == "1")
{
Img1.ImageUrl = FilePath;
ViewState["img1"] = FilePath;
}
else if (Session["imagecount"].ToString() == "2")
{
Img1.ImageUrl = ViewState["img1"].ToString();
Img2.ImageUrl = FilePath;
ViewState["img2"] = FilePath;
}
else if (Session["imagecount"].ToString() == "3")
{
Img1.ImageUrl = ViewState["img1"].ToString();
Img2.ImageUrl = ViewState["img2"].ToString();
Img3.ImageUrl = FilePath;
ViewState["img3"] = FilePath;
}
else if (Session["imagecount"].ToString() == "4")
{
Img1.ImageUrl = ViewState["img1"].ToString();
Img2.ImageUrl = ViewState["img2"].ToString();
Img3.ImageUrl = ViewState["img3"].ToString();
Img4.ImageUrl = FilePath;
ViewState["img4"] = FilePath;
}
else if (Session["imagecount"].ToString() == "5")
{
Img1.ImageUrl = ViewState["img1"].ToString();
Img2.ImageUrl = ViewState["img2"].ToString();
Img3.ImageUrl = ViewState["img3"].ToString();
Img4.ImageUrl = ViewState["img4"].ToString();
Img5.ImageUrl = FilePath;
ViewState["img5"] = FilePath;
}
}
}
//execption handling
else
{
lblErrMsg.Visible = true;
lblErrMsg.Text = "";
lblErrMsg.Text = "please select a file";
}
}
//if file extension belongs to these list then only allowed
public bool CheckFileType(string filename)
{
string ext;
ext = System.IO.Path.GetExtension(filename);
switch (ext.ToLower())
{
case ".gif":
return true;
case ".jpeg":
return true;
case ".jpg":
return true;
case ".bmp":
return true;
case ".png":
return true;
default:
return false;
}
}
How to submit a form on pressing enter key
function clickButton(e, buttonid)
{
var bt = document.getElementById(buttonid);
if (typeof bt == 'object'){
if(navigator.appName.indexOf("Netscape")>(-1)){
if (e.keyCode == 13){
bt.click();
return false;
}
}
if (navigator.appName.indexOf("Microsoft Internet Explorer")>(-1))
{
if (event.keyCode == 13){
bt.click();
return false;
}
}
}
}
//Call this function on last text box of a form with onKeyPress="clickButton(this)"
{
var bt = document.getElementById(buttonid);
if (typeof bt == 'object'){
if(navigator.appName.indexOf("Netscape")>(-1)){
if (e.keyCode == 13){
bt.click();
return false;
}
}
if (navigator.appName.indexOf("Microsoft Internet Explorer")>(-1))
{
if (event.keyCode == 13){
bt.click();
return false;
}
}
}
}
//Call this function on last text box of a form with onKeyPress="clickButton(this)"
Saturday, February 20, 2010
Wednesday, February 10, 2010
How to select and deselect checkbox field into the GridView
//JavaScript function for Select and Deselect checkbox field in GridView
function SelectDeselectAll(chkAll)
{
var a = document.forms[0];
var i=0;
for(i=0;i lessthansign a.length;i++)
{
if(a[i].name.indexOf("chkItem") != -1)
{
a[i].checked = chkAll.checked;
}
}
}
function DeselectChkAll(chk)
{
var c=0;
var d=1;
var a = document.forms[0];
//alert(a.length);
if(chk.checked == false)
{
document.getElementById("chkAll").checked = chk.checked;
}
else
{
for(i=0;i lessthansign a.length;i++)
{
if(a[i].name.indexOf("chkItem") != -1)
{
if(a[i].checked==true)
{
c=1;
}
else
{
d=0;
}
}
}
if(d != 0)
{
document.getElementById("chkAll").checked =true;
}
}
}
//How to use this function
asp:TemplateField>
input id="Checkbox1" runat="server" onclick="javascript:SelectDeselectAll(this);" type="checkbox" />
/HeaderTemplate>
/asp:GridView>columns>
asp:TemplateField>headertemplate>
input id="chkAll" runat="server" onclick="javascript:SelectDeselectAll(this);" type="checkbox" />
/HeaderTemplate>
function SelectDeselectAll(chkAll)
{
var a = document.forms[0];
var i=0;
for(i=0;i lessthansign a.length;i++)
{
if(a[i].name.indexOf("chkItem") != -1)
{
a[i].checked = chkAll.checked;
}
}
}
function DeselectChkAll(chk)
{
var c=0;
var d=1;
var a = document.forms[0];
//alert(a.length);
if(chk.checked == false)
{
document.getElementById("chkAll").checked = chk.checked;
}
else
{
for(i=0;i lessthansign a.length;i++)
{
if(a[i].name.indexOf("chkItem") != -1)
{
if(a[i].checked==true)
{
c=1;
}
else
{
d=0;
}
}
}
if(d != 0)
{
document.getElementById("chkAll").checked =true;
}
}
}
//How to use this function
asp:TemplateField>
input id="Checkbox1" runat="server" onclick="javascript:SelectDeselectAll(this);" type="checkbox" />
/HeaderTemplate>
/asp:GridView>
asp:TemplateField>headertemplate>
input id="chkAll" runat="server" onclick="javascript:SelectDeselectAll(this);" type="checkbox" />
/HeaderTemplate>
How to use Ajax Validator Collout Extender
Steps:-
Step 1 : Insert any validation control with textbox
Step 2 : Insert Validator Collout Extender with validation control from the Ajax Control Toolkit
Step 3 : Set the property of the Validation control : ControlToValidate,ErrorMessage,SetFocusOnError=True,Display=none and Give the proper name to the validation control
Step 4 : Set the ValidationControlID into the Validator collout Extender Property TargetControlID
Step 1 : Insert any validation control with textbox
Step 2 : Insert Validator Collout Extender with validation control from the Ajax Control Toolkit
Step 3 : Set the property of the Validation control : ControlToValidate,ErrorMessage,SetFocusOnError=True,Display=none and Give the proper name to the validation control
Step 4 : Set the ValidationControlID into the Validator collout Extender Property TargetControlID
C# window application : How to validate mobile no.
//First : Simple Method
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
if (char.IsDigit(e.KeyChar) == true)
{
if (textBox1.Text.Length < 10) { //do nothing } else { MessageBox.Show("Max 10 chars"); e.Handled = true; } } else { e.Handled = true; } } //Second Method using System.Text.RegularExpressions; private void btnValidatePhoneNumber_Click(object sender, EventArgs e) { Regex re = new Regex("^9[0-9]{9}"); if(re.IsMatch(txtPhone.Text.Trim()) == false || txtPhone.Text.Length>10)
{
MessageBox.Show("Invalid Indian Mobile Number !!");
txtPhone.Focus();
}
}
//With the help of JavaScript
function phone_validate(phone)
{
var phoneReg = ^((\+)?(\d{2}[-]))?(\d{10}){1}?$;
if(phoneReg.test(phone) == false)
{
alert("Phone number is not yet valid.");
}
else
{
alert("You have entered a valid phone number!");
}
}
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
if (char.IsDigit(e.KeyChar) == true)
{
if (textBox1.Text.Length < 10) { //do nothing } else { MessageBox.Show("Max 10 chars"); e.Handled = true; } } else { e.Handled = true; } } //Second Method using System.Text.RegularExpressions; private void btnValidatePhoneNumber_Click(object sender, EventArgs e) { Regex re = new Regex("^9[0-9]{9}"); if(re.IsMatch(txtPhone.Text.Trim()) == false || txtPhone.Text.Length>10)
{
MessageBox.Show("Invalid Indian Mobile Number !!");
txtPhone.Focus();
}
}
//With the help of JavaScript
function phone_validate(phone)
{
var phoneReg = ^((\+)?(\d{2}[-]))?(\d{10}){1}?$;
if(phoneReg.test(phone) == false)
{
alert("Phone number is not yet valid.");
}
else
{
alert("You have entered a valid phone number!");
}
}
Tuesday, February 9, 2010
How to load Image in C# and set properties of the Picture Box
Create a C# application drag a picture Box, four buttons and open file dialog on the form.
Write code on btn_browse Button click
-----------------------------------------
private void btn_browse_Click(object sender, System.EventArgs e)
{
try
{
OpenFileDialog open = new OpenFileDialog();
open.Filter = "Image Files(*.jpg; *.jpeg; *.gif; *.bmp)|*.jpg; *.jpeg; *.gif; *.bmp";
if (open.ShowDialog()==DialogResult.OK)
{
pictureBox1.Image = new Bitmap(open.FileName);
}
}
catch (Exception)
{
throw new ApplicationException("Failed loading image");
}
}
Write code on btn_StretchImage Button click
------------------------------------------------
private void btn_StretchImage_Click(object sender, System.EventArgs e)
{
pictureBox1.SizeMode = System.Windows.Forms.PictureBoxSizeMode.StretchImage;
}
Write code on btn_AutoSize Button click
-------------------------------------------------
private void btn_AutoSize_Click(object sender, System.EventArgs e)
{
pictureBox1.SizeMode = System.Windows.Forms.PictureBoxSizeMode.AutoSize;
}
Write code on btn_CenterImage Button click
--------------------------------------------------
private void btn_CenterImage_Click(object sender, System.EventArgs e)
{
pictureBox1.SizeMode = System.Windows.Forms.PictureBoxSizeMode.CenterImage;
}
Write code on btn_browse Button click
-----------------------------------------
private void btn_browse_Click(object sender, System.EventArgs e)
{
try
{
OpenFileDialog open = new OpenFileDialog();
open.Filter = "Image Files(*.jpg; *.jpeg; *.gif; *.bmp)|*.jpg; *.jpeg; *.gif; *.bmp";
if (open.ShowDialog()==DialogResult.OK)
{
pictureBox1.Image = new Bitmap(open.FileName);
}
}
catch (Exception)
{
throw new ApplicationException("Failed loading image");
}
}
Write code on btn_StretchImage Button click
------------------------------------------------
private void btn_StretchImage_Click(object sender, System.EventArgs e)
{
pictureBox1.SizeMode = System.Windows.Forms.PictureBoxSizeMode.StretchImage;
}
Write code on btn_AutoSize Button click
-------------------------------------------------
private void btn_AutoSize_Click(object sender, System.EventArgs e)
{
pictureBox1.SizeMode = System.Windows.Forms.PictureBoxSizeMode.AutoSize;
}
Write code on btn_CenterImage Button click
--------------------------------------------------
private void btn_CenterImage_Click(object sender, System.EventArgs e)
{
pictureBox1.SizeMode = System.Windows.Forms.PictureBoxSizeMode.CenterImage;
}
Monday, February 8, 2010
Thursday, February 4, 2010
C# window application : How to pass the value from one page to another
//In Mdi Form
//Declare the variable, which you want to pass
string userid;
string password;
FormName obj = new FormName(userid,password);
obj.MdiParent = this;
obj.Show();
//In Other Form
//Declare the variable, which you want to pass
string userid;
string password;
public FormName(string uid1,string psw)
{
userid = uid1;
password = psw;
InitializeComponent();
}
//Declare the variable, which you want to pass
string userid;
string password;
FormName obj = new FormName(userid,password);
obj.MdiParent = this;
obj.Show();
//In Other Form
//Declare the variable, which you want to pass
string userid;
string password;
public FormName(string uid1,string psw)
{
userid = uid1;
password = psw;
InitializeComponent();
}
Thursday, January 28, 2010
Passing data from one database to another database table (Access) (C#)
string conString = "Provider=Microsoft.Jet.OLEDB.4.0 ;Data Source=Backup.mdb;Jet
OLEDB:Database Password=12345";
OleDbConnection dbconn = new OleDbConnection();
OleDbDataAdapter dAdapter = new OleDbDataAdapter();
OleDbCommand dbcommand = new OleDbCommand();
try
{
if (dbconn.State == ConnectionState.Closed)
dbconn.Open();
string selQuery = "INSERT INTO [Master] SELECT * FROM [MS Access;DATABASE="+
"\\Data.mdb" + ";].[Master]";
dbcommand.CommandText = selQuery;
dbcommand.CommandType = CommandType.Text;
dbcommand.Connection = dbconn;
int result = dbcommand.ExecuteNonQuery();
}
catch(Exception ex) {}
OLEDB:Database Password=12345";
OleDbConnection dbconn = new OleDbConnection();
OleDbDataAdapter dAdapter = new OleDbDataAdapter();
OleDbCommand dbcommand = new OleDbCommand();
try
{
if (dbconn.State == ConnectionState.Closed)
dbconn.Open();
string selQuery = "INSERT INTO [Master] SELECT * FROM [MS Access;DATABASE="+
"\\Data.mdb" + ";].[Master]";
dbcommand.CommandText = selQuery;
dbcommand.CommandType = CommandType.Text;
dbcommand.Connection = dbconn;
int result = dbcommand.ExecuteNonQuery();
}
catch(Exception ex) {}
How to create an Access database by using ADOX and Visual C# .NET
Build an Access Database
1. Open a new Visual C# .NET console application.
2. In Solution Explorer, right-click the References node and select Add Reference.
3. On the COM tab, select Microsoft ADO Ext. 2.7 for DDL and Security, click Select to add it to the Selected Components, and then click OK.
4. Delete all of the code from the code window for Class1.cs.
5. Paste the following code into the code window:
using System;
using ADOX;
private void btnCreate_Click(object sender, EventArgs e)
{
ADOX.CatalogClass cat = new ADOX.CatalogClass();
cat.Create("Provider=Microsoft.Jet.OLEDB.4.0;" +"Data Source=D:\\NewMDB.mdb;" +"Jet OLEDB:Engine Type=5");
MessageBox.Show("Database Created Successfully");
cat = null;
}
1. Open a new Visual C# .NET console application.
2. In Solution Explorer, right-click the References node and select Add Reference.
3. On the COM tab, select Microsoft ADO Ext. 2.7 for DDL and Security, click Select to add it to the Selected Components, and then click OK.
4. Delete all of the code from the code window for Class1.cs.
5. Paste the following code into the code window:
using System;
using ADOX;
private void btnCreate_Click(object sender, EventArgs e)
{
ADOX.CatalogClass cat = new ADOX.CatalogClass();
cat.Create("Provider=Microsoft.Jet.OLEDB.4.0;" +"Data Source=D:\\NewMDB.mdb;" +"Jet OLEDB:Engine Type=5");
MessageBox.Show("Database Created Successfully");
cat = null;
}
Wednesday, January 27, 2010
Pager Control for Repeater, DataList
http://www.codeproject.com/KB/custom-controls/CollectionPager.aspx?fid=160845&df=90&mpp=25&noise=3&sort=Position&view=Quick&fr=251
Friday, January 22, 2010
How to use Crystal Report into the ASP.NET
using CrystalDecisions.CrystalReports.Engine;
protected void Page_Load(object sender, EventArgs e)
{
ConfigureReport();
}
private void ConfigureReport()
{
ReportDocument mydoc = new ReportDocument();
string reportPath = Server.MapPath("Report.rpt");
mydoc.Load(reportPath);
CrystalReportViewer1.ReportSource = mydoc;
CrystalReportViewer1.DataBind();
}
protected void Page_Load(object sender, EventArgs e)
{
ConfigureReport();
}
private void ConfigureReport()
{
ReportDocument mydoc = new ReportDocument();
string reportPath = Server.MapPath("Report.rpt");
mydoc.Load(reportPath);
CrystalReportViewer1.ReportSource = mydoc;
CrystalReportViewer1.DataBind();
}
Disable Typing in Combobox in C# window application
//Disable Typing in Combobox in C# window application
Set the Combobox DropDownStyle property to : DropDownList
Set the Combobox DropDownStyle property to : DropDownList
How to clear all the textbox/groupbox on single click
public void ClearTextBox(Form f)
{
for (int i = 0; i < f.Controls.Count; i++)
{
if (f.Controls[i] is TextBox)
{
f.Controls[i].Text = "";
}
else if (f.Controls[i] is GroupBox)
{
for (int j = 0; j < f.Controls[i].Controls.Count; j++)
{
if (f.Controls[i].Controls[j] is TextBox)
{
f.Controls[i].Controls[j].Text = "";
}
}
}
}
}
//How to call this function(Into the Submit Button)
Make a object from the Program.cs file.
object.ClearTextBox(this);
//After submit query
{
for (int i = 0; i < f.Controls.Count; i++)
{
if (f.Controls[i] is TextBox)
{
f.Controls[i].Text = "";
}
else if (f.Controls[i] is GroupBox)
{
for (int j = 0; j < f.Controls[i].Controls.Count; j++)
{
if (f.Controls[i].Controls[j] is TextBox)
{
f.Controls[i].Controls[j].Text = "";
}
}
}
}
}
//How to call this function(Into the Submit Button)
Make a object from the Program.cs file.
object.ClearTextBox(this);
//After submit query
Monday, January 18, 2010
Window Application : C# Function for Insert,get data and fill the dropdown list
//To get data from database
string constr;
constr = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=|DataDirectory|\database.mdb";
public object getdata(string str)
{
OleDbConnection con = new OleDbConnection(constr);
con.Open();
object a;
OleDbCommand cmd = new OleDbCommand(str, con);
a = cmd.ExecuteScalar();
con.Close();
return a;
}
//To inserting data into the database
public void insertdata(string str)
{
OleDbConnection con = new OleDbConnection(constr);
con.Open();
OleDbCommand cmd = new OleDbCommand(str, con);
cmd.ExecuteNonQuery();
con.Close();
}
//To fill the dropdownlist
public void dataset(ComboBox ddl, string str)
{
OleDbConnection con = new OleDbConnection(constr);
OleDbDataAdapter dap = new OleDbDataAdapter(str, con);
con.Open();
DataSet ds = new DataSet();
dap.Fill(ds);
for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
{
if (!string.IsNullOrEmpty(ds.Tables[0].Rows[i].ItemArray[0].ToString()))
{
ddl.Items.Add(ds.Tables[0].Rows[i].ItemArray[0].ToString());
}
}
con.Close();
}
string constr;
constr = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=|DataDirectory|\database.mdb";
public object getdata(string str)
{
OleDbConnection con = new OleDbConnection(constr);
con.Open();
object a;
OleDbCommand cmd = new OleDbCommand(str, con);
a = cmd.ExecuteScalar();
con.Close();
return a;
}
//To inserting data into the database
public void insertdata(string str)
{
OleDbConnection con = new OleDbConnection(constr);
con.Open();
OleDbCommand cmd = new OleDbCommand(str, con);
cmd.ExecuteNonQuery();
con.Close();
}
//To fill the dropdownlist
public void dataset(ComboBox ddl, string str)
{
OleDbConnection con = new OleDbConnection(constr);
OleDbDataAdapter dap = new OleDbDataAdapter(str, con);
con.Open();
DataSet ds = new DataSet();
dap.Fill(ds);
for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
{
if (!string.IsNullOrEmpty(ds.Tables[0].Rows[i].ItemArray[0].ToString()))
{
ddl.Items.Add(ds.Tables[0].Rows[i].ItemArray[0].ToString());
}
}
con.Close();
}
Monday, January 4, 2010
URL validation in C# window application
private void TextBox1_Validating(object sender, CancelEventArgs e)
{
System.Text.RegularExpressions.Regex rURL = new System.Text.RegularExpressions.Regex(@"^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}" +
@"\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\" +
@".)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$");
if (txtURL.Text.Length > 0)
{
if (!rURL.IsMatch(txtEmail.Text))
{
MessageBox.Show("Please provide valid URL", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
txtURL.SelectAll();
}
}
}
{
System.Text.RegularExpressions.Regex rURL = new System.Text.RegularExpressions.Regex(@"^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}" +
@"\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\" +
@".)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$");
if (txtURL.Text.Length > 0)
{
if (!rURL.IsMatch(txtEmail.Text))
{
MessageBox.Show("Please provide valid URL", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
txtURL.SelectAll();
}
}
}
Email validation in C# window application
private void TextBox1_Validating(object sender, CancelEventArgs e)
{
System.Text.RegularExpressions.Regex rEmail = new System.Text.RegularExpressions.Regex(@"^[a-zA-Z][\w\.-]*[a-zA-Z0-9]@[a-zA-Z0-9][\w\.-]*[a-zA-Z0-9]\.[a-zA-Z][a-zA-Z\.]*[a-zA-Z]$");
if (txtEmail.Text.Length > 0)
{
if(!rEmail.IsMatch(txtEmail.Text))
{
MessageBox.Show("Please provide valid email address", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
txtEmail.SelectAll();
}
}
}
{
System.Text.RegularExpressions.Regex rEmail = new System.Text.RegularExpressions.Regex(@"^[a-zA-Z][\w\.-]*[a-zA-Z0-9]@[a-zA-Z0-9][\w\.-]*[a-zA-Z0-9]\.[a-zA-Z][a-zA-Z\.]*[a-zA-Z]$");
if (txtEmail.Text.Length > 0)
{
if(!rEmail.IsMatch(txtEmail.Text))
{
MessageBox.Show("Please provide valid email address", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
txtEmail.SelectAll();
}
}
}
Validation for textbox : C# window application
private void TextBox1_KeyPress(object sender, KeyPressEventArgs e)
{
if ((e.KeyChar >= 47 && e.KeyChar <= 58) || (e.KeyChar == 46) || (e.KeyChar == 8))
{
e.Handled = false;
}
else
{
e.Handled = true;
MessageBox.Show("Please enter only number");
}
}
{
if ((e.KeyChar >= 47 && e.KeyChar <= 58) || (e.KeyChar == 46) || (e.KeyChar == 8))
{
e.Handled = false;
}
else
{
e.Handled = true;
MessageBox.Show("Please enter only number");
}
}
Thursday, December 17, 2009
Split String
string str = ds.Tables[0].Rows[0].ItemArray[1].ToString();
string[] str1 = str.Split(new char[] { ',' });
v1 = str1[0].ToString();
v2 = str1[1].ToString();
string[] str1 = str.Split(new char[] { ',' });
v1 = str1[0].ToString();
v2 = str1[1].ToString();
Tuesday, December 15, 2009
Get the IP address in a Windows application
Using .NET 1.1 and 2.0 to retrieve the IP address
Well, in .NET 1.1 and 2.0 there are methods in the System.Net namespace that do that. Speaking of System.Net, don't forget to include the using statement, to avoid the long lines I have below:
using System.Net;
// Get the hostname
string myHost = System.Net.Dns.GetHostName();
// Show the hostname
MessageBox.Show(myHost);
// Get the IP from the host name
string myIP = System.Net.Dns.GetHostByName(myHost).AddressList[0].ToString();
// Show the IP
MessageBox.Show(myIP);
Well, in .NET 1.1 and 2.0 there are methods in the System.Net namespace that do that. Speaking of System.Net, don't forget to include the using statement, to avoid the long lines I have below:
using System.Net;
// Get the hostname
string myHost = System.Net.Dns.GetHostName();
// Show the hostname
MessageBox.Show(myHost);
// Get the IP from the host name
string myIP = System.Net.Dns.GetHostByName(myHost).AddressList[0].ToString();
// Show the IP
MessageBox.Show(myIP);
Friday, December 11, 2009
How to send an Email through Window Application with C#
private void btnSend_Click(object sender, EventArgs e)
{
string sTo = txtToEmailAddress.Text;
string sFrom = txtEmail.Text;
string sSubject = txtSubject.Text;
string sBody = txtBody.Text;
try
{
MailMessage mail = new MailMessage(sFrom, sTo, sSubject, sBody);
SmtpClient client = new SmtpClient("IP address");
client.Send(mail);
MessageBox.Show("Mail Successfully Sent");
txtSubject.Text = "";
txtEmail.Text = "";
txtBody.Text = "";
}
catch (Exception)
{
MessageBox.Show("Mail Sending Fail");
}
}
{
string sTo = txtToEmailAddress.Text;
string sFrom = txtEmail.Text;
string sSubject = txtSubject.Text;
string sBody = txtBody.Text;
try
{
MailMessage mail = new MailMessage(sFrom, sTo, sSubject, sBody);
SmtpClient client = new SmtpClient("IP address");
client.Send(mail);
MessageBox.Show("Mail Successfully Sent");
txtSubject.Text = "";
txtEmail.Text = "";
txtBody.Text = "";
}
catch (Exception)
{
MessageBox.Show("Mail Sending Fail");
}
}
Saturday, November 28, 2009
Web Application : C# Function for Insert,get data and fill the dropdown list
//To get data from database
public object getdata(string str)
{
string constr;
constr = "ConnectionString";
SqlConnection con = new SqlConnection(constr);
con.Open();
object a;
SqlCommand cmd = new SqlCommand(str,con);
a = cmd.ExecuteScalar();
con.Close();
return a;
}
//To inserting data into the database
public void insertdata(string str)
{
string constr;
constr = "ConnectionString";
SqlConnection con = new SqlConnection(constr);
con.Open();
SqlCommand cmd = new SqlCommand(str,con);
cmd.ExecuteNonQuery();
con.Close();
}
//To fill the dropdownlist
public void dataset(DropDownList ddl,string str)
{
string constr;
constr = "ConnectionString";
SqlConnection con = new SqlConnection(constr);
SqlDataAdapter dap = new SqlDataAdapter(str, con);
con.Open();
DataSet ds = new DataSet();
dap.Fill(ds);
ddl.Items.Add("Select Option");
for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
{
if(!string.IsNullOrEmpty(ds.Tables[0].Rows[i].ItemArray[0].ToString()))
{
ddl.Items.Add(ds.Tables[0].Rows[i].ItemArray[0].ToString());
}
}
con.Close();
}
public object getdata(string str)
{
string constr;
constr = "ConnectionString";
SqlConnection con = new SqlConnection(constr);
con.Open();
object a;
SqlCommand cmd = new SqlCommand(str,con);
a = cmd.ExecuteScalar();
con.Close();
return a;
}
//To inserting data into the database
public void insertdata(string str)
{
string constr;
constr = "ConnectionString";
SqlConnection con = new SqlConnection(constr);
con.Open();
SqlCommand cmd = new SqlCommand(str,con);
cmd.ExecuteNonQuery();
con.Close();
}
//To fill the dropdownlist
public void dataset(DropDownList ddl,string str)
{
string constr;
constr = "ConnectionString";
SqlConnection con = new SqlConnection(constr);
SqlDataAdapter dap = new SqlDataAdapter(str, con);
con.Open();
DataSet ds = new DataSet();
dap.Fill(ds);
ddl.Items.Add("Select Option");
for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
{
if(!string.IsNullOrEmpty(ds.Tables[0].Rows[i].ItemArray[0].ToString()))
{
ddl.Items.Add(ds.Tables[0].Rows[i].ItemArray[0].ToString());
}
}
con.Close();
}
Tuesday, November 24, 2009
free sms webservice to send sms using way2sms
http://www.aswinanand.com/sendsms.php(WEBSERVICE)
Now go through this link : http://www.aswinanand.com/2008/07/send-free-sms-web-service/
By the above web service link any one can able to send free sms through ASP.Net code via way2sms.
Implementation of webservice in our code:
Before using you should create way2sms account to use this webservice.
Method to add webreference in visual studio:
1.Right click ur project and click AddWebReference and paste the above top link in it then it will produce xml code below and click ok.
then follow/use the below code
you can write below code in Button event for trial purpose..
com.aswinanand.www.SendSMS sms = new com.aswinanand.www.SendSMS();
sms.sendSMSToMany("ur way2sms username","password","to number","message");
Please go with this url :
http://way2sms.codeplex.com/
Now go through this link : http://www.aswinanand.com/2008/07/send-free-sms-web-service/
By the above web service link any one can able to send free sms through ASP.Net code via way2sms.
Implementation of webservice in our code:
Before using you should create way2sms account to use this webservice.
Method to add webreference in visual studio:
1.Right click ur project and click AddWebReference and paste the above top link in it then it will produce xml code below and click ok.
then follow/use the below code
you can write below code in Button event for trial purpose..
com.aswinanand.www.SendSMS sms = new com.aswinanand.www.SendSMS();
sms.sendSMSToMany("ur way2sms username","password","to number","message");
Please go with this url :
http://way2sms.codeplex.com/
Thursday, September 3, 2009
.NET Remoting
Interview Questions
.NET Remoting
1. What’s a Windows process?
It’s an application that’s running and had been allocated memory.
2. What’s typical about a Windows process in regards to memory allocation?
Each process is allocated its own block of available RAM space, no process can access another process’ code or data. If the process crashes, it dies alone without taking the entire OS or a bunch of other applications down.
3. Why do you call it a process? What’s different between process and application in .NET, not common computer usage, terminology?
A process is an instance of a running application. An application is an executable on the hard drive or network. There can be numerous processes launched of the same application (5 copies of Word running), but 1 process can run just 1 application.
4. What distributed process frameworks outside .NET do you know?
Distributed Computing Environment/Remote Procedure Calls (DEC/RPC), Microsoft Distributed Component Object Model (DCOM), Common Object Request Broker Architecture (CORBA), and Java Remote Method Invocation (RMI).
5. What are possible implementations of distributed applications in .NET?
.NET Remoting and ASP.NET Web Services. If we talk about the Framework Class Library, noteworthy classes are in System.Runtime.Remoting and System.Web.Services.
6. When would you use .NET Remoting and when Web services?
Use remoting for more efficient exchange of information when you control both ends of the application. Use Web services for open-protocol-based information exchange when you are just a client or a server with the other end belonging to someone else.
7. What’s a proxy of the server object in .NET Remoting?
It’s a fake copy of the server object that resides on the client side and behaves as if it was the server. It handles the communication between real server object and the client object. This process is also known as marshaling.
8. What are remotable objects in .NET Remoting?
Remotable objects are the objects that can be marshaled across the application domains. You can marshal by value, where a deep copy of the object is created and then passed to the receiver. You can also marshal by reference, where just a reference to an existing object is passed.
9. What are channels in .NET Remoting?
Channels represent the objects that transfer the other serialized objects from one application domain to another and from one computer to another, as well as one process to another on the same box. A channel must exist before an object can be transferred.
10. What security measures exist for .NET Remoting in System.Runtime.Remoting?
None. Security should be taken care of at the application level. Cryptography and other security techniques can be applied at application or server level.
11. What is a formatter?
A formatter is an object that is responsible for encoding and serializing data into messages on one end, and deserializing and decoding messages into data on the other end.
12. Choosing between HTTP and TCP for protocols and Binary and SOAP for formatters, what are the trade-offs?
Binary over TCP is the most effiecient, SOAP over HTTP is the most interoperable.
13. What’s SingleCall activation mode used for?
f the server object is instantiated for responding to just one single request, the request should be made in SingleCall mode.
14. What’s Singleton activation mode?
A single object is instantiated regardless of the number of clients accessing it. Lifetime of this object is determined by lifetime lease.
15. How do you define the lease of the object?
By implementing ILease interface when writing the class code.
16. Can you configure a .NET Remoting object via XML file?
Yes, via machine.config and application level .config file (or web.config in ASP.NET). Application-level XML settings take precedence over machine.config.
17. How can you automatically generate interface for the remotable object in .NET with Microsoft tools?
Use the Soapsuds tool.
.NET Remoting
1. What’s a Windows process?
It’s an application that’s running and had been allocated memory.
2. What’s typical about a Windows process in regards to memory allocation?
Each process is allocated its own block of available RAM space, no process can access another process’ code or data. If the process crashes, it dies alone without taking the entire OS or a bunch of other applications down.
3. Why do you call it a process? What’s different between process and application in .NET, not common computer usage, terminology?
A process is an instance of a running application. An application is an executable on the hard drive or network. There can be numerous processes launched of the same application (5 copies of Word running), but 1 process can run just 1 application.
4. What distributed process frameworks outside .NET do you know?
Distributed Computing Environment/Remote Procedure Calls (DEC/RPC), Microsoft Distributed Component Object Model (DCOM), Common Object Request Broker Architecture (CORBA), and Java Remote Method Invocation (RMI).
5. What are possible implementations of distributed applications in .NET?
.NET Remoting and ASP.NET Web Services. If we talk about the Framework Class Library, noteworthy classes are in System.Runtime.Remoting and System.Web.Services.
6. When would you use .NET Remoting and when Web services?
Use remoting for more efficient exchange of information when you control both ends of the application. Use Web services for open-protocol-based information exchange when you are just a client or a server with the other end belonging to someone else.
7. What’s a proxy of the server object in .NET Remoting?
It’s a fake copy of the server object that resides on the client side and behaves as if it was the server. It handles the communication between real server object and the client object. This process is also known as marshaling.
8. What are remotable objects in .NET Remoting?
Remotable objects are the objects that can be marshaled across the application domains. You can marshal by value, where a deep copy of the object is created and then passed to the receiver. You can also marshal by reference, where just a reference to an existing object is passed.
9. What are channels in .NET Remoting?
Channels represent the objects that transfer the other serialized objects from one application domain to another and from one computer to another, as well as one process to another on the same box. A channel must exist before an object can be transferred.
10. What security measures exist for .NET Remoting in System.Runtime.Remoting?
None. Security should be taken care of at the application level. Cryptography and other security techniques can be applied at application or server level.
11. What is a formatter?
A formatter is an object that is responsible for encoding and serializing data into messages on one end, and deserializing and decoding messages into data on the other end.
12. Choosing between HTTP and TCP for protocols and Binary and SOAP for formatters, what are the trade-offs?
Binary over TCP is the most effiecient, SOAP over HTTP is the most interoperable.
13. What’s SingleCall activation mode used for?
f the server object is instantiated for responding to just one single request, the request should be made in SingleCall mode.
14. What’s Singleton activation mode?
A single object is instantiated regardless of the number of clients accessing it. Lifetime of this object is determined by lifetime lease.
15. How do you define the lease of the object?
By implementing ILease interface when writing the class code.
16. Can you configure a .NET Remoting object via XML file?
Yes, via machine.config and application level .config file (or web.config in ASP.NET). Application-level XML settings take precedence over machine.config.
17. How can you automatically generate interface for the remotable object in .NET with Microsoft tools?
Use the Soapsuds tool.
Tuesday, May 12, 2009
DOT NET Interview Questions
(According to latest VS.NET 2005 whidbey)
(Including SQL ServerUML,Architecture,Project
Management and General Interview Questions)
http://rapidshare.com/files/61630032/DotnetInterview.pdf
(Including SQL ServerUML,Architecture,Project
Management and General Interview Questions)
http://rapidshare.com/files/61630032/DotnetInterview.pdf
Thursday, April 16, 2009
Tuesday, April 14, 2009
How to go back to the previous page in ASP.NET 2.0 with C#
// static variable
static string prevPage = String.Empty;
protected void Page_Load(object sender, EventArgs e)
{
if( !IsPostBack )
{
prevPage = Request.UrlReferrer.ToString();
}
}
protected void Button1_Click(object sender, EventArgs e)
{
Response.Redirect(prevPage);
}
--------------------
--------------------
protected void Page_Load(object sender, EventArgs e)
{
if( !IsPostBack )
{
ViewState["RefUrl"] = Request.UrlReferrer.ToString();
}
}
protected void Button3_Click(object sender, EventArgs e)
{
object refUrl = ViewState["RefUrl"];
if (refUrl != null)
Response.Redirect((string)refUrl);
}
Wednesday, April 8, 2009
Paging With SQL Server Stored Procedures In ASP.NET
Data paging is very useful when you work with large amount of data. Instead of confusing your user with thousands or maybe even millions of records you simply show only first page with 10, 20 or 30 records and enable navigation buttons like Next or Previous if user wants to see other pages. Standard ASP.NET server controls, like GridView have built in paging capabilities in two modes: simple or custom.
Simple paging is easy to implement but it always bind complete records set which is not so scalable solution and can take a lot of network traffic and work very slow if you have large table or your web site is on shared hosting or especially if you have a lot of concurrent visitors. More about how to implement simple or custom paging in GridView and ListView you can read in Data Paging in ASP.NET tutorial.
But, which ever server control you use for data presentation, to get efficient and scalable data paging you need to do all your paging logic on SQL Server's side and SQL Server should return only selected page to ASP.NET web application. With logic like this, you get faster solution, need less memory and avoid too much traffic between SQL Server and web server. On SQL Server side, you can do paging on two main ways:
Paging stored procedure with three nested queries
I will publish next time.
Simple paging is easy to implement but it always bind complete records set which is not so scalable solution and can take a lot of network traffic and work very slow if you have large table or your web site is on shared hosting or especially if you have a lot of concurrent visitors. More about how to implement simple or custom paging in GridView and ListView you can read in Data Paging in ASP.NET tutorial.
But, which ever server control you use for data presentation, to get efficient and scalable data paging you need to do all your paging logic on SQL Server's side and SQL Server should return only selected page to ASP.NET web application. With logic like this, you get faster solution, need less memory and avoid too much traffic between SQL Server and web server. On SQL Server side, you can do paging on two main ways:
1. By building a dynamic SQL query
2. By using a stored procedure
Both methods are used widely, to find out how to build dynamic SQL queries for paging check SQL Queries For Paging In ASP.NET. In this tutorial we will see some common solution when paging is done with stored procedure.
Paging stored procedure with three nested queries
I will publish next time.
Setting the maximum length of a singleline/multiline text box
How can I set the maximum length of a singleline/multiline textbox in a webform?
Restricting the length of text on a Single line/Multi line textbox is not supported by the standard ASP.NET Web control. This can be done by adding the following Javascript function in your ASPX page.
1. Add a javascript:
At the top of your ASPX page you will see the following tag . Add the following code under this tag:
function Count(text,long)
{
var maxlength = new Number(long); // Change number to your max length.
if (text.value.length > maxlength){
text.value = text.value.substring(0,maxlength);
alert(" Only " + long + " characters");
}
}
2. Change your text controls on your ASPX page
On every multi-line text box where you would like to control the length, add the following code to the asp text box control.
onKeyUp="Count(this,300)" onChange="Count(this,300)"
Your original text control before adding this code:
<asp:TextBox ID="TESTDATA" runat="server" TextMode="MultiLine">asp:TextBox>
After adding the code:
<asp:TextBox ID="TextBox1" runat="server" onKeyUp="Count(this,300)" onChange="Count(this,300)" TextMode="MultiLine">asp:TextBox>
Restricting the length of text on a Single line/Multi line textbox is not supported by the standard ASP.NET Web control. This can be done by adding the following Javascript function in your ASPX page.
1. Add a javascript:
At the top of your ASPX page you will see the following tag . Add the following code under this tag:
function Count(text,long)
{
var maxlength = new Number(long); // Change number to your max length.
if (text.value.length > maxlength){
text.value = text.value.substring(0,maxlength);
alert(" Only " + long + " characters");
}
}
2. Change your text controls on your ASPX page
On every multi-line text box where you would like to control the length, add the following code to the asp text box control.
onKeyUp="Count(this,300)" onChange="Count(this,300)"
Your original text control before adding this code:
<asp:TextBox ID="TESTDATA" runat="server" TextMode="MultiLine">asp:TextBox>
After adding the code:
<asp:TextBox ID="TextBox1" runat="server" onKeyUp="Count(this,300)" onChange="Count(this,300)" TextMode="MultiLine">asp:TextBox>
Saturday, April 4, 2009
Regular Expressions,.NET, C# Programming
Positive decimal value regular expression with max 3 decimal places:
Regular Expressions, .NET, C# Programming Language
* Accepts all positive decimal values (currently only accepts values greater and equal to one (1))
* i.e accepts ---> 0.0001
* Can have maximum 3 decimal places.
* Decimal places are optional.
This regular expression will be used to validate currency input.
1:ValidationExpression="^\d*[1-9]\d*(\.\d+)?$"
Validate Indian Vehicle Number:
@"^[a-zA-Z]{2}[a-zA-Z0-9]{0,6}[0-9]{3}$"
http://www.cs.princeton.edu/introcs/72regular/
Regular Expressions, .NET, C# Programming Language
* Accepts all positive decimal values (currently only accepts values greater and equal to one (1))
* i.e accepts ---> 0.0001
* Can have maximum 3 decimal places.
* Decimal places are optional.
This regular expression will be used to validate currency input.
1:ValidationExpression="^\d*[1-9]\d*(\.\d+)?$"
Validate Indian Vehicle Number:
@"^[a-zA-Z]{2}[a-zA-Z0-9]{0,6}[0-9]{3}$"
http://www.cs.princeton.edu/introcs/72regular/
Subscribe to:
Posts (Atom)