Sie sind auf Seite 1von 26

4.

Miscellaneous

.1 How to get the currently logged in user?

To get the user ID of the user who is currently logged in, you would get it using this:

System.Web.HttpContext.Current.User.Identity.Name VB.NET

'Displays the currently logged in user


Response.Write(User.Identity.Name.ToString())

C#

//Displays the currently logged in user


Response.Write(User.Identity.Name.ToString());

4.2 How to specify a line break in a Label's Text?

Use the "<br>" tag to specify line breaks. For example:

VB.NET

Label1.Text = "<sometag1>" + "<br>" + "<sometag1>"

C#

Label1.Text = "<sometag1>" + "<br>" + "<sometag1>";

4.3 How to convert a string to HTML format?

Use namespace System.Web.HttpUtility

VB.NET

Dim mystring as string =”Tom & Jerry”


Response.Write (HttpUtility.HtmlDecode (mystring))

1
C#

string mystring=”Tom & Jerry”;


Response.Write (HttpUtility.HtmlDecode (mystring));

4.4 How do I determine if the user clicked a "Submit" button twice in the
page?

Check out Andy Smith's OneClick Control

4.5 How to write date-time values of fields in a dataset into xml in a specific
format?

Refer Format DateTime Values in XML extracted from Dataset

4.6 What does "~" mean in ASP.NET applications?

The tilde (~) in front of URLs means that these URLs point to the root of your web application.

Web developers are familiar with using relative paths for all links, including hyperlinks, images, and stylesheets, to

be able to move around web pages collectively.

In ASP.NET when using User controls the relative paths can be difficult to use. The typical solution to this is to use

web-root absolute paths instead here, resulting in the hard-coded sub-directories that are common on ASP.NET

sites.

The correct solution to this problem is to use app-relative paths instead, which ASP.NET nicely makes possible

through the use of the tilde (~) prefix. Instead of <a href="/UC/Page.aspx">, use <a href="~/Page.aspx"

runat="server">. The same ~ notation works for images also, as long as you add runat="server". There is also a

ResolveUrl method that allows you to use ~ in your own code, which is one possible way to get stylesheet paths

app-relative. Refer Tilde: Reference the Application Root

4.7 How can I reference simple DLL which contains one class but has no
namespace assigned to it in an .aspx page?

You don't need a namespace to reference it; anything in the bin folder is implicitly in the same namespace as the

page being compiled. So if your class looks like this:

2
Public Class MyClass1
Public Sub New()
End Sub

public Function getTheName(byval strval as string) as string


Return "Hello" + strval
End function
End Class

VB.NET

Dim mc As New MyClass1


Response.Write(mc.getTheName)

C#

MyClass1 mc = new MyClass1();


Response.Write(mc.getTheName);

4.8 How do I specify the Japanese locale for the controls in my Japanese
localized page?

Just set the locale to Japanese in the Page directive.

i. e Set the Culture= "ja-JP" for the Page Directive.

• ASP.NET pages support Culture and UICulture attributes to support independent localized pages.

• Controls on pages can pick the culture of the page and can render culture-dependent content.

4.9 Why do some of the events on my page fire twice?

This is probably because you explicitly subscribed to the events in code and also specified the AutoEventWireUp of

Page to true (it's true by default). If so, the Page_Load, for example, will be fired once for your event subscription

and once because the Page subscribed it for you (by looking for a specific event handler method signature).

To avoid this turn off AutoEventWireUp or remove your subscription code.

4.10 How to remove the spaces in a given string?

Use the Namespace System.Text.RegularExpressions VB.NET

3
Dim strval As String = "Jack and Jill"
Dim strnewval As String = Regex.Replace(strval, " ", "")
Response.Write(strnewval)

C#

string strval = "Jack and Jill";


string strnewval = Regex.Replace(strval, " ", "");
Response.Write(strnewval) ;

4.11 I get the error System.__ComObject when using recordset?

This error occurs if you are trying to fetch the recordset value as follows

rs.Fields("productname")

To avoid this error try VB.NET

rs.Fields("productname").Value.ToString()

C#

rs.Fields["productname").Value.ToString() ;

4.12 Why do I get error "A generic error occurred in GDI+." when trying to
save the bitmap file?

May be the path of the file you are giving is wrong or you do not have write permissions on the specific folder.

4.13 How can I force a Save As dialog box from an ASP.NET Web page.

VB.NET

Response.Clear()
Response.AppendHeader("content-disposition", "attachment; filename=document1.doc")
Response.ContentType = "text/plain"
Response.WriteFile(Server.MapPath("document1.doc"))

4
Response.Flush()
Response.End()

C#

Response.Clear();
Response.AppendHeader("content-disposition", "attachment; filename=document1.doc");
Response.ContentType = "text/plain";
Response.WriteFile(Server.MapPath("document1.doc"));
Response.Flush();
Response.End();

4.14 In ASP.NET is there a control similar to Combobox in Windows forms?

Check out Andy Smith's ComboBox Control

Also an useful article by Khoi ComboBox WebControl

4.15 How to do text encryption and decryption?

Here are some interesting articles that talk about encryption and decryption:

• Encrypting Cookie Data with ASP.NET

• Using MD5 to Encrypt Passwords in a Database

• String Encryption With Visual Basic .NET

4.16 How can I trigger a submit on my form when the enter key is pressed?

Add this to the body element:

<body MS_POSITIONING="GridLayout" onkeypress="if(window.event.keyCode==13){


document.Form1.submit();}">
...
</body>

