New Year Wishes - Year 2010

Dec 31, 2009 Posted by Lara Kannan 0 comments
New Year Wishes - Year 2010

To my ever tolerant my friends and relatives, available round the clock for valuable support and guidance, and to all those who are very close to my heart, here is a special note, exactly a day before yet another sunrise in our life that'd see us replace one more calendar with a brand new one, quite symbolic to our mind's act of replacing unfullfilled dreams and promises with new ones and to give it all a fresh beginning.

GOOD BYE my 2009.

Here's wishing all a very happy, peaceful and prosperous New Year 2010.

Share
Labels:

What is an ASHX file Handler or web handler ?

Posted by Lara Kannan 0 comments
In ASP.NET, you probably spend most of your time creating .aspx files with .cs files as code behind or use .ascx files for your controls and .asmx files for web services.

A web handler file works just like an aspx file except you are one step back away from the messy browser level where HTML and C# mix. One reason you would write an .ashx file instead of an .aspx file is that your output is not going to a browser but to an xml-consuming client of some kind.

Working with .ashx keeps you away from all the browser technology you don't need in this case. Notice that you have to include the IsReusable property.

What does the code there do?

It defines two parts of the IHttpHandler interface. The important part is ProcessRequest(), which will be invoked whenever the Handler.ashx file is requested or pointed to.

<%@ WebHandler Language="C#" Class="Handler" %>

using System;
using System.Web;

public class Handler : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/plain";
context.Response.Write("Hello World");
}

public bool IsReusable
{
get
{
return false;
}
}
}

Using query strings:

Developers commonly need to use the QueryString collection on the Request. You can use the Request.QueryString in the Handler just like you would on any ASPX web form page.

<%@ WebHandler Language="C#" Class="QueryStringHandler" %>

using System;
using System.Web;

public class QueryStringHandler : IHttpHandler
{
public void ProcessRequest (HttpContext context)
{
HttpResponse r = context.Response;
r.ContentType = "image/png";
string file = context.Request.QueryString["file"];
if (file == "Arrow")
{
r.WriteFile("Arrow.gif");
}
else
{
r.WriteFile("Image.gif");
}
}

public bool IsReusable
{
get
{
return false;
}
}
}

Now Debug the application:

When you pass Fille='Arrow' in query string like as follows

http://localhost:1372/FileHandler/QueryStringHandler.ashx?file=Arrow
You will get the output with arrow image. Otherwise you will get output as image.

http://localhost:1372/FileHandler/QueryStringHandler.ashx?file=Image

The above code receives requests and then returns a different file based on the QueryString collection value. It will return one of two images from the two query strings.

When we use Handler:

Here I want to propose some guidelines about when to use custom handlers and when to use ASPX web form pages. Handlers are better for binary data, and web forms are best for rapid development.

Use web forms (ASPX) when you have:

  • Simple HTML pages

  • ASP.NET custom controls

  • Simple dynamic pages

Use handlers (ASHX) when you have:

  • Binary files

  • Dynamic image views

  • Performance-critical web pages

  • XML files

  • Minimal web pages

Hope this will be useful.

Thanks : Purushottam

Share
Labels: ,

How to add jQuery intellisense in Visual Studio 2008

Posted by Lara Kannan 0 comments
How to add jQuery intellisense in Visual Studio 2008. I will discuss the below items :

  • How to add jQuery intellisense in .aspx page.

  • How to add jQuery intellisense in external javascript file.


Step 1 : Install Visual Studio 2008 Service Pack 1

To see whether you have already installed version of Visual Studio 2008 Service Pack 1.
1. Open Visual Studio 2008. Go to Help--->About Microsoft Visual Studio.

2. About Microsoft Visual Studio window will open.
You may here Version 9.0.30729.1 SP or later version.
If Visual Studio service pack is not installed then your first step is to install it.

Step 2 : Download and install VS2008 SP1 Hotfix to Support "-vsdoc.js" IntelliSense Doc Files

You can get information regarding hot fix in detail on below links
http://blogs.msdn.com/...doc-files-is-now-available.aspx

http://code.msdn.microsoft.com/.../ProjectReleases.aspx?ReleaseId=1736

Step3 : Download the jQuery-vsdoc.js file

Go to http://docs.jquery.com/...#Download_jQuery

You will find different releases of jQuery. The latest release is jQuery 1.3.2.

