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: ,

Whats mean by 'Stand up meeting' ?

Nov 17, 2009 Posted by Lara Kannan 0 comments
Start doing daily stand up meeting in Agile programming method

A daily standup meeting is one of the easiest practices you can implement with your team. It only takes 10-15 minutes at the beginning of each day, and it increases the amount of communication and synchronization in the team immensely.

The idea is very simple...

The whole team (usually no more than 10 people) literally stands up in a sort of circle so everyone can see each other. then the team lead (or the "facilitator" that was chosen for the team) will go one by one and ask each team member three simple questions:

1. What did you do yesterday?
2. What are you going to do today?
3. Is there anything stopping you from getting your work done?

Question #1 is important for several reasons:

  • Everyone hears what happened yesterday and know the current status on that part of the app that member worked on

  • The team lead understands the progress of the team member and the overall status of the app

  • If the team member didn't get anything really done yesterday, it might mean they are stuck - which is very important to know early as we've seen.

Question #2 also has its uses:

  • The team member stands up in front of their own peers and says they will do something. They will feel more responsibility to make sure those things get accomplished. they are now accountable to the team.

  • If they do not know what to do today, that's also good since you've caught this early. make sure they know what to do. If there is a task board, they can grab the task with the highest priority, for example.

  • Other team members will know what is going on, can offer help or tips (maybe they worked on this just the other day?)

Question #3 is very important to prevent bottlenecks in the team productivity

  • maybe someone's computer is overheating, or has low memory

  • maybe a team member needs to take half a day since some other project called them

  • maybe... you get the idea

it is your job as a team lead to make sure nothing is stopping team members from working on the things with the highest value to the project(s) they are working on. If they are not, find out why and solve it immediately after the meeting.

5 useful tips I learned the hard way

  1. Make sure it does not take longer than 15 minutes (that's why standing up is important - people don't feel comfortable ranting on when they stand up so things finish up quickly)

  2. Make sure that technical discussions do not ensue in the middle of the meeting. when one breaks out call it out as a "talk about this later, just the both of you" and ask people to move on

  3. When all else fails, you can tell the person who won't stop talking - "you have 30 seconds to finish your overview" and then move on.

  4. Don't be afraid to stop people in the middle of speaking. The rules must be clear and concise.

  5. Once you have this meeting, try to see what meetings you can now cancelfor the whole team. For example, in our company we have only two meetings a week where the whole dev team needs to be in: daily standup, and once a week a company meeting. besides those they are just at work, working.
Thanks :5whys.com

Happy Programming!!!

Share your thoughts with me !!! A 'Thank You' would be nice!

Share

ASP.NET - Stylish submit buttons

Sep 21, 2009 Posted by Lara Kannan 0 comments
Most people would agree the default look of submit buttons is rather dull and unattractive. Using CSS and a nice gradient background image, it's easy to transform a form button from a duck to a swan.

Demo:

<style type="text/css">
.formbutton{
cursor:pointer;
border:outset 1px #ccc;
background:#999;
color:#666;
font-weight:bold;
padding: 1px 2px;
background:url(formbg.gif) repeat-x left top;
}
</style>

The image used:


<form>
<input type="text" style="width: 200px; border: 1px solid gray" />
<input type="submit" class="formbutton" value="Submit" />
</form>
I hope this ll help you. A 'Thank You' would be nice!

Share
Labels:

ASP.NET : Dynamically change a style at Run-Time

Posted by Lara Kannan 0 comments
A nice feature of CSS is the ability to assign multiple classes to can DOM element via the class attribute. This opens up the possibility to dynamically set a class assignment based on some logic as the page is being rendered.

The example below demonstrates having a common style rule and a rule added at run-time. Of course you are not limited to this methodology, there are many ways to apply styles to an element.
<div class="contentBox bkg1">...</div>
I find the solution from Chris blog, for easiest way to set something like a dynamic style at run-time is to define a public method in the page class to return the desired rule. For my demonstration I will return a style rule name based on a QueryString parameter, but you can use all sorts of criteria. I also chose to apply the rule to the Body tag.

This is a simple method to return a style rule to define the background color of the page. I have three rules defined.
public string GetBackgroundClass()
{
switch ( Request.QueryString["bkg"])
{
case "1":
return "bkg1";
case "2":
return "bkg2";
case "3":
return "bkg3";
default:
return "bkg1";
}
}
The style rules just set the color as follows, a nice egg shell (at least that is what I call it), red and blue.
.bkg1
{
background-color: #FFFFCC;
}

.bkg2
{
background-color: #C30000;
}

.bkg3
{
background-color: #0000CC;
}
Finally I just inline the call to the method in the HTML markup:
<body class="<%=GetBackgroundClass() %>">
I hope this ll help you. A 'Thank You' would be nice!