Also check out Andy Smith's DefaultButton Control which triggers submit selectively on one of many buttons based

on the context.

4.17 How to get list of all files in the directory?

5
To get the list of aspx files under your app directory:

Use namespace System.IO

VB.NET

Dim dirInfo As New DirectoryInfo(Server.MapPath(""))


DataGrid1.DataSource = dirInfo.GetFiles("*.aspx")
DataGrid1.DataBind()

C#

DirectoryInfo dirInfo = new DirectoryInfo(Server.MapPath(""));


DataGrid1.DataSource = dirInfo.GetFiles("*.aspx");
DataGrid1.DataBind();

The following aspx code will display the resultant files list in the DataGrid in a proper format:

<asp:DataGrid runat="server" id="DataGrid1" AutoGenerateColumns="False">


<Columns>
<asp:HyperLinkColumn DataNavigateUrlField="Name" DataTextField="Name" HeaderText="File
Name"></asp:HyperLinkColumn>
<asp:BoundColumn DataField="LastWriteTime" HeaderText="Last Write Time"
DataFormatString="{0:d}"></asp:BoundColumn>
<asp:BoundColumn DataField="Length" HeaderText="File Size" DataFormatString="{0:#,###
bytes}"></asp:BoundColumn>
</Columns>
</asp:DataGrid>

4.18 What is HttpHandler?

An HttpHandler is a class that handles HTTP requests. In ASP.Net a Page class, for example, is the default

HttpHandler for files with a .aspx extension. You can map different file extensions to different HttpHandlers in

ASP.Net. When the web server receives a request for a file, it looks in its configuration to find out whether a special

HttpHandler has been designated for that file extension. ASP.Net provides the HttpHandler class to extend the

functionality of ASP.net to be able to handle requests for other file types (extensions). In IIS, you make ASP.Net the

HttpHandler for the type of file that you desire, and use the web.config file for your web to identify what DLL (Class

Library) is used to handle specific file extensions.

The HttpHandler is a class that handles the request. It has access to the same HttpContext (Request, Response,

Cookies, Session, Application, Server, etc) that the Page class does. For more detailed information, see:

HttpHandlers

6
4.19 How to get the size of a byte array?

VB.NET

myByteArray.Length

C#

myByteArray.Length;

4.20 How to know the width and height in pixels of a given image
programmatically?

You will have to create a Bitmap instance from the image file and then query the Width and Height as follows:

VB.NET

Dim bm As Bitmap = New Bitmap(Server.MapPath("b2346.jpg"))


Response.Write("Height :" + bm.Height.ToString())
Response.Write("<br> Width :" + bm.Width.ToString())

C#

Bitmap bm = new Bitmap( Server.MapPath("b2346.jpg"));


Response.Write ("Height :" + bm.Height.ToString() );
Response.Write ("<br> Width :" +bm.Width.ToString() );

4.21 When using FormsAuthentication, how can I redirect a user to a


different page other than the default page?

When FormsAuthentication is used in ASP.NET, by default, it gets redirected to the default.aspx page.

To redirect it to some other page other than default.aspx you have to use the code below.

VB.NET

FormsAuthentication.SetAuthCookie(txtUsername.Text,false)
Response.Redirect("someotherpage.aspx")

7
C#

FormsAuthentication.SetAuthCookie(txtUsername.Text,false);
Response.Redirect("someotherpage.aspx");

4.22 Is there a control in ASP.NET for geting HTML like the ASPHTTP for the
classic asp.

Use System.Net.HttpWebRequest

4.23 Why do I get error message "System.Web.HttpException: Request is not


