Tuesday, March 20, 2007

Return IDENTITY value

SCOPE_IDENTITY, IDENT_CURRENT, and @@IDENTITY are similar functions in that they return values inserted into IDENTITY columns.

IDENT_CURRENT is not limited by scope and session; it is limited to a specified table. IDENT_CURRENT returns the value generated for a specific table in any session and any scope.


SCOPE_IDENTITY and @@IDENTITY will return last identity values generated in any table in the current session. However, SCOPE_IDENTITY returns values inserted only within the current scope; @@IDENTITY is not limited to a specific scope.

For example, you have two tables, T1 and T2, and an INSERT trigger defined on T1. When a row is inserted to T1, the trigger fires and inserts a row in T2. This scenario illustrates two scopes: the insert on T1, and the insert on T2 as a result of the trigger.

Assuming that both T1 and T2 have IDENTITY columns, @@IDENTITY and SCOPE_IDENTITY will return different values at the end of an INSERT statement on T1.
@@IDENTITY will return the last IDENTITY column value inserted across any scope in the current session, which is the value inserted in T2.

SCOPE_IDENTITY() will return the IDENTITY value inserted in T1, which was the last INSERT that occurred in the same scope. The SCOPE_IDENTITY() function will return the NULL value if the function is invoked before any insert statements into an identity column occur in the scope.

Failed statements and transactions can alter the current identity for a table and create gaps in the identity column values. The identity value is never rolled back even though the transaction that attempted to insert the value into the table is not committed. For example, if an INSERT statement fails because of an IGNORE_DUP_KEY violation, the current identity value for the table is still incremented.

Examples:
The following example creates two tables, TZ and TY, and an INSERT trigger on TZ. When a row is inserted to table TZ, the trigger (Ztrig) fires and inserts a row in TY.

USE tempdb
GO
CREATE TABLE TZ (
Z_id int IDENTITY(1,1)PRIMARY KEY,
Z_name varchar(20) NOT NULL)

INSERT TZ
VALUES ('Lisa')
INSERT TZ
VALUES ('Mike')
INSERT TZ
VALUES ('Carla')

SELECT * FROM TZ

--Result set: This is how table TZ looks
Z_id Z_name
-------------
1 Lisa
2 Mike
3 Carla

CREATE TABLE TY (
Y_id int IDENTITY(100,5)PRIMARY KEY,
Y_name varchar(20) NULL)

INSERT TY (Y_name)
VALUES ('boathouse')
INSERT TY (Y_name)
VALUES ('rocks')
INSERT TY (Y_name)
VALUES ('elevator')

SELECT * FROM TY
--Result set: This is how TY looks:
Y_id Y_name
---------------
100 boathouse
105 rocks
110 elevator

/*Create the trigger that inserts a row in table TY
when a row is inserted in table TZ*/
CREATE TRIGGER Ztrig
ON TZ
FOR INSERT AS
BEGIN
INSERT TY VALUES ('')
END

/*FIRE the trigger and find out what identity values you get
with the @@IDENTITY and SCOPE_IDENTITY functions*/
INSERT TZ VALUES ('Rosalie')

SELECT SCOPE_IDENTITY() AS [SCOPE_IDENTITY]
GO
SELECT @@IDENTITY AS [@@IDENTITY]
GO

Setting wallpaper programmatically

private const int SPI_SETDESKWALLPAPER = 0X14;
private const int SPIF_UPDATEINIFILE = 0X1;
private const int SPIF_SENDWININICHANGE = 0X2;


[DllImport("USER32.DLL",EntryPoint="SystemParametersInfo", SetLastError = true)]
private static extern int SystemParametersInfo(int uAction, int uParam, string lpvParam, int fuWinIni);


private const string WallpaperFile = "Saibaba.bmp";
//Place this picture in MyPictures folder.

internal void SetWallpaper(Image img)
{
string imageLocation;
imageLocation = System.IO.Path.GetFullPath (System.Environment.SpecialFolder.MyPictures.ToString() + WallpaperFile);

try
{
img.Save(imageLocation, System.Drawing.Imaging.ImageFormat.Bmp);
SystemParametersInfo(SPI_SETDESKWALLPAPER, 0, imageLocation, SPIF_UPDATEINIFILE | SPIF_SENDWININICHANGE);
}

catch (Exception Ex)
{
MessageBox.Show("There was an error setting the wallpaper: " + Ex.Message);
}
}

Copy a file to ClipBoard

copy a gif file to clipboard:

ClipBoard.GetData(Bitmap, Image.LoadFile())

Select Rows in a datagridview

List selectedItems = new List(); //holds your
selected DataRowViews
private void button1_Click(object sender, EventArgs e)
{
CurrencyManager cm =
this.dataGridView1.BindingContext[dataGridView1.DataSource,
dataGridView1.DataMember] as CurrencyManager;
DataView dv = cm.List as DataView;
int i = 0;
foreach (DataRowView drv in dv)
{
if ((selectedItems.IndexOf(drv)) > -1)
{
this.dataGridView1.Rows[i].Selected = true;
}
i++;
}
}