Share
Labels: ,

Split camelCase string in C#

Sep 10, 2009 Posted by Lara Kannan 0 comments
Recently in our project there was a requirement were in the validation of the large number text boxes were required to be done.

We were following the camel casing as a naming convection for the text box. Mention below function was used to break the camel case and show the appropriate message to the user.

You require passing the camel case string to the function SplitCamelCase and it will return the necessary string.

public string SplitCamelCase(string CamelCaseString)
{
return System.Text.RegularExpressions.Regex.Replace(CamelCaseString,
"([A-Z])",
" $1",
System.Text.RegularExpressions.RegexOptions.Compiled
).Trim();
}

Hope this helps.
Share
Labels:

Auto click a button in asp.net on page load event

Sep 5, 2009 Posted by Lara Kannan 0 comments
In page load event itself, you just call the that button click event.

private void Page_Load(object sender, System.EventArgs e)
{
Button1_Click(null, null); // This button event ll fire while page load.
}

This code will execute the button click event also, when page load event executes.
Share
Labels: ,

WCF - Interview Questions Part 3

Jun 30, 2009 Posted by Lara Kannan 0 comments
  1. Explain transactions in WCF.
    Transactions in WCF allow several components to concurrently participate in an operation. Transactions are a group of operations that are atomic, consistent, isolated and durable. WCF has features that allow distributed transactions. Application config file can be used for setting transaction timeouts.

  2. What are different isolation levels provided in WCF?
    The different isolation levels:

    1. READ UNCOMMITTED: - An uncommitted transaction can be read. This transaction can be rolled back later.

    2. READ COMMITTED :- Will not read data of a transaction that has not been committed yet

    3. REPEATABLE READ: - Locks placed on all data and another transaction cannot read.

    4. SERIALIZABLE:- Does not allow other transactions to insert or update data until the transaction is complete.

  3. Explain transactions in WCF.
    Transactions in WCF allow several components to concurrently participate in an operation. Transactions are a group of operations that are atomic, consistent, isolated and durable. WCF has features that allow distributed transactions. Application config file can be used for setting transaction timeouts.

  4. How do I serialize entities using WCF?
    LINQ to SQL supports serialization as XML via WCF by generating WCF serialization attributes and special serialization specific logic during code-generation. You can turn on this feature in the designer by setting serialization mode to ‘Unidirectional’. Note this is not a general solution for serialization as unidirectional mode may be insufficient for many use cases.

  5. What is End point ?
    Every service must have Address that defines where the service resides, Contract that defines what the service does and a Binding that defines how to communicate with the service. In WCF the relationship between Address, Contract and Binding is called Endpoint.

    The Endpoint is the fusion of Address, Contract and Binding.


Happy Interview!!!
Share
Labels: ,

WCF - Interview Questions Part 2