Click Visual Studio link in front of Documentation tag. You will be redirected to next page. In next page you can found the link for downloading jQuery-vsdoc.js file

Step 4: Rename the downloaded file

After downloading that rename it as follows.

1. Rename jquery-1.3.2-vsdoc2.js into jquery-1.3.2.min-vsdoc.js

2. Rename jquery-1.3.2.js into jquery-1.3.2.min.js



How to add jQuery intellisense in .aspx page.

In the .aspx page, add the reference jquery-1.3.2.min.js file into .aspx page. Here I have my script file under scirpts folder.

 <script src="scirpts/jquery-1.3.2.min.js" type="text/javascript"> </script> 

Now press CTRL+ SHIFT+J to update the Jscript intellisense or Go to Edit ---> IntelliSense ---> Update Jscript Intellisense. You will see Update JScript Intellisense message in the status bar.

That's all. Now you can test that your jQuery intellisense has started working.



How to add jQuery Intellisense in External javascript file

1. Add the reference of jQuery file at the top of My.js file
/// <reference path = "jquery-1.3.2.min.js" /> 

2. Now press CTRL+ SHIFT+J to update the Jscript intellisense or Go to
Edit ---> IntelliSense ---> Update Jscript Intellisense.

That's all. Make your light weight web application by using jQuery.

Hope this will be helpfull.

Share
Labels: ,

Free eBook - jQuery Cookbook Dec 2009

Dec 29, 2009 Posted by Lara Kannan 1 comments
Free download jQuery Cook book Dec 2009 edition.

Use of jQuery :
  • Create better, cross-platform JavaScript code

  • Learn detailed solutions to specific client-side problems

  • For web designers who want to create interactive elements for their designs

  • For developers who want to create the best user interface for their web applications and so on...


Downloads :
Megaupload

Rapidshare

Hotfile

Mediafire

Password :
www.updatebooks.com

A 'Thank You' would be nice! I hope this will be useful.
Thanks : Katz

Share
Labels: ,

Download : SQLite Expert Professional

Dec 27, 2009 Posted by Lara Kannan 0 comments
SQLite Expert Professional v2.3.17.1934 Portable

SQLite Expert is a powerful visual tool that enables you to easily administer your SQLite3 databases and gain significantly better visibility into how your databases are operating. SQLite Expert integrates database management and maintenance into a single, seamless environment, with a clear and intuitive graphical user interface.


Features and Benefits

  • Edit tables and views visually, without writing a line of SQL. Easily restructure fields, indexes, constraints, triggers without losing data already existing in the tables.

  • Build SQL scripts and generate views visually using the integrated Query Builder.

  • Create SQLite3 databases, view and change database parameters, check database integrity and vacuum (compact) databases.

  • Easily transfer data between SQLite databases, import data from SQL scripts or ADO data sources, or export to SQL scripts.

  • Display and edit data in the grid, including BLOB and image fields. Currently supports BMP, JPG and PNG image formats. BLOB fields can be edited with the integrated hex editor.

  • Execute SQL queries and display results in the grid or as text.

Requirements:

Windows 2000/XP/2003/Vista

Download Links:

Hotfile

Uploading

Rapidshare

Use the technology. A 'Thanks' would be appriciated.

Share

How to highlight the GridView rows when the mouse moves over it

Dec 21, 2009 Posted by Lara Kannan 0 comments
In ASP.NET, in order to add a TextBox to the GridView you will need to add a Template Column. In most of the cases I suggest that you use the Template Column instead of the Bound Column.

The reason is that by using the Template Column you can refer to the column by finding the control which exists inside the column. Bound Column works by using indexes which means that if later you add another column and change the columns placement then you will need to change all the columns respectively.



Take a look at the code below which adds Template Columns to the GridView.

We need to highlight the row when the focus is on the TextBox. For this we can attach a simple client side event to the TextBox which is called "onFocus". The onFocus event is fired whenever a focus is made on the control. Take a look at the code below which demonstrate how to add the onFocus event to the TextBox control.