Tuesday, March 13, 2007

Update Connection String after Deployment

Code in VB.NET:
To update the ConnectionString in "App.Config" file after deploying a windows application and code to restore database.


Imports System.Configuration
Imports System.Configuration.Install
Imports System.ComponentModel
Imports System.XML
Imports System.Data.SqlClient

Public Class UpdateConnectionString
Inherits Installer

Public Sub New()

End Sub


Public Overrides Sub install(ByVal stateSaver As System.Collections.IDictionary)

MyBase.Install(stateSaver)

Try

Dim ServerName As String = Context.Parameters("PathValue")
'This comes from Set up page (Custom Actions)

Dim ConnectionString As String

If ServerName <> "" Then

Dim AuthenticationMode, UID, PWD As String
AuthenticationMode = Context.Parameters("AuthVal")

If AuthenticationMode = "2" Then
UID = Context.Parameters("UID")
PWD = Context.Parameters("PWD")
End If


Dim AssemblyPath As String = Context.Parameters("assemblypath")
Dim appConfigPath As String = AssemblyPath + ".config"

Dim doc As XmlDocument = New XmlDocument
doc.Load(appConfigPath)

Dim configuration As XmlNode = Nothing
For Each Node As XmlNode In doc.ChildNodes
If Node.Name = "configuration" Then
configuration = Node
Exit For
End If
Next

If Not configuration Is Nothing Then
Dim settingNode As XmlNode = Nothing
For Each ASNode As XmlNode In configuration.ChildNodes
If ASNode.Name = "appSettings" Then
settingNode = ASNode
Exit For
End If
Next

If Not settingNode Is Nothing Then
Dim NumNode As XmlNode = Nothing
For Each NNode As XmlNode In settingNode.ChildNodes
If Not NNode.Attributes("key") Is Nothing Then
If NNode.Attributes("key").Value "ConnectionString" Then
NumNode = NNode
Exit For
End If
End If
Next

If Not NumNode Is Nothing Then
Dim CnAttr As XmlAttribute = NumNode.Attributes("value")

If AuthenticationMode = "2" Then
ConnectionString = "Data Source=" + ServerName + "\SQLEXPRESS;Initial Catalog=SCSAdv1;User ID=" + UID + ";pwd=" + PWD

Else

ConnectionString = "Data Source=" + ServerName + "\SQLEXPRESS;Initial Catalog=SCSAdv1;Integrated Security=True"
End If

CnAttr.Value = ConnectionString
doc.Save(appConfigPath)
End If
End If
End If

Dim cnToRestore As String

If AuthenticationMode = "2" Then
cnToRestore = "Data Source=" + ServerName + "\SQLEXPRESS;Initial Catalog=master;User ID=" + UID + ";pwd=" + PWD

Else

cnToRestore = "Data Source=" + ServerName + "\SQLEXPRESS;Initial Catalog=master;Integrated Security=True"

End If

Dim Sqlcn As New SqlConnection(cnToRestore)
Dim sqlcmd As New SqlCommand()
sqlcmd.CommandType = CommandType.Text
sqlcmd.CommandText = "RESTORE DATABASE [SCSAdv1] FROM DISK = N'" + AssemblyPath.Substring(0, AssemblyPath.IndexOf("SCSAdv1.exe")) + "\SCSAdv1.bak' WITH FILE = 1, MOVE N'SCS_Data' TO N'" + AssemblyPath.Substring(0, AssemblyPath.IndexOf("SCSAdv1.exe")) + "\SCSAdv1.mdf', MOVE N'SCS_Log' TO N'" + AssemblyPath.Substring(0, AssemblyPath.IndexOf("SCSAdv1.exe")) + "\SCSAdv1_log.ldf', NOUNLOAD, STATS = 10"

sqlcmd.Connection = Sqlcn
Try
Sqlcn.Open()
Catch sqlex As SqlException
MsgBox("We are unable to locate the SQL Server instance you have specified." + vbCrLf + "Inorder to run the 'Simulator' you need to manually restore the database after the completion of setup.", MsgBoxStyle.Critical, "")
End Try
sqlcmd.ExecuteNonQuery()
End If

Catch ex As Exception
MsgBox(ex.Message, MsgBoxStyle.Critical, "")
End Try
End Sub



Public Overrides Sub Uninstall(
ByVal stateSaver As System.Collections.IDictionary)

MyBase.Uninstall(stateSaver)
End Sub

End Class

Thursday, March 8, 2007

Microsoft Tool to uninstall programs

Have you ever wondered how to uninstall a program without using
Control Panel-> Add or Remove Programs.

There is a tool called 'Windows Installer clean up' from Microsoft .

Download the exe from Microsoft web site & uninstall the ones which are not required.

;-)

Enjoy!

Create a Dictionary class in Vb.NET

Public Class DicInteger
Inherits DictionaryBase

Default Public Property Item(ByVal Id As Integer) As Integer
 Get
Return CType(Dictionary(Id), Integer)
End Get