Posted by Lara Kannan 0 comments
  1. What is address in WCF and how many types of transport schemas are there in WCF?
    Address is a way of letting client know that where a service is located. In WCF, every service is associated with a unique address. This contains the location of the service and transport schemas. WCF supports following transport schemas

    1. HTTP
    2. TCP
    3. Peer network
    4. IPC (Inter-Process Communication over named pipes)
    5. MSMQ

    The sample address for above transport schema may look like

    http://localhost:81
    http://localhost:81/MyService
    net.tcp://localhost:82/MyService
    net.pipe://localhost/MyPipeService
    net.msmq://localhost/private/MyMsMqService
    net.msmq://localhost/MyMsMqService

  2. What is the difference WCF and Web services?
    1. Web services can only be invoked by HTTP. While Service or a WCF component can be invoked by any protocol and any transport type.

    2. Second web services are not flexible. But Services are flexible. If you make a new version of the service then you need to just expose a new end point. So services are agile and which is a very practical approach looking at the current business trends.

  3. How can we host a service on two different protocols on a single server?
    Let’s first understand what this question actually means. Let’s say we have made a service and we want to host this service using HTTP as well as TCP.

    You must be wondering why to ever host services on two different types of protocol. When we host a service it’s consumed by multiple types of client and it’s very much possible that they have there own protocol of communication. A good service has the capability to downgrade or upgrade its protocol according the client who is consuming him.

    Let’s do a small sample in which we will host the ServiceGetCost on TCP and HTTP protocol.

    Once we are done the server side coding its time to see make a client by which we can switch between the protocols and see the results. Below is the code snippet of the client side for multi-protocol hosting

  4. How does WCF work?
    Follows the 'software as a service' model, where all units of functionality are defined as services.

    A WCF Service is a program that exposes a collection of Endpoints. Each Endpoint is a portal (connection) for communication with either clients (applications) or other services.

    Enables greater design flexibility and extensibility of distributed systems architectures.

    A WCF application is represented as a collection of services with multiple entry points for communications.

  5. What are the main components of WCF?

    1.Service: The working logic or offering, implemented using any .Net Language(C#).

    2.Host: The environment where the service is parked. E.g. exe, process, windows service

    3.Endpoints: The way a service is exposed to outside world.

    Following figure shows us all the core components.

Happy Interview!!!
Share
Labels: ,

WCF - Interview Questions Part 1

Posted by Lara Kannan 0 comments
  1. What is WCF?
    Windows Communication Foundation (WCF) is an SDK for developing and deploying services on Windows. WCF provides a runtime environment for services, enabling you to expose CLR types as services, and to consume other services as CLR types.

    WCF is part of .NET 3.0 and requires .NET 2.0, so it can only run on systems that support it. WCF is Microsoft's unified programming model for building service-oriented applications with managed code. It extends the .NET Framework to enable developers to build secure and reliable transacted Web services that integrate across platforms and interoperate with existing investments.

    Windows Communication Foundation combines and extends the capabilities of existing Microsoft distributed systems technologies, including Enterprise Services, System.Messaging, Microsoft .NET Remoting, ASMX, and WSE to deliver a unified development experience across multiple axes, including distance (cross-process, cross-machine, cross-subnet, cross-intranet, cross-Internet), topologies (farms, fire-walled, content-routed, dynamic), hosts (ASP.NET, EXE, Windows Presentation Foundation, Windows Forms, NT Service, COM+), protocols (TCP, HTTP, cross-process, custom), and security models (SAML, Kerberos, X509, username/password, custom).

  2. What is service and client in perspective of data communication?
    A service is a unit of functionality exposed to the world. The client of a service is merely the party consuming the service.

  3. What is endpoint in WCF? or What is three major points in WCF?
    Every service must have Address that defines where the service resides, Contract that defines what the service does and a Binding that defines how to communicate with the service.

    In WCF the relationship between Address, Contract and Binding is called Endpoint. The Endpoint is the fusion of Address, Contract and Binding.

    1. Address : Specifies the location of the service which will be like http://Myserver/MyService.Clients will use this location to communicate with our service.

    2. Contract : Specifies the interface between client and the server.It's a simple interface with some attribute.

    3. Binding : Specifies how the two paries will communicate in term of transport and encoding and protocols.
  4. What is binding and how many types of bindings are there in WCF?
    A binding defines how an endpoint communicates to the world. A binding defines the transport (such as HTTP or TCP) and the encoding being used (such as text or binary).

    A binding can contain binding elements that specify details like the security mechanisms used to secure messages, or the message pattern used by an endpoint.

    WCF supports nine types of bindings.

    1. Basic binding :
      Offered by the BasicHttpBinding class, this is designed to expose a WCF service as a legacy ASMX web service, so that old clients can work with new services. When used by the client, this binding enables new WCF clients to work with old ASMX services.


    2. TCP binding :
      Offered by the NetTcpBinding class, this uses TCP for cross-machine communication on the intranet. It supports a variety of features, including reliability, transactions, and security, and is optimized for WCF-to-WCF communication. As a result, it requires both the client and the service to use WCF.

    3. Peer network binding :
      Offered by the NetPeerTcpBinding class, this uses peer networking as a transport. The peer network-enabled client and services all subscribe to the same grid and broadcast messages to it.

    4. IPC binding :
      Offered by the NetNamedPipeBinding class, this uses named pipes as a transport for same-machine communication. It is the most secure binding since it cannot accept calls from outside the machine and it supports a variety of features similar to the TCP binding.

    5. Web Service (WS) binding :
      Offered by the WSHttpBinding class, this uses HTTP or HTTPS for transport, and is designed to offer a variety of features such as reliability, transactions, and security over the Internet.

    6. Federated WS binding :
      Offered by the WSFederationHttpBinding class, this is a specialization of the WS binding, offering support for federated security.

    7. Duplex WS binding :
      Offered by the WSDualHttpBinding class, this is similar to the WS binding except it also supports bidirectional communication from the service to the client.

    8. MSMQ binding :
      Offered by the NetMsmqBinding class, this uses MSMQ for transport and is designed to offer support for disconnected queued calls.

    9. MSMQ integration binding :
      Offered by the MsmqIntegrationBinding class, this converts WCF messages to and from MSMQ messages, and is designed to interoperate with legacy MSMQ clients.
  5. What is contracts in WCF?
    In WCF, all services expose contracts. The contract is a platform-neutral and standard way of describing what the service does.

    WCF defines four types of contracts.

    1. Service contracts : Describe which operations the client can perform on the service.

    2. Data contracts : Define which data types are passed to and from the service. WCF defines implicit contracts for built-in types such as int and string, but we can easily define explicit opt-in data contracts for custom types.

    3. Fault contracts : Define which errors are raised by the service, and how the service handles and propagates errors to its clients.

    4. Message contracts : Allow the service to interact directly with messages. Message contracts can be typed or untyped, and are useful in interoperability cases and when there is an existing message format we have to comply with.

Happy Interview!!!
Share
Labels: ,

WCF Performance: Making your service run 3 times faster

Posted by Lara Kannan 0 comments
Wisely changing WCF defaults can yield a significant improvement in your service performance. The exact changes need to be made and their exact effect are dependent in the scenario. The example below how to speed up a certain service 3 times faster.

Read more at http://webservices20.blogspot.com/2009/01/wcf-performance-gearing-up-your-service.html

Share
Labels: ,

Java Script : 'toFixed' Math function for number format

Posted by Lara Kannan 0 comments
<div style="text-align: justify;">We can use 'toFixed()' function in math to format a number upto required decimal places. The value we get is after rounding the number upto the decimal place required. This function is frequently used in java script. </div>

Here is the syntax.
my_val.toFixed(4)

my_val is the variable which stores the number. Here we are formatting the number upto 4 decimal places.

Let us try with some examples with different number values.
var my_val=11.257;
document.write (my_val.toFixed(2)); // output 11.26

var my_val=11.25;
document.write (my_val.toFixed(1)); // output 11.3

var my_val=11.978;
document.write (my_val.toFixed(4)); // output 11.9780

Use the tips!
Share
Labels:

How to Drop Primary Key Contraint from a Table

Posted by Lara Kannan 0 comments
First, we will create a table that has primary key. Next, we will drop the primary key successfully using the correct syntax of SQL Server.

CREATE TABLE Table1(
Col1 INT NOT NULL,
Col2 VARCHAR(100)
CONSTRAINT PK_Table1_Col1 PRIMARY KEY CLUSTERED (
Col1 ASC)
)
GO

Second, try to drop the primary key constraint using following lines.

/* For SQL Server/Oracle/MS ACCESS */
ALTER TABLE Table1
DROP CONSTRAINT PK_Table1_Col1
GO

/* For MySql */
ALTER TABLE Table1
DROP PRIMARY KEY
GO

Use the tips!!!
Share
Labels:

Automatic Thumbnail and Read More Function for Blogger

Posted by Lara Kannan 0 comments
Read more function is used to cut our post on homepage, post will appear fully when we click read more link. It's cut automatically and if we insert image, it appears thumbnail.
This is automatic read more function with thumbnail. We just need to set up our HTML code.

Follow steps:
1. Go to "Layout" click "Edit HTML"

2. Tick on "Expand Widget Templates"

3. Find this code : <data:post.body/>(Using Ctrl + F)

4. Replace with this code below

<script type='text/javascript'>
summary_noimg = 430;
summary_img = 340;
img_thumb_height = 100;
img_thumb_width = 120;
</script>

<script src='http://ankitbajaj151.googlepages.com/readmore.js' type='text/javascript'/>
<b:if cond='data:blog.pageType != &quot;item&quot;'>
<div expr:id='&quot;summary&quot; + data:post.id'><data:post.body/>
</div>
<script type='text/javascript' >createSummaryAndThumb(&quot;summary <data:post.id/>&quot;);
</script>

<span class='rmlink' style='float:right'> <a expr:href='data:post.url' >Read more</a> </span>
</b:if>
<b:if cond='data:blog.pageType == &quot;item&quot;'> <data:post.body/> </b:if>

5. Save / Check your blog

Note:
If you need help to install it or to customize it, pls contact here.

If you like this post, say thanks.
Share

To Create a DropDown List from an ENUM

Jun 29, 2009 Posted by Lara Kannan 0 comments
You have an 'enum' defined as follows:
public enum CompanyAddressType
{
Unknown = 0,
Primary = 1,
Warehouse = 2,
Distribution_Center = 3,
Cross_Dock = 4
}

You want to iterate through the list and put the data into an asp.net dropdownlist.

Here is the simple code:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
string[] names = Enum.GetNames(typeof(CompanyAddressType));
var values = (CompanyAddressType[])Enum.GetValues(typeof(CompanyAddressType));
for (int i = 0; i < names.Length; i++)
{
DropDownListCompanyAddressType.Items.Add(
new ListItem(names[i], values.ToString()));
}
}
}

There are probably easier ways to do it, but this works.

Use the tips!

If you like this post, say thank!
Share
Labels: , ,