available in this context" " when using Cookies?

Try using "System.Web.HttpContext.Current.Request.Cookies" instead of "Request.Cookies" in your code.

4.24 How to save the Output of ASP.NET to HTML?

Use the namespaces

• System.Net which have classes WebRequest and WebResponse.

o WebRequest is the abstact base class for the .NET Framework's request/response model for

accessing data from the internet and

o WebResponse is the abstract base class from which protocol specific response classes are derived.

• System.IO which have classes StreamReader and StreamWriter.

o StreamReader designed for character input in a particular encoding.

o StreamWriter designed for character output in a particular encoding.

VB.NET

Dim mywebReq As WebRequest


Dim mywebResp As WebResponse
Dim sr As StreamReader
Dim strHTML As String
Dim sw As StreamWriter
Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
'Give the Appropriate URL for .aspx page. in this case its "http://www.syncfusion.com/faq.asp"
mywebReq = WebRequest.Create("http://www.syncfusion.com/faq.asp")
mywebResp = mywebReq.GetResponse()
sr = New StreamReader(mywebResp.GetResponseStream)

8
strHTML = sr.ReadToEnd
sw = File.CreateText(Server.MapPath("temp.html"))
sw.WriteLine(strHTML)
sw.Close()
Response.WriteFile(Server.MapPath("temp.html"))
End Sub

C#

WebRequest mywebReq ;
WebResponse mywebResp ;
StreamReader sr ;
string strHTML ;
StreamWriter sw;
private void Page_Load(object sender, System.EventArgs e)
{
// Put user code to initialize the page here
mywebReq = WebRequest.Create("http://www.syncfusion.com/faq.asp");
mywebResp = mywebReq.GetResponse();
sr = new StreamReader(mywebResp.GetResponseStream());
strHTML = sr.ReadToEnd();
sw = File.CreateText(Server.MapPath("temp.html"));
sw.WriteLine(strHTML);
sw.Close();
Response.WriteFile(Server.MapPath("temp.html"));
}

Note:For creating the file (in above case "temp.html") give appropriate rights (modify and write) to the ASPNET

user.

To specify the Encoding specify the second parameter of the StreamReader accordingly

VB.NET

sr = New StreamReader(mywebResp.GetResponseStream, System.Text.Encoding.ASCII)

C#

sr = new StreamReader(mywebResp.GetResponseStream(), System.Text.Encoding.ASCII);

4.25 Why do I get ViewState error when upgrading my application from a


single web server to a web farm?

This usually happens when encryption is enabled for ViewState in all your pages but the different server machines

use different Validation Keys for encrypting. Ensure that all the machines has the same validation key specified in

9
their machine.config file. For example, add the following key:

<machinekey validation='3DES'>

4.26 How to convert Color to it's corresponding Hexadecimal value?

VB.NET

Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load


'Put user code to initialize the page here
Response.Write(ToHexColor(Color.Blue))
End Sub

Function ToHexColor(ByVal c As Color) As String


Return "#" + c.ToArgb().ToString("x").Substring(2)
End Function

C#

private void Page_Load(object sender, System.EventArgs e)


{
// Put user code to initialize the page here
Response.Write(ToHexColor(Color.Blue));
}
string ToHexColor(Color c )
{
return "#" + c.ToArgb().ToString("x").Substring(2);
}

4.27 How to Select a record using Listbox and edit/update it's fields using
textboxes?

<TABLE class="cdb-AltRow2" id="Table1" style="Z-INDEX: 101; LEFT: 189px; POSITION: absolute; TOP: 20px"
cellSpacing="1" cellPadding="1" width="300" border="0">
<TR>
<TD>ProductID</TD>
<TD><asp:textbox id="txtProductId" runat="server" Enabled="False"></asp:textbox></TD>
</TR>
<TR>
<TD>Qunatity per unit</TD>
<TD><asp:textbox id="txtQuantity" runat="server"></asp:textbox></TD>
</TR>
<TR>
<TD>UnitPrice</TD>
<TD><asp:textbox id="txtUnitPrice" runat="server"></asp:textbox></TD>
</TR>
<TR>
<TD></TD>

10
<TD><asp:button id="btnUpdate" runat="server" Text="Update"></asp:button></TD>
</TR>
<TR>
<TD></TD>
<TD><asp:label id="lblError" runat="server" Visible="False"></asp:label></TD>
</TR>
</TABLE>
<asp:listbox id="ListBox1" style="Z-INDEX: 102; LEFT: 8px; POSITION: absolute; TOP: 12px" runat="server"
AutoPostBack="True"></asp:listbox>