Set(ByVal Value As Integer)
Dictionary(Id) = Value
End Set
End Property


Public ReadOnly Property Keys() As ICollection
Get
Return Dictionary.Keys
End Get
End Property


Public ReadOnly Property Values() As ICollection
Get
Return Dictionary.Values()
End Get
End Property


Public Function Contains(ByVal Id As Integer) As Boolean
Return Dictionary.Contains(Id)
End Function


Public Sub Add(ByVal Id As Integer, ByVal IntValue As Integer)
If Dictionary.Contains(Id) Then
Dim PrevVal As Integer = Dictionary.Item(Id)
Dictionary.Remove(Id)
IntValue = PrevVal + IntValue
End If
Dictionary.Add(Id, IntValue)
End Sub

End Class

Wanna import data from MS-Excel to SQL SERVER?

Import data from Ms-Excel to SQL SERVER in windows application using VB.NET:


Step 1: Add Microsoft Excel reference to the project
(From COM Tab: Microsoft Excel 9.0/11.0 object library)

We get the reference Microsoft.office.core into our project


step 2: Create a form & in the code-behind file write the following:

Imports Microsoft.Office.Interop


Step 3: In form1.vb create Excel.Application instance
Dim obj As Excel.Application

Step 4: Let the user upload excel file containing data. In 'import' click write the following code:

obj = New Excel.Application

If File1.ShowDialog() = Windows.Forms.DialogResult.OK Then
Dim intNoofRecords As Int32
Dim dt As New DataTable
Dim dr As DataRow
dt.Columns.Add(New DataColumn("ItemName", GetType(System.String)))

Dim theWorkbook As Excel.Workbook =
obj.Workbooks.Open(File1.FileName, 0, True, 5, "", "", True, Excel.XlPlatform.xlWindows, "\t", False, False, 0, True)

Dim sheet As Excel.Sheets = theWorkbook.Worksheets

Dim worksheet As Excel.Worksheet = CType(sheet.Item(1), Excel.Worksheet)

Dim val As String

Dim R As Excel.Range

R = worksheet.Range("A2")

val = R.Cells.Value()

Dim i As Int32 = 2

While (Not val Is Nothing)
If val.Trim = "" Then
Exit While
End If

dr = dt.NewRow
dr.Item(0) = val
dt.Rows.Add(dr)

intNoofRecords = intNoofRecords + 1
i = i + 1

R = worksheet.Range("A" + i.ToString)
val = R.Cells.Value

End While


theWorkbook.Close() 'Dont forget to close the workbook. Otherwise EXCEL application remains in memory & we can see this in Task Manager.


--------------------------------------------------------------------------------------------
Now using ADO.NET data adapter object bulk insert the data into database.


Dim da As New System.Data.SqlClient.SqlDataAdapter

da.TableMappings.Add("Table", "ItemMst")

Dim MyConnection As New System.Data.SqlClient.SqlConnection(System.Configuration.ConfigurationSettings.AppSettings("ConnectionString"))

Dim MyCommand As New SqlClient.SqlCommand()
MyCommand.Connection = MyConnection
MyCommand.CommandText = "CreateItems_ForImport"
MyCommand.CommandType = CommandType.StoredProcedure

MyCommand.Parameters.Add(New System.Data.SqlClient.SqlParameter("@ItemName", SqlDbType.VarChar, 50))

MyCommand.Parameters.Item("@ItemName").SourceColumn = "ItemName"


da.InsertCommand = MyCommand

Dim intdbRecordsEffected As Int32

Try

MyConnection.Open()
intdbRecordsEffected = da.Update(dt)

If intNoofRecords <> intdbRecordsEffected Then

MsgBox("Some of the records in the excel are already existing in the database. They are not imported. ")

End If

MsgBox("Successfully imported the item(s) to database.", MsgBoxStyle.Information, "Operation complete")

Catch ex As Exception
MsgBox("Failed to Import! Please try later.", MsgBoxStyle.Critical)
Finally
MyConnection.Close()
MyCommand = Nothing
da = Nothing
End Try

Want to add 3-valued object to combo box?

Adding 3 valued object to a combo box in VB.NET

Hi,

We usually come across situations where we add two valued object to a combo box. One is used as an index (Value Member) and the other is used to display the text (Display Member).

But in rare cases we may come across 3-valued object. For ex: I want Entity Id, Entity Name, Entity type to be added to a combo box.

The following code snippet demonstrates how can we achieve this:

'First create a class containing 3 fields & properties for accessing the members.
-------------------------------------------------------------------------------------------
Public Class clsComboBoxItem2

Private m_ItemText As String 'This is for Entityname
Private m_ItemIndex As Int32 'This is for Entity Id
Private m_ItemText2 As String 'This is for Entity type


'Constructor
Public Sub New(ByVal strItemText As String, ByVal intItemIndex As Integer, ByVal strItemText2 As String)

m_ItemText = strItemText
m_ItemIndex = intItemIndex
m_ItemText2 = strItemText2End Sub

End Sub