<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" BackColor="White"
BorderColor="#CCCCCC" BorderStyle="Solid" BorderWidth="1px" CellPadding="3" Font-Names="Verdana"
Font-Size="Small" Width="300px">
<FooterStyle BackColor="White" ForeColor="#000066" />
<RowStyle ForeColor="#000066" />
<Columns>
<asp:ButtonField CommandName="Select" Visible="false" />
<asp:BoundField DataField="RowNumber" HeaderText="S.No" InsertVisible="False" ReadOnly="True"
Visible="true" SortExpression="RowNumber" />
<asp:TemplateField HeaderText="Name">
<ItemTemplate>
<asp:TextBox ID="TextBox1" onBlur="ResetColor()" onFocus="ChangeColor()" TabIndex="1"
Text='<%#Eval("FirstName")%>' runat="server"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Name">
<ItemTemplate>
<asp:TextBox ID="TextBox1" onBlur="ResetColor()" onFocus="ChangeColor()" TabIndex="1"
Text='<%#Eval("Address")%>' runat="server"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Delete">
<HeaderStyle HorizontalAlign="Center" Width="6%" VerticalAlign="Middle" />
<ItemStyle HorizontalAlign="Center" Width="6%" VerticalAlign="Middle" />
<ItemTemplate>
<asp:ImageButton ID="btnDelete" OnClientClick="return confirm('Do you want to delete this record?');"
CommandName="DeleteRow" AlternateText="Delete" runat="server" CommandArgument='<%# Eval("RowNumber") %>'
ImageUrl="icon_delete_grid.gif"></asp:ImageButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
<PagerStyle BackColor="White" ForeColor="#000066" HorizontalAlign="Left" />
<SelectedRowStyle BackColor="Yellow" Font-Bold="True" ForeColor="White" />
<HeaderStyle BackColor="#006699" Font-Bold="True" ForeColor="White" />
</asp:GridView>


Include the javascript function on the page :

<script type="text/javascript">
var oldRowColor;
function ResetColor()
{
var obj = window.event.srcElement;
if(obj.tagName == "INPUT" && obj.type == "text")
{
obj = obj.parentElement.parentElement;
obj.className = oldRowColor;
}
}

// this function is used to change the backgound color
function ChangeColor()
{
var obj = window.event.srcElement;
if(obj.tagName == "INPUT" && obj.type == "text")
{
obj = obj.parentElement.parentElement;
oldRowColor = obj.className;
obj.className = "HighLightRowColor";
}
}
</script>

Include the style into the page

<style type="text/css">
.RowStyleBackGroundColor
{
background-color: #FFFBD6;
}
.RowAlternateStyleBackGroundColor
{
background-color: White;
}
.HighLightRowColor
{
background-color: Yellow;
}
</style>