VB.NET

Dim productid As String


Dim strSQL As String
Dim strConn As String
Dim dr, dr1 As SqlDataReader
Dim mycn As SqlConnection
Dim mycmd As SqlCommand

Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load


strConn = "server=localhost;uid=sa;database=northwind;pwd=;"
lblError.Visible = False
' Put user code to initialize the page here
If Not Page.IsPostBack Then
mycn = New SqlConnection(strConn)
strSQL = "Select * from Products"
mycmd = New SqlCommand(strSQL, mycn)
mycn.Open()
dr = mycmd.ExecuteReader(CommandBehavior.CloseConnection)
ListBox1.DataSource = dr
ListBox1.DataTextField = "ProductID"
ListBox1.DataValueField = "ProductID"
ListBox1.DataBind()
End If
End Sub 'Page_Load

Private Sub btnUpdate_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles


btnUpdate.Click
Try
lblError.Visible = False
Dim updateCmd As String = "UPDATE Products SET QuantityPerUnit = @QuantityPerUnit ," + "UnitPrice =
@UnitPrice where ProductId=@ProductId"
Dim cn As New SqlConnection(strConn)
Dim myCommand As New SqlCommand(updateCmd, cn)
myCommand.Parameters.Add(New SqlParameter("@QuantityPerUnit", txtQuantity.Text))
myCommand.Parameters.Add(New SqlParameter("@UnitPrice", Convert.ToDouble(txtUnitPrice.Text)))
myCommand.Parameters.Add(New SqlParameter("@ProductId", Convert.ToInt16(txtProductId.Text)))
cn.Open()
myCommand.ExecuteNonQuery()
lblError.Visible = True
lblError.Text = "Record Updated successfully"
Catch ex As Exception
lblError.Visible = True
lblError.Text = ex.Message
End Try
End Sub 'btnUpdate_Click

Private Sub ListBox1_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs)


Handles ListBox1.SelectedIndexChanged
productid = ListBox1.SelectedItem.Value
txtProductId.Text = productid.ToString()

11
strSQL = "Select * from Products where productid =" + productid
mycn = New SqlConnection(strConn)
mycmd = New SqlCommand(strSQL, mycn)
mycn.Open()
dr1 = mycmd.ExecuteReader(CommandBehavior.CloseConnection)
If dr1.Read() Then
txtProductId.Text = dr1("ProductId").ToString()
txtQuantity.Text = dr1("QuantityPerUnit").ToString()
txtUnitPrice.Text = dr1("UnitPrice").ToString()
Else
Response.Write("No data found")
End If
End Sub 'ListBox1_SelectedIndexChanged

C#

string productid;
string strSQL;
string strConn;
SqlDataReader dr,dr1;
SqlConnection mycn;
SqlCommand mycmd;

private void Page_Load(object sender, System.EventArgs e)


{
strConn ="server=localhost;uid=sa;database=northwind;pwd=;";
lblError.Visible =false;
// Put user code to initialize the page here
if (!Page.IsPostBack )
{
mycn = new SqlConnection(strConn);
strSQL ="Select * from Products";
mycmd = new SqlCommand (strSQL, mycn);
mycn.Open ();
dr=mycmd.ExecuteReader(CommandBehavior.CloseConnection );
ListBox1.DataSource = dr;
ListBox1.DataTextField ="ProductID";
ListBox1.DataValueField ="ProductID";
ListBox1.DataBind ();
}
}

private void btnUpdate_Click(object sender, System.EventArgs e)


{
try
{
lblError.Visible =false;

string updateCmd = "UPDATE Products SET QuantityPerUnit = @QuantityPerUnit ,"


+ "UnitPrice = @UnitPrice where ProductId=@ProductId";

SqlConnection cn = new SqlConnection (strConn);


SqlCommand myCommand = new SqlCommand(updateCmd, cn);
myCommand.Parameters.Add(new SqlParameter("@QuantityPerUnit", txtQuantity.Text ));
myCommand.Parameters.Add(new SqlParameter("@UnitPrice", Convert.ToDouble( txtUnitPrice.Text )));
myCommand.Parameters.Add(new SqlParameter("@ProductId", Convert.ToInt16 ( txtProductId.Text)));
cn.Open ();
myCommand.ExecuteNonQuery ();
lblError.Visible =true;
lblError.Text ="Record Updated successfully";
}
catch(Exception ex)

12
{
lblError.Visible =true;
lblError.Text =(ex.Message );
}
}

private void ListBox1_SelectedIndexChanged(object sender, System.EventArgs e)