Public ReadOnly Property ItemIndex() As String
Get
Return m_ItemIndex
End Get
End Property

Public ReadOnly Property ItemText() As String
Get
Return m_ItemText
End Get
End Property

Public ReadOnly Property ItemText2() As String
Get
Return m_ItemText2
End Get
End Property

End Class
-----------------------------------------------------------------------------

Code to add 3-valued elements to combo box:

For i = 0 To ds.Rows.Count - 1
cmbEntities.Items.Add(
New clsComboBoxItem2(ds.Rows(i).Item(0), ds.Rows(i).Item(1), ds.Rows(i).Item(2)))
Next

cmbEntities.DisplayMember = "ItemText"
cmbEntities.ValueMember = "ItemIndex"
-----------------------------------------------------------------------------
Code to retrieve selected item from combo box:

Dim itmCombo2 as clsComboBoxItem2 =
CType(cmbEntities.SelectedItem, clsComboBoxItem2)

Dim EntityId as Int32 = itmCombo2.ItemIndex
Dim EntityName as String = itmCombo2.ItemText
Dim EntityType as String = itmCombo2.ItemText2

----------------------------------------------------------------------------
Hope this is very clear.
Even though this code is in VB.NET, same logic is used for C#.NET also.



Cheers....

System.Random is not generating Random numbers (.NET code)