Finally, add the code behind code (sample given here is based on C#)

protected void Page_Load(object sender, EventArgs e)
{
DummyData();
}

private void DummyData()
{
DataTable dtCurrentTable = (DataTable)ViewState["CurrentTable"];
DataRow drCurrentRow = null;

//Store the current data to ViewState
DataTable dt = new DataTable();
DataRow dr = null;
dt.Columns.Add(new DataColumn("RowNumber", typeof(string)));
dt.Columns.Add(new DataColumn("FirstName", typeof(string)));
dt.Columns.Add(new DataColumn("Address", typeof(string)));
for (int i = 1; i <= 5; i++)
{
dr = dt.NewRow();
dr["RowNumber"] = i;
dr["FirstName"] = "Test Name " + i;
dr["Address"] = "Test Address " + i;

dt.Rows.Add(dr);
}
ViewState["CurrentTable"] = dt;

//Rebind the Grid with the current data
GridView1.DataSource = dt;
GridView1.DataBind();
}

Now, run the application and focus on one of the TextBoxes and the appropriate row will be highlighted. The result should be like below :



If you have any doubts on this, add your comments.

Share
Labels: , ,

How to change the background color in the Textbox on focus ?

Posted by Lara Kannan 0 comments

I searched the solution for the following situation. In asp.net web application, gridview contains textbox in each row. When there is focus on the textbox, the background colour of the textbox must be yellow with bold otherwise it must be black with white text.

See the sample code: we reach the solution by simply adding onfocus and onblur event to the text box.


...
...

<asp:TextBox ID="text1" runat="server"
onFocus="this.style.background ='yellow'"
onBlur="this.style.background='white'"/>

....
....

Happy coding!

Share
Labels: ,

How to catch TAB key press with JavaScript?

Dec 18, 2009 Posted by Lara Kannan 0 comments
The example code is tested in IE, Firefox and Opare. Probably also works in Netscape as well as others like Safari.

<html>
<head>
<script type="text/javascript">
var obj;
var TAB = 9;
function catchTAB(evt,elem)
{
obj = elem;
var keyCode;
if ("which" in evt)
{// NN4 & FF &amp; Opera
keyCode=evt.which;
} else if ("keyCode" in evt)
{// Safari & IE4+
keyCode=evt.keyCode;
} else if ("keyCode" in window.event)
{// IE4+
keyCode=window.event.keyCode;
} else if ("which" in window.event)
{
keyCode=evt.which;
} else { alert("the browser don't support"); }

if (keyCode == TAB)
{
obj.value = obj.value + "\t";
alert("TAB was pressed");
setTimeout("obj.focus()",1);// the focus is set back to the text input
}
}
</script>
</head>
<body>
<input type="text" onkeydown="catchTAB(event,this);">
</body>
</html>

Hope this will help you. Happy coding!
Share
Labels: ,

How to show a client-side message box at the next page load in ASP.NET

Dec 17, 2009 Posted by Lara Kannan 0 comments
Showing a client-side message box at the next page load by use the below technique.

' Show a client-side message box at the next page load
' Example:
' ShowMessageBox(Me, "Order successfully submitted!")

public void ShowMessageBox(System.Web.UI.Page webPage, string message)
{
// replace ' with \', otherwise the resulting javascript may raise errors
message = message.Replace("'", "\\'");

// create the script and add it to the page's response
string script = "";
if ((!webPage.IsStartupScriptRegistered("StartupAlert")))
{
webPage.RegisterStartupScript("StartupAlert", script);
}
}

Happy Coding!
Share
Labels: , ,

How to assign a default value to a Password Control in ASP.NET

Dec 16, 2009 Posted by Lara Kannan 0 comments
If you set the TextMode property of a TextBox Web control to "Password" any default value you assign to the TextBox won't show up.

To work around this problem, add the following code to your ASP page:

There are two ways to initialize a TextBox whose TextMode is "password" with a default password:

Method 1 :-
<asp:TextBox TextMode="Password" id="txtPwd" RunAt="server"/>

<script language="C#" runat="server">
void Page_Load (Object sender, EventArgs e)
{
txtPwd.Attributes.Add ("value", "MyPassword");
}
</script>

Method 2 :-
<asp:TextBox Value="MyPassword" TextMode="Password" id="txtPwd" RunAt="server"/>

Happy coding!

Share
Labels: ,

How to change the Title in a Web Form at runtime in ASP.NET ?

Dec 15, 2009 Posted by Lara Kannan 0 comments
In ASP.NET, a web form's title is determined by the HTML View's Title attribute. However, there is no property in the default (or any other namespace) that helps you to change the title programmatically.

Here's a simple workaround to accomplish this:

  • 1. Modify the current <Title> tag so that it's accessible in the code, by adding the tag.

  • 2. Assign an ID to the <Title> tag. Your code should look like this:
    <title id="pgTitle">Default Title</title>

  • 3. Add it to the code:
    protected System.Web.UI.HtmlControls.HtmlGenericControl pgTitle;

  • 4. Change the title in the code, using its InnerText property.
    pgTitle.InnerText = "Changed Text"

Happy Coding!

Share
Labels: ,

C# codes that improve productivity - Part 2

Dec 14, 2009 Posted by Lara Kannan 0 comments
My early post, I explained five c# shorthands code tips. Again, I have listed another 5 C# shorthands that you can use to make your code too short.

Read my previous post at C# codes that improve productivity - Part 1

6. Nullable objects

A variable needs to have a value, it cannot be null. Sometimes it would be handy it was possible to assign "null" (eg. undefined) to a variable.

.NET 2.0 introduced the Nullable generic that makes this possible. The following two lines produce exactly the same object:
Nullable x = null;
int? x = null;

By putting a ? following a variable definition the compiler will wrap a Nullable generic around the type.

7. Automatic Properties

C# 3.0 introduced automatic properties. A property typically consists of a private variable which is exposed to the outside world through getters and setters (get;set;).

The following is common example of this:
public class Person
{
private string _firstName;
public string FirstName
{
get { return _firstName; }
set { _firstName = value; }
}
}

From C# 3.0 on we can reduce the above code to:
public class Person
{
public string Firstname { get; set; }
}

The C# compiler will automatically generate a backing variable and the correct get and set properties. Why is this useful? After all you could have just made a string variable in the class public instead.

By defining it as a property allows you to add the actual validation logic to your class at a later stage. The in-memory signature of the class won’t change which means that any external libraries compiled against your code will not have to be recompiled.

8. Type inference

In typical C# you will always carefully spell out your definitions:
string MyString = "Hello World";

From the right side of the declaration it is obvious that only one type (string) will ever match this definition. So instead of us doing the work, why not let the compiler figure this out?
var MyString = "Hello World";

The above definition will also create a string variable named "MyString". It is important to note that C# is still strongly typed.There is no performance impact results from using type inference.

The compiler does all the work figuring out the data type at compile time. Of course this feature created two opposite camps, one that thinks var should be liberally applied, and another one that abhors the whole idea. The middle ground seems to be that var should be used there were its use is obvious.
var SeniorStaff = Employees.Where(s => s.Age > 35);
foreach(var Member in SeniorStaff)
Console.WriteLine("Name: {0} Age: {1}",Member.Name,Member.Age);

For example what type would SeniorStaff be ?
((System.Linq.Enumerable.Iterator<<>f__AnonymousType0>)(SeniorStaff))

9. Lambda Expressions

C# 2.0 introduced anonymous methods, which are methods defined inside a method. Incredibly powerful and a nice way to put all kinds of evaluation logic inside your code they had the drawback that they could be quite hard to read.
Func mySeniorStaffFilter = delegate(int a) { return a > 35; }; 

The above method takes an integer as a parameter, and returns a boolean. It checks if the staff member passed to it is older than 35. If so, it returns true.

Lamba expressions make things a little easier to read, while being functionally exactly the same:
Func mySeniorStaffFilter = a => a > 35; 

Even better, you can define them anywhere a delegate would have fitted:
var SeniorStaff = Employees.Where(s => s.Age > 35); 

10. string.IsNullOrEmpty

Not really a language feature, but a useful little library function in its own right. How often do you need to test if a string is empty? Or null? The string.IsNullOrEmpty method returns true if this is the case.
if (String.IsNullOrEmpty(s) == true)
return "is null or empty";
else
return String.Format("(\"{0}\") is not null or empty", s);

Thanks : dijksterhuis

Hope this will help you. A 'Thank You' would be nice!

Share

C# codes that improve productivity - Part 1

Posted by Lara Kannan 0 comments
Below I have listed 5 C# shorthands that you can use to make your code tighter and less wordy. No doubt you know one or more already — but do you currently use all five of them ?

1. The ? conditional operator

It allows you to compress a common if-then-else pattern into a single assignment.
int x = 10;
int y = 20;
int max;

if (x > y)
max = x;
else
max = y;

Using the (Question) ? Positive Answer : Negative Answer patterns the above can be rewritten as:
int x = 10;
int y = 20;
int max = (x > y) ? x : y;

2. Null-Coalesce operator (??)

How often do you test for null values in your code? Often? Then the null-coalesce operator (??) comes in handy.

To see how it works consider the following code example:
object cache = null;
object d = new object();
object e;

if (c != null)
e = c; // c is an object
else
e = d;

t is obvious that we can rewrite this using the single ? operator :
object cache = null;
object d = new object();
object e = (c != null) ? c : d;

3. Object Initializers

After you create a new object you often have to assign one or more of its properties. With the introduction of C# 3.0 it is now possible to use object initializers to both improve the readability of this, and to shorten your code.
Customer c = new Customer();
c.Name = "James";
c.Address = "204 Lime Street";

can be re-written as:
Customer c = new Customer { Name="James", Address = "204 Lime Street" };

4. The using statement

Often you will need to allocate a system resource such as a font, file handle, network resource etc. Each time you need such a resource there are three critical steps to go through: You acquire the resource, you use it, and then you dispose of it.

If you forget to properly dispose of it you will have created a memory or resource leak. This is best illustrated through the following patterns:
// 1. Allocation of the object
Font font1 = new Font("Arial", 10.0f);
try
{
// 2. The bit where we use the resource
}
finally
{
// 3. Disposal of the object
if (font1 != null)
((IDisposable)font1).Dispose();
}

The using statement allows us to compress this down to:
// Allocate the resource
using (Font font1 = new Font("Arial", 10.0f))
{
// The bit where we use the resource
}
// Disposal is automatic

The using statement is intended to be used with objects that implement the "IDisposable" interface which in practice is all .NET objects that allocate and manage resources.

5. Aliases for long winded namespaces and types

The names of C# identifiers can become quite long. If you are doing Microsoft Office automation in C# you might want to do something simple like open MS Word and change a document. You can use the "using" statement to create an alias for either a class or a namespace.
using Word = Microsoft.Office.Interop.Word;
...
Word.Application = new Word.Application() { Visible = True; }

Thanks : dijksterhuis

Read more tips at C# codes that improve productivity - Part 2

Hope this will help you. A 'Thank You' would be nice!

Share

How to upload more than 4 MB of file in ASP.NET ?

Dec 12, 2009 Posted by Lara Kannan 0 comments
As many developers have found when uploading files from an FTP server or shared drive, by default, ASP.NET programs cannot upload a dataset from a file that exceeds 4MB.

Its possible by changing the value of maxRequestLength under the tag of <httpRuntime> in the web.config file.

<httpRuntime executionTimeout="420"  maxRequestLength="40960" />

Please note that the value is in KB.

I hope this will help you. A 'Thank You' would be nice!

Share
Labels: ,

How to cache dynamically generated images for quick page response in ASP.NET ?

Posted by Lara Kannan 0 comments
If you have an image gallery with dynamically generated thumbnails, you should make sure to tell the browser to cache the thumbnails.

If you don't, the page will download each image every time the browser visits, which stresses the CPU unnecessarily and causes the page to take longer to load. In contrast, when images are in the browser's cache, the page loads far faster.

If your image gallery contains multiple pages, the chances are good that users will visit the same page more than once. For returning visitors, the chances are even higher.

To enable browser caching, set the Last-Modified header in the .aspx or .ashx that you use to generate the thumbnails, using a date value so that the page always appears unmodified to the browser. Here's an example that sets the last modified date to one year ago:

Response.Cache.SetLastModified( DateTime.Now.AddYears(-1));

I hope this will help you. A 'Thank You' would be nice!

Share
Labels: , ,

How to create dynamic Hyperlinks from URLs Stored in Web.Config ?

Posted by Lara Kannan 0 comments
Consider storing any URLs used by your application in the web.config file where you can easily update them and then using them to create hyperlinks in your web site dynamically.

To do that, you need to decide exactly how to store and retrieve the URLs. Here's one method.

In the web.config file, create an entry like the one shown below:

<appSettings>
<add key="indexurl" value="http://www.index.aspx" />
</appSettings>

To read this entry from the web.config file, use AppSettings and the key attribute value of the entry, for example:

<asp:HyperLink ID="HyperLink1" runat="server"
NavigateUrl="<%$ Appsettings:indexurl %>" Text="Devx">
</asp:HyperLink>

I hope this will help you. A 'Thank You' would be nice!

Share
Labels: , ,

How to get the name of the current executing ASP.NET page ?

Posted by Lara Kannan 0 comments
To get the name of the executing ASP.NET Page from server-side code by using the namespace called System.IO.FileInfo.

See the below pices of C# code which will return the current executing asp.net page like default.aspx, home.aspx.
string sPagePath = System.Web.HttpContext.Current.Request.Url.AbsolutePath;

System.IO.FileInfo oFileInfo = new System.IO.FileInfo(sPagePath);
tring sPageName = oInfo.Name;

I hope this will help you. A 'Thank You' would be nice!

Share
Labels: , ,

How to access JavaScript variables on postback in ASP.NET ?

Posted by Lara Kannan 0 comments
When you want to access some value set in the browser in JavaScript code in your server-side code, you'll need to pass those values to the server during postback.

There's a simple and straightforward way to do that in ASP.NET. All you need to do is, place a Hidden field on your web page, and set the field's value in your JavaScript code.

See the sample code :
<html>
<head runat="server">
<title>Pass Javascript Variables to Server</title>
<script type="text/javascript">
function SetHiddenVariable()
{
var jsVar = "devx.com";
// Set the value of the hidden variable to
// the value of the javascript variable
var hiddenControl = '<%= inpHide.ClientID %>';
document.getElementById(hiddenControl).value=jsVar;
}
</script>
<body onload="SetHiddenVariable()">
<form id="form1" runat="server">
<div>
<input id="inpHide" type="hidden" runat="server" />
<asp:TextBox ID="txtJSValue" runat="server"></asp:TextBox>
<asp:Button ID="btnJSValue"
Text="Click to retrieve Javascript Variable"
runat="server" onclick="btnJSValue_Click"/>
</div>
</form>
</body>
</html>


Now you can access the value of the hidden field (Ex: inpHide) in your code-behind when the user submits / postback the page—in this case, with a button click as shown below:


protected void btnJSValue_Click(object sender, EventArgs e)
{
txtJSValue.Text = inpHide.Value;
}

In this example, the &lr;body> tag has an onload attribute that calls the JavaScript function that sets the hidden variable (&lr;body onload="SetHiddenVariable()">). But you don't have to set the hidden field value in the onload function; you can set it however you like—as long as you set the hidden field's value before you postback the page, you'll be able to access the value from the server-side code after the postback occurs.

I hope this will help you. A 'Thank You' would be nice!

Share
Labels: , ,

How to add metatags dynamically via ASP.NET ?

Posted by Lara Kannan 0 comments
Meta elements are typically used to specify page description, keywords, author of the document, last modified, and other metadata.

lt;meta> tags are a component of the invisible part of your HTML page — all that stuff between the <head> </head> tags.

The benefits of metatags is, the web search engines use them to categorize web pages.

To add metatags dynamically, ASP.NET provides a handy class called HtmlMeta, from the System.Web.UI.HtmlControls namespace.

Here's some sample C# code that shows how to add a meta tag to an ASP.NET page:
protected void Page_Load(object sender, EventArgs e)
{
/* ... some other code .... */

System.Web.UI.HtmlControls.HtmlMeta htmlMeta =
new System.Web.UI.HtmlControls.HtmlMeta();
htmlMeta.Name = "keyword";
htmlMeta.Content = "This is a keyword";
Page.Header.Controls.Add(htmlMeta);

/* ... some other code .... */
}
The preceding code creates an HtmlMeta object and sets its Name and Content properties, then adds the HtmlMeta object to the Page.Header.Controls collection. This instructs ASP.NET to place the HTML metatag in the HEAD block.

Here's an example:

<!-- Head contents come before this... -->
<meta name="keyword" content="This is a keyword" />
</head>

I hope this will help you. A 'Thank You' would be nice!

Share
Labels: , ,

How to convert from signed integer / decimal to RGB in Realbasic ?

Dec 8, 2009 Posted by Lara Kannan 0 comments

Last Monday, I faced one color conversion issue in my RealBasic application. That is, how to convert from the signed integer to RGB color in REALBASIC?. There is no stright forward funtion available in Realbasic.

Luckly, I got one clue from the Realbasic forum. I am not too sure if this is absolutely correct; but I have tried this with some of the decimals and I am getting the correct RGB value.


Solution for decimal to RGB conversion :

Private Function Convert_Dec2RGB(ByVal myDECIMAL As Long) As String
Dim myRED As Long
Dim myGREEN As Long
Dim myBLUE As Long

myRED = myDECIMAL And &HFF
myGREEN = (myDECIMAL And &HFF00&) \ 256
myBLUE = myDECIMAL \ 65536

Convert_Dec2RGB = CStr(myRED) & "," & CStr(myGREEN) & "," & CStr(myBLUE)
End Sub

Solution for signed integer to RGB conversion:

Private Function Convert_sInteger2RGB(ByVal myDECIMAL As Long) As Color
Dim newRGB as Variant
newRGB = myDECIMAL
Convert_sInteger2RGB = newRGB.ColorValue
End Sub

Let me know if you have any comment or feedback on this.


I hope this ll help you. A 'Thank You' would be nice!

Share
Labels:

Globally register User and Custom Controls in ASP.NET

Posted by Lara Kannan 1 comments

In previous versions of ASP.NET, to import and use user or custom controls on a page, you needed to add a page directive (<%@ Register %>) in the .aspx code for that page.

Fortunately, ASP.NET 2.0 and later versions introduced a shortcut that makes managing the controls much easier. Rather than declaring them on every page, you can declare them once, in your web.config file, and then use them in your entire project.

Register your controls in web.config as shown below. The example assumes that there is a user control named table.ascx in the project:


<configuration>
<system.web>
<pages>
<controls>
<addtagPrefix="uc" tagName="table" src="table.ascx" />
<!-- Add other user/custom control references here -->
</controls >
</pages >
</system.web>
</configuration>

You can now use the table.ascx user control on any page—without explicitly adding a Register directive on the page. Here's a short example:


<body>
<form id="form1" runat="server">
<div>
<uc:table ID="Table1" runat="server" />
</div>
</form>
</body>

Thanks : devx.com

I hope this will help you. A 'Thank You' would be nice!

Share
Labels: ,