{
productid = ListBox1.SelectedItem.Value ;
txtProductId.Text =productid.ToString ();
strSQL = "Select * from Products where productid =" + productid ;
mycn = new SqlConnection(strConn);
mycmd = new SqlCommand (strSQL, mycn);
mycn.Open ();
dr1=mycmd.ExecuteReader(CommandBehavior.CloseConnection );
if(dr1.Read() )
{
txtProductId.Text = dr1["ProductId"].ToString ();
txtQuantity.Text = dr1["QuantityPerUnit"].ToString ();
txtUnitPrice.Text = dr1["UnitPrice"].ToString ();
}
else
{
Response.Write ("No data found");
}
}

4.28 How to select a value from a child form and send it to parent form?

page1.aspx

<asp:TextBox id="txtSelect" style="Z-INDEX: 101; LEFT: 186px; POSITION: absolute; TOP: 19px"
runat="server"></asp:TextBox>
<a
href="javascript:my_window=window.open('page2.aspx?formname=Form1.txtSelect','my_window','width=300,height=300');my_
Select CategoryName</a>

page2.aspx

<asp:DropDownList id="DropDownList1" style="Z-INDEX: 101; LEFT: 180px; POSITION: absolute; TOP: 66px"
runat="server" AutoPostBack="True">
<asp:Label id="Label1" style="Z-INDEX: 102; LEFT: 16px; POSITION: absolute; TOP: 66px" runat="server">Select
Category Name
<asp:Literal id="Literal1" runat="server">

VB.NET

Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load


'Put user code to initialize the page here
If Not Page.IsPostBack Then
'Fill DataSet ....
DropDownList1.DataSource = ds.Tables(0)

13
DropDownList1.DataTextField = "CategoryName"
DropDownList1.DataValueField = "CategoryId"
DropDownList1.DataBind()
End If
End Sub

Private Sub DropDownList1_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs)


Handles DropDownList1.SelectedIndexChanged
Try
Dim strjscript As String = "<script language=""javascript"">"
strjscript = strjscript & "window.opener." & HttpContext.Current.Request.QueryString("formname") & ".value =
'" & DropDownList1.SelectedItem.Text & "';window.close();"
strjscript = strjscript & "</script>"
Literal1.Text = strjscript
Catch ex As Exception
Response.Write(ex.Message)
End Try
End Sub

C#

private void Page_Load(object sender, System.EventArgs e)


{
// Put user code to initialize the page here
if (!Page.IsPostBack )
{
//Fill DataSet
DropDownList1.DataSource = ds.Tables[0];
DropDownList1.DataTextField = "CategoryName";
DropDownList1.DataValueField = "CategoryId";
DropDownList1.DataBind();
}
}

private void DropDownList1_SelectedIndexChanged(object sender, System.EventArgs e)


{
try
{
string strjscript = @"<script language=""javascript"">";
strjscript = strjscript + "window.opener." + HttpContext.Current.Request.QueryString["formname"].ToString ()
+ ".value = '" + DropDownList1.SelectedItem.Text + "';window.close();";
strjscript = strjscript + "</script>";
Literal1.Text = strjscript;
}
catch(Exception ex)
{
Response.Write (ex.Message );
}
}

4.29 How to read the comma seperated values from a string?

VB.NET

Dim myString As String = "A, B, C, D"


Dim delimStr As String = " ,"

14
Dim delimiter As Char() = delimStr.ToCharArray()
Dim s As String
For Each s In myString.Split(delimiter)
Response.Write((s.ToString() + "<br>"))
Next

C#

string myString = "A, B, C, D";


string delimStr = " ,";
char[] delimiter = delimStr.ToCharArray();
foreach (string s in myString.Split(delimiter))
{
Response.Write (s.ToString ()+ "<br>");
}

4.30 How do I make my TextBox positioned below a DataGrid move up or


down in position as the height of the DataGrid changes?

Specify the pageLayout of the Document from GridLayout to FlowLayout, this will position the controls automatically

and optimally.

4.31 How to stamp Date-Time on all the pages in an application when


requested?

Use the global.asax file and listen to the PostRequestHandlerExecute event of the Global object.

In the handler Global_PostRequestHandlerExecute write the following code

VB.NET

Response.Write("This page is updated on " & DateTime.Now.ToString())

Response.Write("This page is updated on " + DateTime.Now.ToString());

4.32 How can I have multiple command buttons map to the same event or
function?

Simply use the same handler for the different button Click events.

<asp:Button id="Button1" runat="server" Text="Button"></asp:Button>