Hi,
I have a scenario to generate 'N' random numbers where N is given by user.
This is the code that I have written to generate random numbers
---------------------------------------------------------------------------------------
double[] a = new double[Convert.ToInt32(txtDays.Text)];
for (int i = 0; i < Convert.ToInt32(txtDays.Text); i++)
{
Random objRandom = new Random(Convert.ToInt32(System.DateTime.Now.Ticks % System.Int32.MaxValue));
a[i] = objRandom.Next(1, 100);
}
---------------------------------------------------------------------------------------
But the above code is not giving random numbers. It seems its following a particular pattern.
;-(

Check out the code below to solve the issue:
-------------------------------------------------------------------------------------------
double[] a = new double[Convert.ToInt32(txtDays.Text)];
Random objRandom = new Random(Convert.ToInt32(System.DateTime.Now.Ticks % System.Int32.MaxValue));
for (int i = 0; i < Convert.ToInt32(txtDays.Text); i++)
{
a[i] = objRandom.Next(1, 100);
}

-------------------------------------------------------------------------------------------
So did u find the difference.
Instantiate random object only once. Dont create multiple instances of System.Random class to get random numbers.

Wednesday, March 7, 2007

Copy a DLL from GAC to your own folder

Have you ever tried copying a dll from GAC to your own folder.

Today I was trying to work with BSM score cards in ASP.NET application (without using sharepoint server). I need to create a control of type 'Microsoft.PerformanceManagement.Scorecards.WebControls.ScorecardCtrl ' and I was getting an error here (Assembly reference error).

when I opened C:\windows\assembly (Location of GAC) I can see Microsoft.PerformanceManagement.Scorecards.WebControls.dll file. But there is no way to access this dll in my prj (web application). So I need to copy this dll to my working folder.

Its not possible to copy directly from c:\windows\assembly directory in GUI mode.

What we can do is go to cmd prompt
c:\cd windows
c:\windows\cd assembly
c:\windows\assembly\cd GAC
c:\windows\assembly\GAC

From assembly folder move to the folder where the required dll is present. For ex. Microsoft.PerformanceManagement.Scorecards.WebControls is present in a folder named 'Microsoft.PerformanceManagement.Scorecards.WebControls'

c:\windows\assembly\GAC\cd Microsoft.PerformanceManagement.Scorecards.WebControls
c:\winodws\assembly\GAC\Microsoft.PerformanceManagement.Scorecards.WebControls\dir *.*

now using ms-dos 'copy' command, copy the dll to your folder.
syntax: copy 'source file name' 'destination path & optional file name'


For ex: to copy system.web dll do the following:
c:\windows\assembly\GAC\system.web\copy 1.0.5000.0__b03f5f7f11d50a3a "c:\Chittydir"
(where 1.0.5000.0__b03f5f7f11d50a3a is the file name. It need not be the same everywhere. Pls check.)

Enjoy....


Reference for using BSM score cards in asp.net:
http://www.iantien.com/downloads/BSMSamples/BSM-ASP.htm

Creating HTTP Handler

Create a new class library project (I have named it as ChittyHandler)

rename the default class & paste the following code:

using System;
using System.Collections.Generic;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.SessionState;

namespace ChittyHandler
{
public class clsMyHandler : IHttpHandler,System.Web.SessionState.IRequiresSessionState
{
public bool IsReusable
{
get
{
return true;
}
}

public void ProcessRequest(System.Web.HttpContext objContext)
{
HttpResponse objResponse;
objResponse = objContext.Response;
objResponse.Write(@"This type of file is not served!");
}
}
}

(This is just an example. You may omit inheriting from (or implementing from)
IRequiresSessionState.

Build this class library. With this step you are done with creating HTTP handler
---------------------------------------------------------------------------------------------

Lets see how to consume the HTTP handler in an ASP.NET web application.
---------------------------------------------------------------------------------------------
Add the following line in web.config file:


httpHandlers
add verb="*" path="*.js,*.css" type="ChittyHandler.clsMyHandler,ChittyHandler"
httpHandlers

(namespace.classname,assemblyname)


From ASP.NET appln add a reference to the httphandler you have created just now.

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

Thats it you are done! Very simple. Isn't it!

;-)

For detailed explanation refer to : http://www.15seconds.com/issue/020417.htm

Monday, March 5, 2007

Crystal Reports in widows applications (VS 2005, CR X)

Crystal Reports in Windows application using Visual Studio 2005 and CR X:
References required:
Interop.CrystalActiveXReportViewerLib102
CrystalDecisions.CrystalReports.Engine
CrystalDecisions.Enterprise.Framework
CrystalDecisions.Enterprise.InfoStore
CrystalDecisions.ReportSource
CrystalDecisions.Shared
CrystalDecisions.Windows.Forms
------------------------------------------------------------------------------------------------
Create crdocument.rpt file. With the help of wizard we can create the graph (GUI) or text based report very easily.
------------------------------------------------------------------------------------------------
Create a form in windows applications. Drag and Drop "Crystal Report Viewer" control on to the form. (CrystalDecisions.Windows.Forms.CrystalReportViewer)

Some of the Properties of CrystalReportsVIewer we need to modify:
ShowCloseButton : True
ShowExportButton : True
ShowGotoPageButton : True
ShowGroupTreeButton : False
ShowPageNaviageButtons : True
ShowPrintButton : True
ShowRefreshButton : True
ShowTextSearchButton:True
ShowZoomButton : True
------------------------------------------------------------------------------------------------
Now bind the dataset (or datatable or any data source) to Crystalreportviewer control.
------------------------------------------------------------------------------------------------
Code in form1.vb page:
Imports CrystalDecisions.CrystalReports
Imports CrystalDecisions.Enterprise.EnterpriseService
Imports CrystalDecisions.CrystalReports.Engine
Imports CrystalDecisions.Shared
------------------------------------------------------------------------------------------------
Dim crData As New ReportDocument
crData.Load(Application.StartupPath() & "\Files\InventoryData.rpt")
///This path can be anything. This is the place where we have .rpt file. When deploying the application to client machine we should deploy .rpts also to the path mentioned here.
------------------------------------------------------------------------------------------------
crData.SetDataSource(Dataset/Datatable instance)
CrystalReportViewer1.ReportSource = crData
------------------------------------------------------------------------------------------------
If there is a parameter to .rpt file then we need to pass value from front end.
Private Sub SetCurrentValuesForParameterField(ByVal myReportDocument As ReportDocument)
Dim Parameter1Val As Object = ParameterValue
Dim parameterFields As New ParameterFields
Dim ParameterField As New ParameterField
ParameterField.ParameterFieldName = "@Parametername"

Dim ParamValue As New ParameterDiscreteValue
ParamValue.Value = Parameter1Val
ParameterField.CurrentValues.Add(ParamValue)
parameterFields.Add(ParameterField)

(This if statement is because sometimes there may not be any data binded to crystal report viewer. In that case it throws 'object reference not set to an instance' type of error.)
If Not CrystalReportViewer1.ParameterFieldInfo Is Nothing Then
CrystalReportViewer1.ParameterFieldInfo = parameterFields
End If

----------------------------------------------------------
To Change the colors of crystal report viewer:
  • *Very important piece of code

Private Sub FormatReportViewer()
Dim thisObj As Object
Dim MyPageView As CrystalDecisions.Windows.Forms.PageView
Dim tcontrol As Windows.Forms.TabControl

For Each thisObj In CrystalReportViewer1.Controls
'yes, of course the names are case sensitive!
'(they are StatusBar and PageView and none other!)
Select Case UCase(thisObj.GetType.Name)
Case "STATUSBAR"
CType(thisObj, StatusBar).Visible = False 'This hides the status bar
Case "PAGEVIEW"
MyPageView = CType(thisObj, CrystalDecisions.Windows.Forms.PageView)
If MyPageView.Controls.Count > 0 Then
tcontrol = CType(MyPageView.Controls(0), TabControl)
With tcontrol
'*****************************************
'these three lines together effectively make tab invisible.
'comment out if you want to show the tab's text.
.ItemSize = New Size(0, 1)
.SizeMode = TabSizeMode.Fixed
.Appearance = TabAppearance.Buttons
'*****************************************
'the crystalreportviewer must be totally drawn before you
'have a tabpage. So you have to call formatreportviewer
'after it has been drawn for the following to work.
If .TabPages.Count > 0 Then
'set color, this is good even if you have chosen
'to make the the tab invisible, does the border.
'the other properties are useless if invisible!
With .TabPages(0)
.BackColor = Color.FromArgb(216, 228, 248)
.Text = "TABTEXT"
End With
End If
End With
End If
End Select
Next

End Sub

To set window size using Javascript

: A pretty blinking red image

to resize window:

window.resizeTo(document.body.offsetWidth ,600)


'div' has to be in a td
To hide a 'div'
document.getElementById('div1').style.display = "none";

To display a 'div'
document.getElementById('div1').style.display = "none";

To assign image dynamically:
var imgname = "expand.gif";
document.getElementById(srcArrow).src = imgname;

To open a pop-up window:

window.open(winname,'Title','left=20,top=20,width=550,height=400,toolbar=0,resizable=0,status=0');

to move to another page:

input id="'Id'" onclick="javascript:window.location='PageName.htm'" type="button" value="Next page"

to move to another page w/o browser caching page name:

location.replace('pagename') //works with browsers above Netscape 4.0 & above &amp; IE 5 & above. Not compatible with earlier versions of browsers.


To move to another secion in the same HTML page:

a href="#1"

somewhere in the HTML we should have .....

tr with id '1'

background color of td to use as a line separator #dcc99d

td bgcolor="#dcc99d" height=1

Some images we can use in left menu: (expandable)

a bullet image: (I like this so much)

: Open dir
: Close dir

: Check Box Checked Image

Mappoint web service

Today we were trying to use map point web service in asp.net using Visual Studio.NET 2003.

Its failed with the error message 401 unauthorized access.

The same web service we have tried from Windows application using Visual Studio .NET 2003. Now this was working fine.

So we have tried google web service & some other third party web services to find out whether they work in ASP.NET web applications. All web services were throwing the same exception.

Atlast we have tried in Visual Studio.NET 2005 (on the same machine). To our astonishment, it worked well without any exception.

;-)

