Wednesday, April 10, 2013

How to create Captcha in ASP.NET

1. Create one page with name "Captcha.aspx"

2. No any control require in this page
3. Go to Captcha.aspx.vb write the below code

Protected Sub Page_Load(sender As Object, e As System.EventArgs) Handles Me.Load
        'create object of Bitmap Class and set its width and height.
        Dim objBMP As Bitmap = New Bitmap(180, 51)
        'Create Graphics object and assign bitmap object to graphics' object.
        Dim objGraphics As Graphics = Graphics.FromImage(objBMP)
        objGraphics.Clear(Color.White)
        objGraphics.TextRenderingHint = TextRenderingHint.AntiAlias
        Dim objFont As Font = New Font("arial", 30, FontStyle.Bold)
        'genetating random 6 digit random number
        Dim randomStr As String = GeneratePassword()
        'set this random number in session
        Session.Add("randomStr", randomStr)
        Session.Add("randomStrCountry", randomStr)
        objGraphics.DrawString(randomStr, objFont, Brushes.Black, 2, 2)
        Response.ContentType = "image/GIF"
        objBMP.Save(Response.OutputStream, ImageFormat.Gif)
        objFont.Dispose()
        objGraphics.Dispose()
        objBMP.Dispose()
    End Sub
    Public Function GeneratePassword() As String
        ' Below code describes how to create random numbers.some of the digits and letters
        ' are ommited because they look same like "i","o","1","0","I","O".
        Dim allowedChars As String = "a,b,c,d,e,f,g,h,j,k,m,n,p,q,r,s,t,u,v,w,x,y,z,"
        allowedChars += "A,B,C,D,E,F,G,H,J,K,L,M,N,P,Q,R,S,T,U,V,W,X,Y,Z,"
        allowedChars += "2,3,4,5,6,7,8,9"
        Dim sep() As Char = {","c}
        Dim arr() As String = allowedChars.Split(sep)
        Dim passwordString As String = ""
        Dim temp As String
        Dim rand As Random = New Random()
        Dim i As Integer
        For i = 0 To 5 - 1 Step i + 1
            temp = arr(rand.Next(0, arr.Length))
            passwordString += temp
        Next
        Return passwordString
    End Function


4. Use this page in you aspx page like this
//
 

                               
your textbox to insert code by user.

Thursday, April 4, 2013

How to delete duplicate records in sql without using temporary table

DELETE FROM table 
WHERE name IN (SELECT name FROM table GROUP BY name HAVING COUNT(*) > 1)
AND NOT id IN (SELECT min(id) FROM table GROUP BY name)

Monday, March 18, 2013

How to delete duplicate records from table in sql server


DELETE
FROM TableName
WHERE ID NOT IN
(
SELECT MAX(ID)
FROM TableName
GROUP BY ColumnName)

Wednesday, January 2, 2013

The connection was reset error in asp.net

Under system web in web.config
add this line..
system.web>
httpRuntime executionTimeout="999" maxRequestLength="2097151"/>

Saturday, March 3, 2012

Microsoft .NET Web Programming: Web Sites versus Web Applications

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

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

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);
}
}

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.

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.

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!";
}

}
}

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

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

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();
}
}

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

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?

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);