<asp:Button id="Button2" style="Z-INDEX: 103; LEFT: 8px; POSITION: absolute; TOP: 80px" runat="server"
Text="Button"></asp:Button>

15
VB.NET

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click,


Button2.Click
Response.Write("hi you clicked " + CType(sender, Button).ID)
End Sub

C#

// In InitializeComponent
this.Button1.Click += new System.EventHandler(this.Button1_Click);
this.Button2.Click += new System.EventHandler(this.Button1_Click);

private void Button1_Click(object sender, System.EventArgs e)


{
Response.Write("hi you clicked " + ((Button)sender).ID );
}

4.33 How to use a RangeValidator to select Colors from a specific range?

<asp:dropdownlist id="DropDownList1" runat="server">


<asp:ListItem Value ="#000000">#000000</asp:ListItem>
<asp:ListItem Value ="#ff0000">#ff0000</asp:ListItem>
<asp:ListItem Value ="#0000ff">#0000ff</asp:ListItem>
<asp:ListItem Value ="#00aacc">#00aacc</asp:ListItem>
<asp:ListItem Value ="#0000cc">#0000cc</asp:ListItem>
<asp:ListItem Value ="#cc0000">#cc0000</asp:ListItem>
<asp:ListItem Value ="#00ff00">#00ff00</asp:ListItem>
</asp:dropdownlist>
<asp:rangevalidator id="RangeValidator1" runat="server"
ErrorMessage="Select a color between #00ff00 to #ff0000" ControlToValidate="DropDownList1"
MaximumValue="#ff0000" MinimumValue="#00ff00">
</asp:rangevalidator>

4.34 How to restore the browser's scroll position after a postback?

Set the SmartNavigation attribute to true.

4.35 Is there something as RecordSet we had in ASP that can be used in


ASP.NET?

16
You can make use of a DataReader.

Refer How to display data in Textboxes using DataReader?

4.36 How to set a <link> tag's href attribute at runtime using a value
specified in the web.config file?

web.config

<configuration>
<appSettings>
<add key="CSS1" value="StyleSheet1.css" />
</appSettings>
</configuration>

.aspx

<link id="link1" runat="server"/>

VB.NET

Dim lnk As New System.Web.UI.HtmlControls.HtmlGenericControl("lnk")


lnk = CType(Me.Page.FindControl("link1"), System.Web.UI.HtmlControls.HtmlGenericControl)
lnk.Attributes.Add("rel", "stylesheet")
lnk.Attributes.Add("href", ConfigurationSettings.AppSettings("CSS1").ToString())
lnk.Attributes.Add("type", "text/css")

C#

System.Web.UI.HtmlControls.HtmlGenericControl lnk =new System.Web.UI.HtmlControls.HtmlGenericControl ("lnk")


;
lnk =(System.Web.UI.HtmlControls.HtmlGenericControl ) this.Page.FindControl( "link1") ;
lnk.Attributes.Add ("rel", "stylesheet");
lnk.Attributes.Add ("href", ConfigurationSettings.AppSettings["CSS1"].ToString()) ;
lnk.Attributes.Add ("type","text/css");

4.37 How to call the Page_load procedure from any event on the page?

VB.NET

Dim strval As String = "a"


If strval = "a" Then
Call Page_Load(sender, e)
End If

17
C#

string strval ="a";


if( strval =="a")
{
Page_Load(sender,e);
}

4.38 How to add login user (ASPNET) to MS SQL 2000 Desktop Engine server?

Go to drive:\Program Files\Microsoft SQL Server\80\Tools\binn

Use OSQL, a command line tool.

osql -S servername\instancename -E -q
--Line numbers will appear
EXEC sp_grantlogin 'machinename\ASPNET'
go

use
go

EXEC sp_grantdbaccess 'machinename\ASPNET'


go

EXEC sp_addrolemember 'db_owner', 'machinename\ASPNET'


go

4.39 How to get the count of rows in a Excel file?

Add reference -> COM tab ->Microsoft Excel 11.0 Object Library

<asp:Label id="Label1" runat="server"></asp:Label>

VB.NET

Dim excelApp As New Microsoft.Office.Interop.Excel.Application


excelApp.Workbooks.Open(Server.MapPath("excel1.xls"))
Label1.Text = excelApp.ActiveSheet.Usedrange.count.ToString
excelApp.Workbooks.Close()

C#