I need to understand why it is happening this like.

Friday, March 2, 2007

ATLAS



Using Script Manager and Update Panel



In this sample application, Default.aspx presents a web form for a bug-tracking web site where users can view a list of bugs displayed in a paged GridView control. Users can also enter a tester's name in the Reported By text box and click the Search button to display only those bugs reported by the tester.


Currently, every time the user clicks the Search button or moves to another page of the GridView control, a full page postback occurs and the entire page is rendered after each request. Once complete, however, the application must refresh only the GridView control when the user clicks the Search button or navigates to another page of the GridView control.


To achieve this, you are required to add a ScriptManager control that enables partial page rendering. You must place the GridView control and one of the Label controls in a new UpdatePanel control, and ensure that the application refreshes only this UpdatePanel control when the Click event of the Search button fires or the user moves to another page of the GridView control.


To complete this task:
Modify the WebSite project to ensure the following:
The WebSite project references the System.Web.Extensions.dll that comes with the Microsoft ASP.NET AJAX Extensions.

The following are the references:

ASP.NET Page object Model

When a page request is sent to the Web server, whether through a submission or location change, the page is run through a series of events during its creation and disposal. When we try to build ASP.NET pages and this execution cycle is not taken into account, we can cause a lot of headaches for ourselves. However, when used and manipulated correctly, a page's execution cycle can be an effective and powerful tool. Many developers are realizing that understanding what happens and when it happens is crucial to effectively writing ASP.NET pages or user controls. So let's examine in detail the ten events of an ASP.NET page, from creation to disposal. We will also see how to tap into these events to implant our own custom code.

I'll set the stage with a simple submission form written in ASP.NET with C#. The page is loaded for the first time and has several server-side Web controls on it. When the Web server receives a request for the page, it will process our Web controls and we will eventually get rendered HTML. The first step in processing our page is object initialization.

1. Object Initialization


A page's controls (and the page itself) are first initialized in their raw form. By declaring your objects within the constructor of your C# code-behind file (see Figure 1), the page knows what types of objects and how many to create. Once you have declared your objects within your constructor, you may then access them from any sub class, method, event, or property. However, if any of your objects are controls specified within your ASPX file, at this point the controls have no attributes or properties. It is dangerous to access them through code, as there is no guarantee of what order the control instances will be created (if they are created at all). The initialization event can be overridden using the OnInit method.


2. Load Viewstate Data


After the Init event, controls can be referenced using their IDs only (no DOM is established yet for relative references). At LoadViewState event, the initialized controls receive their first properties: viewstate information that was persisted back to the server on the last submission. The page viewstate is managed by ASP.NET and is used to persist information over a page roundtrip to the server. Viewstate information is saved as a string of name/value pairs and contains information such as control text or value. The viewstate is held in the value property of a hidden control that is passed from page request to page request. As you can see, this is a giant leap forward from the old ASP 3.0 techniques of maintaining state. This event can be overridden using the LoadViewState method and is commonly used to customize the data received by the control at the time it is populated. Figure 2 shows an example of overriding and setting viewstate at the LoadViewState event.



3. LoadPostData Processes Postback Data


During this phase of the page creation, form data that was posted to the server (termed postback data in ASP.NET) is processed against each control that requires it. When a page submits a form, the framework will implement the IPostBackDataHandler interface on each control that submitted data. The page then fires the LoadPostData event and parses through the page to find each control that implements this interface and updates the control state with the correct postback data. ASP.NET updates the correct control by matching the control's unique ID with the name/value pair in the NameValueCollection. This is one reason that ASP.NET requires unique IDs for each control on any given page. Extra steps are taken by the framework to ensure each ID is unique in situations, such as several custom user controls existing on a single page. After the LoadPostData event triggers, the RaisePostDataChanged event is free to execute


4. Object Load


Objects take true form during the Load event. All object are first arranged in the page DOM (called the Control Tree in ASP.NET) and can be referenced easily through code or relative position (crawling the DOM). Objects are then free to retrieve the client-side properties set in the HTML, such as width, value, or visibility. During Load, coded logic, such as arithmetic, setting control properties programmatically, and using the StringBuilder to assemble a string for output, is also executed. This stage is where the majority of work happens. The Load event can be overridden by calling OnLoad


5. Raise PostBack Change Events


As stated earlier, this occurs after all controls that implement the IPostBackDataHandler interface have been updated with the correct postback data. During this operation, each control is flagged with a Boolean on whether its data was actually changed or remains the same since the previous submit. ASP.NET then sweeps through the page looking for flags indicating that any object's data has been updated and fires RaisePostDataChanged. The RaisePostDataChanged event does not fire until all controls are updated and after the Load event has occurred. This ensures data in another control is not manually altered during the RaisePostDataChanged event before it is updated with postback data.


6. Process Client-Side PostBack Event


After the server-side events fire on data that was changed due to postback updates, the object which caused the postback is handled at the RaisePostBackEvent event. The offending object is usually a control that posted the page back to the server due to a state change (with autopostback enabled) or a form submit button that was clicked. There is often code that will execute in this event, as this is an ideal location to handle event-driven logic. The RaisePostBackEvent event fires last in the series of postback events due to the accuracy of the data that is rendered to the browser.

Controls that are changed during postback should not be updated after the executing function is called due to the consistency factor. That is, data that is changed by an anticipated event should always be reflected in the resulting page. The RaisePostBackEvent can be trapped by catching RaisePostBackEvent


7. Prerender the Objects


The point at which the objects are prerendered is the last time changes to the objects can be saved or persisted to viewstate. This makes the PreRender step a good place to make final modifications, such as changing properties of controls or changing Control Tree structure, without having to worry about ASP.NET making changes to objects based off of database calls or viewstate updates. After the PreRender phase those changes to objects are locked in and can no longer be saved to the page viewstate. The PreRender step can be overridden using OnPreRender


8. ViewState Saved


The viewstate is saved after all changes to the page objects have occurred. Object state data is persisted in the hidden object and this is also where object state data is prepared to be rendered to HTML. At the SaveViewState event, values can be saved to the ViewState object, but changes to page controls are not. You can override this step by using SaveViewState


9. Render To HTML


The Render event commences the building of the page by assembling the HTML for output to the browser. During the Render event, the page calls on the objects to render themselves into HTML. The page then collects the HTML for delivery. When the Render event is overridden, the developer can write custom HTML to the browser that nullifies all the HTML the page has created thus far. The Render method takes an HtmlTextWriter object as a parameter and uses that to output HTML to be streamed to the browser. Changes can still be made at this point, but they are reflected to the client only. The Render event can be overridden



10. Disposal


After the page's HTML is rendered, the objects are disposed of. During the Dispose event, you should destroy any objects or references you have created in building the page. At this point, all processing has occurred and it is safe to dispose of any remaining objects, including the Page object. You can override Dispose

What happens when an ASP.NET page is requested

Step 0: The Browser Makes an HTTP Request for an ASP.NET Web Page
The entire process begins with a Web browser making a request for an ASP.NET Web page.
For example, a user might type into their browser's Address window the URL for this article, http://dotnetmonk.blogspot.com.

The Web browser, then, would make an HTTP request to the blogger Web server, asking for the particular file.

Step 1:
The Web Server Receives the HTTP RequestThe sole task of a Web server is to accept incoming HTTP requests and to return the requested resource in an HTTP response.
Let us assume the Web server runs Microsoft's Internet Information Services (IIS) Web server. The first things IIS does when a request comes in is decide how to handle the request.
Its decision is based upon the requested file's extension.
For example, if the requested file has the .asp extension, IIS will route the request to be handled by asp.dll.

There are numerous file extensions that map to the ASP.NET engine, some of which include:
.aspx, for ASP.NET Web pages,
.asmx, for ASP.NET Web services,
.config, for ASP.NET configuration files,
.ashx, for custom ASP.NET HTTP handlers,
.rem, for remoting resources, And others!



In the IIS administration screens, you can configure the extension mappings. The screenshot to the right shows the configuration screen for IIS 5.0. You could, for example, add your own custom extensions here. That is, you could have requests for .scott files routed to the ASP.NET engine.



The diagram below illustrates the steps 0 and 1 of a request for an ASP.NET Web page. When a request comes into the Web server, it is routed to the proper place (perhaps asp.dll for classic ASP page requests, perhaps the ASP.NET engine for ASP.NET requests) based on the requested file's extension.



