18
Microsoft.Office.Interop.Excel.Application excelApp = new Microsoft.Office.Interop.Excel.Application();
excelApp.Workbooks.Open ( Server.MapPath ("excel1.xls"), Type.Missing, Type.Missing, Type.Missing, Type.Missing,
Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing,
Type.Missing, Type.Missing );
Microsoft.Office.Interop.Excel.Worksheet wks;
wks =(Microsoft.Office.Interop.Excel.Worksheet)excelApp.ActiveSheet;
Label1.Text =wks.UsedRange.Count.ToString();
excelApp.Workbooks.Close();

4.40 What are the pros and cons of using Session or Cache to save
intermediate state?

To store in Session:

Pros:

• It's stored per user session

• It's just a handle to a live object, if using InProc

• If you use StateServer or SQLServer mode, you can access your session state across the webfarm. (can't

use InProc mode in webfarm)

Cons:

• If you use StateServer or SQLServer mode, your object must be serializable, and you pay the performance

cost of network traffic + serialization cost

To use cache:
Pros:

• It's always stored as just a handle to the live object

• Can use cache dependencies or other cache features to control its lifetime

• Can be shared by all users on that web server

Cons:

• It's per app-domain per web server.

4.41 How to mirror (align elements Right to Left) a form or control on a form?

Process of switching of User Interface between left to right i.e English, German ...and right to left such as

Hebrew/Arabic is called Mirroring.

19
To mirror a form

<html dir="rtl">

To mirror individual control in a form set dir=rtl for individual controls.

4.42 How can I Enable ASPX Compression in IIS?

You can use Http Compression to compress static aspx files. Refer Microsoft Knowledge Base Article - 322603

4.43 How to run an exe from a ASP.NET page?

For security reasons, you can't force a user to run any executable.

Instead give user the option to click on it and download the executable, and execute it if he wants to. All you can do

is put .exe in a directory on your web site and put a hyperlink to it on some page.

Note : Be sure to secure this directory by deactivating all execution permissions both in the IIS console and in the

directory ACL

For more details refer INFO: Executing Files by Hyperlink and the File Download Dialog Box

4.44 Why does FormsAuthentication.Decrypt crashes when moving to another


Server?

The reason why the encrypted data couldn't be decrypted on another machine is because the validation key in the

original machine's machine.config is set to AutoGenerate. This means that the generated keys are unique to each

machine. A better solution will be to specify the validation key, so you can decrypt it across any machine with the

same validation key. For more details on solutioon refer following article :

• Microsoft Knowledge Base Article - 313091

• Microsoft Knowledge Base Article - 312906

4.45 Why do I get error message "Login failed for user


DOMAIN\USERNAME"?

You'll have to create an account in SQL Server for the aspnet user.

20
• Start enterprise manager-> expand the server-> select security->Right-click in the right view and select

new login,

• enter the DOMAIN\USERNAME and select your database as the default database of the user at the bottom

of the page,

• Select last tab Database Access -> select your database, and add the db_datareader and db_datawriter

policies to your user.

4.46 How to check if the current User has been Authenticated?

VB.NET

If User.Identity.IsAuthenticated Then
'Your code
End If

C#

if (User.Identity.IsAuthenticated )
{
//Your code
}

4.47 How to get the Computer Name on which the code is running?

This will return the information of the server computer, not the client browser computer.

Add reference to System.Windows.Forms.dll.

VB.NET

Response.Write(System.Windows.Forms.SystemInformation.ComputerName)

C#

Response.Write(System.Windows.Forms.SystemInformation.ComputerName);

21
4.48 How to pass argument to accessdatasourcecontrol selectcommand
statement?

VB.NET

AccessDataSourceControl1.SelectCommand = "SELECT * FROM <tablename> WHERE <fieldname> = " &


Request("CustID")

C#

AccessDataSourceControl1.SelectCommand = "SELECT * FROM <tablename> WHERE <fieldname> = "+


Request["CustID"]

4.49 How to compile CS/VB file and place new DLL in bin subdirectory?

You can build a dll using the following command line .

Assuming your command window has the appropriate path set to use the following exes:

VB.NET compiler vbc.exe

vbc.exe /out:SyncVB.dll /target:library SyncVB.vb

C# compiler csc.exe

csc.exe /out:SyncCS.dll /target:library SyncCS.cs

To reference it within the .aspx page use the Import directive:

<%@ Import Namespace="SyncVB" %>

or

<%@ Import Namespace="SyncCS" %>

4.50 Can I use a src attribute with a Web Service?

The .aspx pages are the only ones that support the Src attribute, and therefore it's the only file type that supports

JIT compilation of separate source files.By using the Src attribute in the page directive, you can specify which file

22
the ASP.NET engine should compile.

It cannot be used with a WebService.

This means that you must precompile the code behind class that is to be used as the basis for the Web Service,

either manually using the Command-line compiler or by building a Visual Studio.NET Web Service Application.

4.51 How to display random images on a web page from a set of images in a
directory?

<table id="Table1" cellspacing="1" cellpadding="1" border="1">


<tr>
<td id="TD1" width="100" runat="server">

</td>
</tr>
</table>

VB.NET (Add reference to Microsoft Visual Basic .NET Runtime)

Dim dirInfo As New System.IO.DirectoryInfo("c:\inetpub\wwwroot\syncfusion\images") 'This is your path to the


bmp's
Dim fileInfo() As IO.FileInfo
Dim strRandomImage As String
Dim i As Integer
Dim rnd As Random
fileInfo = dirInfo.GetFiles("*") 'Gets an array of file info
rnd = New Random
Randomize()
i = CInt(rnd.NextDouble * UBound(fileInfo)) ' gets a random index
strRandomImage = "images/" + fileInfo(i).Name ' Returns the random string
TD1.Attributes.Add("background", strRandomImage)

C#

System.IO.DirectoryInfo dirInfo =new System.IO.DirectoryInfo(@"c:\inetpub\wwwroot\SyncnewCsharp\images")


;//This is your path to the bmp's
System.IO.FileInfo[] fileInfo ;
string strRandomImage;
int i ;
Random rnd ;
fileInfo = dirInfo.GetFiles("*"); //Gets an array of file info
rnd = new Random();
Microsoft.VisualBasic.VBMath.Randomize ();
i = Convert.ToInt32 (rnd.NextDouble() * fileInfo.GetUpperBound(0));// gets a random index
strRandomImage = "Images/" + fileInfo[i].Name ;// Returns the random string
TD1.Attributes.Add ("background", strRandomImage);

23
4.52 How can I scan a string to determine if it contains DBCS chars?

VB.NET

Public Shared Function IsAsciiString(s As [String]) As Boolean


Dim i As Integer
For i = 0 To s.Length - 1
Dim ch As Char = s(i)
If ch < 0 Or ch > 127 Then
Return False
End If
Next
Return True
End Function 'IsAsciiString

'In Page_Load
dim originalString as string = "a±"
Response.Write (IsAsciiString(originalString))

C#

public static bool IsAsciiString(String s)


{
for (int i = 0; i < s.Length; i++)
{
char ch = s[i];
if (ch < 0 || ch > 127) return false;
}
return true;
}
//In Page_Load
String originalString = "a±" ;
Response.Write (IsAsciiString(originalString));

4.53 Request.ServerVariables("LOGON_USER") always returns empty string


in Framework 1.1 . Why? It worked fine in ASP?

If Request.ServerVariables("LOGON_USER") is returning an empty string, the problem is probably that your app

allows anonymous users. To change this:

• Open IIS manager

• right-click on your app name and choose properties

• Click on directory security tab

• Edit Authentication and Access Control

24
• Uncheck 'Enable anonymous'.

4.54 Is there a way to specify CSS only if the browser is IE?

You can examine the Request.UserAgent to check if the browser was IE, define a custom HtmlGenericControl type

representing your stylesheet link and set the href property on it depending on if the browser was IE.

<LINK rel=stylesheet runat="server" id="lnkStyle">

Where LINK is a HtmlGenericControl. You could then do something like this:

VB.NET

lnkStyle.Attributes("href") = "ie/styles.css"

C#

lnkStyle.Attributes["href"] = "ie/styles.css" ;

4.55 How to create Custom Application Settings in the web.config?

In the web.config file add a key-value pair as follows:

<configuration>
<appSettings>
<add key="PageSize" value="10">
</add>
</appSettings>
</configuration>

Then you can access the settings as follows in code:

VB.NET

Response.Write (ConfigurationSettings.AppSettings("PageSize"))

C#

25
Response.Write (ConfigurationSettings.AppSettings["PageSize"] );

4.56 Why do I get "do not have permissions" error when accessing a Access
mdb file in my local system?

This could be because of security concerns. Please check this KB for resolutions:

KB 316675

4.57 How can I access an MS Access database in my ASPX page, if the db is


on a remote server?

To access an MS Access database from your ASP.Net page, you must use the UNC format in the path, like:

\\Servername\yourpath\your.mdb

To fully use the database, grant permissions to the ASPNet user account equal to 'modify', for the folder/directory

where the database exists.

26

Das könnte Ihnen auch gefallen