Step 2: Examining the ASP.NET EngineAn initial request for http://dotnetmonk.blogspot.com will reach IIS and then be routed to the ASP.NET engine, but what happens next? The ASP.NET engine is often referred to as the ASP.NET HTTP pipeline, because the incoming request passes through a variable number of HTTP modules on its way to an HTTP handler.
HTTP modules are classes that have access to the incoming request.

These modules can inspect the incoming request and make decisions that affect the internal flow of the request. After passing through the specified HTTP modules, the request reaches an HTTP handler, whose job it is to generate the output that will be sent back to the requesting browser. The following diagram illustrates the pipeline an ASP.NET request flows through.








There are a number of pre-built HTTP modules that are included in the HTTP pipeline by default. These modules include:


  • OutputCache, which handles returning and caching the page's HTML output, if needed

  • Session, which loads in the session state based on the user's incoming request and the session method specified in the Web.config file

  • FormsAuthentication, which attempts to authenticate the user based on the forms authentication scheme, if used

  • And others!

In fact, you can see a precise list of what modules are used by default by going to the machine.config file (located in the $WINDOWS$\Microsoft.NET\Framework\$VERSION$\CONFIG directory) and searching for the element. The following shows the default element:

HTTP handlers are the endpoints in the ASP.NET HTTP pipeline. The job of the HTTP handler is to generate the output for the requested resource. For ASP.NET Web pages, this means rendering the Web controls into HTML and returning this HTML. For a Web service, it would involve executing the specified method and wrapping its return values into an appropriately formatted SOAP response. (For more on Web services, be sure to read: An Extensive Examination of Web Services.)

Different ASP.NET resources use different HTTP handlers. The handlers used by default are spelled out in the machine.config's section. Entries in this section refer to classes that are either HTTP handlers themselves or are HTTP handler factories. An HTTP handler factory merely returns a suitable HTTP handler instance when invoked.

The following shows a snippet of the element in the default machine.config file:

...

Realize that you can create your own HTTP modules and HTTP handlers, and then plug them into the pipeline for all Web sites on the Web server by modifying machine.config, or you can add them to a particular Web application by modifying that application's Web.config file. A thorough discussion on using HTTP modules and handlers is far beyond the scope of this article, but realize that you can accomplish some neat things using modules and handlers. For example, you can use HTTP modules to provide a custom URL rewritter, which can be useful for automatically fixing 404 errors to using shorter and user-friendlier URLs. (See Rewrite.NET - A URL Rewriting Engine for .NET for an example of using HTTP modules for URL rewriting.) Another cool use of modules is compressing the generated HTML.

For a good discussion on HTTP modules and handlers be sure to read Mansoor Ahmed Siddiqui's article: HTTP Handlers and HTTP Modules in ASP.NET.

Step 3: Generating the OutputThe final step is for the suitable HTTP handler to generate the appropriate output. This output, then, is passed back through the HTTP modules and then back to IIS, which then sends it back to the client that initiated the request. (If the client was a Web browser, the Web browser would receive this HTML and display it.)

Since the steps for generating the output differ by HTTP handler, let's focus in on one in particular - the HTTP handler that is used to render ASP.NET Web pages. To retrace the initial steps, when a request comes into IIS for an ASP.NET page (i.e., one with a .aspx extension), the request is handed off to the ASP.NET engine. The request then moves through the modules. The request is then routed to the PageHandlerFactory, since in the machine.config's section we have the mapping:

...

...

The PageHandlerFactory class is an HTTP handler factory. It's job is to provide an instance of an HTTP handler that can handle the request. What PageHandlerFactory does is find the compiled class that represents the ASP.NET Web page that is being requested.

If you use Visual Studio .NET to create your ASP.NET Web pages you know that the Web pages are composed of two separate files: a .aspx file, which contains just the HTML markup and Web controls, and a .aspx.vb or .aspx.cs file that contains the code-behind class (which contains the server-side code). If you don't use Visual Studio .NET, you likely use a server-side
"script" block to hold the server-side code. Regardless of what approach you use, when the ASP.NET Web page is first visited after a change to the HTML or Web control content, the ASP.NET engine creates a class that derives from the System.Web.UI.Page class. This dynamically created class is then compiled.

Not coincidentally, the Page class implements IHttpHandler, thereby indicating that it suffices as an HTTP handler. What the PageHandlerFactory does, then, is check to see if a compiled version of the requested ASP.NET Web page's class exists. If not, it dynamically creates this class and compiles it. This class, then, has a particular method invoked which generates the page's complete HTML markup. It's this HTML markup that is then returned to the client. (Have you noticed that when visiting an ASP.NET Web page after making changes to the HTML or Web control content, there is a bit of a delay? This delay is due to the ASP.NET engine needing to recreate and recompile the ASP.NET page's corresponding class.)



courtesy : http://aspnet.4guysfromrolla.com/articles/011404-1.aspx