Sunday, December 21, 2008

Javascript:Window.Open Invalid Argument Error IE

Internet Explorer (IE) starts giving Javascript error when I tried to open Pop-up Dialog, Which works perfect with Fire Fox and Chrome.


So If you are getting javascript error in IE on doing Javascript:Window.Open

Javascript Error: Invalid Argument or Syntax Error 
Example: (In Asp.net Code Behind)
string url = "MyTestURL?qsTestId=" + TestId;

string winFeatures = "toolbar=no,status=no,menubar=no,height=400,width=400";

string winPoPUpScript = string.Format("javascript:window.open('{0}', 'My Test Popup', '{1}');", url, winFeatures);

lnkCounter.Attributes.Add("onclick", winPoPUpScript);

Opening Window.open with javascript works perfectly with Firefox and Chrome, but will give error with IE.

Solution (Quick Fix): 
You need to remove spaces from 2nd Argument of Javascript Function Window.open() to make it work with IE.   If your second argument of Window.Open contains spaces than you may receive javascript errors like Invalid Argument or Syntax Error. 

To Fix the above code we need remove spaces from 2nd argument of Window.open
Example: (In Asp.net Code Behind)
string url = "MyTestURL?qsTestId=" + TestId;

string winFeatures = "toolbar=no,status=no,menubar=no,height=400,width=400";

string winPoPUpScript = string.Format("javascript:window.open('{0}', 'MyTestPopup', '{1}');", url, winFeatures);

lnkCounter.Attributes.Add("onclick", winPoPUpScript);

Sunday, December 14, 2008

Maintain Scroll Position Rating Control Ajax

Update to my previous post Rating Control Ajax - Display Message on Rating

Ajax Rating Control has bug, that is whenever user clicks the rating control, page causes jumps to top of the page. To avoid jump to top of page when user clicks Rating Control you need to add following line.

Add following line to maintain scroll position of page after user clicks rating control asp.net ajax.


protected void Page_Load(object sender, EventArgs e)
{
Rating1.Attributes.Add("onclick", "return false;");
}

For Detailed explanation about why Rating control jumps to top of page when user clicks on Rating control

Saturday, December 13, 2008

MSXML to System.xml with C# - XSL Transformation

Good Link for XSLT Transformation

XSL Transformation


This step-by-step article describes the features of MSXML and .NET Framework Classes for XML processing. This article also includes samples on how to use MSXML in Microsoft Visual Basic 6.0 and how to use .NET Framework Classes for XML processing.

http://support.microsoft.com/kb/330589

This article mainly focus on following
  • MSXML vs. System.xml for XML Processing
  • XSL Transformation
  • XML Validation
  • XML Navigation

Wednesday, December 10, 2008

Reflection in C# - List of Class Name, Method Name

Reflection is way through which we can identify metadata about assembly runtime.
Example: We have a .Net Assembly file (.dll file), which consist of 2 Class Definition and 10 Method Names, We can get information about classes and method name list through reflection.

Few Examples of Reflection

Loading Assembly FileAssembly assem = Assembly.LoadFrom(sAssemblyFileName);

Get List of Class Name.
Type[] types = assem.GetTypes();

Get List of Method Name


foreach (Type cls in types)
{
try
{
//Add Namespace Name
arrl.Add(cls.FullName);

//Add Class Name
if(cls.IsAbstract)
arrl.Add("Abstract Class:" + cls.Name.ToString());
else if(cls.IsPublic)
arrl.Add("Public Class:" + cls.Name.ToString());
else if(cls.IsSealed)
arrl.Add("Sealed Class:" + cls.Name.ToString());


MemberInfo[] methodName = cls.GetMethods();
foreach (MemberInfo method in methodName)
{
if (method.ReflectedType.IsPublic)
arrl.Add("\tPublic - " + method.Name.ToString());
else
arrl.Add("\tNon-Public - " + method.Name.ToString());
}
}
catch (System.NullReferenceException)
{
Console.WriteLine("Error msg");
}
}


A Sample Application Showing Good Usage of Reflection in .Net
Following application shows how to identify list of Classes and Method in any .Net Assembly file with the help of .Net Reflection. For an example I am using Ajax Assembly filename to list all its classname and method name.



Step 1: Design a web form consisting of following controls.
Label – Shows text “Assembly File Name”
Textbox – Taking Input Assembly File Name.
Listbox – For displaying list of Class Names and Method Names
Button – On Button Click Event Display List of Class Name and Method Name

Step 2: Write following code on Button_Click Event.


private void btnListMethodName_Click(object sender, EventArgs e)
{
string sAssemblyFileName = txtAssemblyFileName.Text;

if (sAssemblyFileName.Length != 0)
{
Assembly assem = Assembly.LoadFrom(sAssemblyFileName);
Type[] types = assem.GetTypes();
ArrayList arrl = new ArrayList();
foreach (Type cls in types)
{
try
{
//Add Class Name
arrl.Add(cls.FullName);
if(cls.IsAbstract)
arrl.Add("Abstract Class:" + cls.Name.ToString());
else if(cls.IsPublic)
arrl.Add("Public Class:" + cls.Name.ToString());
else if(cls.IsSealed)
arrl.Add("Sealed Class:" + cls.Name.ToString());

MemberInfo[] methodName = cls.GetMethods();
foreach (MemberInfo method in methodName)
{
//arrl.Add("\t" + method.Name.ToString());
if (method.ReflectedType.IsPublic)
arrl.Add("\tPublic - " + method.Name.ToString());
else
arrl.Add("\tNon-Public - " + method.Name.ToString());
}
}
catch (System.NullReferenceException)
{
Console.WriteLine("Error msg");
}
}

//Dump Data to NotePad File
FileStream fs = new FileStream(@"c:\myData.txt", FileMode.Create, FileAccess.Write, FileShare.ReadWrite);
StreamWriter sw = new StreamWriter(fs);
for (int i = 0; i < arrl.Count; i++)
{
lstInfo.Items.Add(arrl[i].ToString());
sw.WriteLine(arrl[i].ToString());
}
sw.Flush();
sw.Close();
}
}

Thursday, December 04, 2008

Rating Control Ajax - Display Message on Rating

One Famous Problem with Rating Control is How to Display Message after Rating is done, without making use of button click.

Following Images Explain How can we display label text on Rating Control Click, without explicitly clicking any button control.

Before Rating Control is Clicked


During Rating Control is Clicked


After Rating Control is Clicked


Now, lets understand how to display message on click of Star Image.

Step1: Declare CSS Styles in Style Sheet file Also Add Images to Image Folder


.ratingStar {
font-size: 0pt;
width: 31px;
height: 30px;
margin: 0px;
padding: 0px;
cursor: pointer;
display: block;
background-repeat: no-repeat;
}

.filledRatingStar {
background-image: url(Images/FilledStar.png);

}

.emptyRatingStar {
background-image: url(Images/EmptyStar.png);
}

.savedRatingStar {
background-image: url(Images/SavedStar.png);
}


Step2: Declare ScriptManager in .aspx file with EnablePartialRendering=true

<asp:ScriptManager ID="ScriptManager1" EnablePartialRendering="true" runat="server">
</asp:ScriptManager>

Step3: Declare UpdatePannel

<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<!-- Declare Rating Control Here -->
</ContentTemplate>
</asp:UpdatePanel>

Step4: Add Rating Control and Label in UpdatePannel

<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<!-- Rating Control -->
<cc1:Rating ID="Rating1" runat="server"
BehaviorID="RatingBhvrId1"
CurrentRating="3"
MaxRating="5"
StarCssClass="ratingStar"
WaitingStarCssClass="savedRatingStar"
FilledStarCssClass="filledRatingStar"
EmptyStarCssClass="emptyRatingStar"
OnChanged="Rating1_Changed"
ToolTip="Please Rate!"
style="float:left;">
</cc1:Rating>

<!-- Label to Display Message -->
<span id="lblResponse" class="heading"></span>
</ContentTemplate>
</asp:UpdatePanel>

Step5: Declare Necessary Javascript to show "Message" after user performs Rating with the help of e.CallbackResult

<script language="javascript" type="text/javascript">
Sys.Application.add_load(function()
{
$find("RatingBhvrId1").add_EndClientCallback(function(sender, e)
{
var lblCtrl = document.getElementById('lblResponse');
lblCtrl.innerHTML = e.get_CallbackResult();
});
});
</script>
Step6: Declaring Rating1_Changed Event
protected void Rating1_Changed(object sender, AjaxControlToolkit.RatingEventArgs e)
{
System.Threading.Thread.Sleep(500);
int iRate = Convert.ToInt16(e.Value);
string strMessage = string.Empty;
switch (iRate)
{
case 1:
strMessage = "Not Useful";
break;
case 2:
strMessage = "Average";
break;
case 3:
strMessage = "Useful";
break;
case 4:
strMessage = "Informative";
break;
case 5:
strMessage = "Excellent";
break;
}
strMessage = "Thanks for Rating, You found this Question " + strMessage;
e.CallbackResult = strMessage;
}

Summary View of .aspx Page

<asp:ScriptManager ID="ScriptManager1" EnablePartialRendering="true" runat="server">
</asp:ScriptManager>

<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<cc1:Rating ID="Rating1" runat="server"
BehaviorID="RatingBhvrId1"
CurrentRating="3"
MaxRating="5"
StarCssClass="ratingStar"
WaitingStarCssClass="savedRatingStar"
FilledStarCssClass="filledRatingStar"
EmptyStarCssClass="emptyRatingStar"
OnChanged="Rating1_Changed"
ToolTip="Please Rate!"
style="float:left;">
</cc1:Rating>
<br />
<span id="lblResponse" class="heading"></span>
<script language="javascript" type="text/javascript">
Sys.Application.add_load(function()
{
$find("RatingBhvrId1").add_EndClientCallback(function(sender, e)
{
var lblCtrl = document.getElementById('lblResponse');
lblCtrl.innerHTML = e.get_CallbackResult();
});
});
</script>
</ContentTemplate>
</asp:UpdatePanel>

Thursday, November 13, 2008

Finding All Controls on Page in Asp.net

Finding All Controls on Page in Asp.net

To find all controls on Page, including child controls. i.e. Loop through all control list.

Example: I have a page with Controls on Page, Pannel Controls (Which contains Few more child controls). Now I want to find list of all controls on Page including child control.




private void ListControlCollections()
{
ArrayList controlList = new ArrayList();
AddControls(Page.Controls,controlList);

foreach (string str in controlList)
{
Response.Write(str + "<br/>");
}
Response.Write("Total Controls:" + controlList.Count);
}

private void AddControls(ControlCollection page,ArrayList controlList)
{
foreach (Control c in page)
{
if (c.ID != null)
{
controlList.Add(c.ID);
}

if(c.HasControls())
{
AddControls(c.Controls, controlList);
}
}
}
//OUTPUT of Code
form1
Panel1
Label1
TextBox1
Label2
TextBox2
Label3
TextBox3
Label10
TextBox10
Label11
TextBox11
Label12
TextBox12
btnControls
lblResult
Total Controls:16

Tuesday, October 28, 2008

Rhino Mocks Tutorial - Unit Testing

Tutorial Link for understanding Rhino Mocks

What is Rhino Mocks
Rhino.Mocks is an attempt to create easier way to build and use mock objects and allow better refactoring support from the current tools. It's a hybrid approach between the pure Record/Replay of EasyMock.Net's model and NMock's expectation based model. Rhino.Mocks originated from EasyMock.Net and attempt to improve on their model to create easy to use and power mocking framework. It's free for use and modification for open source and commercial software.

Rhino.Mocks is an attempt to create easier way to build and use mock objects and allow better refactoring support from the current tools. It's a hybrid approach between the pure Record/Replay of EasyMock.Net's model and NMock's expectation based model. Rhino.Mocks originated from EasyMock.Net and attempt to improve on their model to create easy to use and power mocking framework. It's free for use and modification for open source and commercial software.Rhino.Mocks is an attempt to create easier way to build and use mock objects and allow better refactoring support from the current tools. It's a hybrid approach between the pure Record/Replay of EasyMock.Net's model and NMock's expectation based model. Rhino.Mocks originated from EasyMock.Net and attempt to improve on their model to create easy to use and power mocking framework. It's free for use and modification for open source and commercial software.

Rhino.Mocks is an attempt to create easier way to build and use mock objects and allow better refactoring support from the current tools. It's a hybrid approach between the pure Record/Replay of EasyMock.Net's model and NMock's expectation based model. Rhino.Mocks originated from EasyMock.Net and attempt to improve on their model to create easy to use and power mocking framework. It's free for use and modification for open source and commercial software.

Rhino Mocks Tutorial

Useful Links for Rhino Mocks

Download Visual Studio 2010

Download Visual Studio 2010 Beta Version

VS.Net 2010 Features Good Links and Highlights


https://connect.microsoft.com/VisualStudio/content/content.aspx?ContentID=9790

Application Architecture Guide Book for Microsoft .Net Patterns and Practise

Application Architecture Guide Book for Microsoft .Net Patterns and Practise V2.0 is Released (Beta 1)

Download Book Application Architechture Guide V2.0

Index of Application Architecture Guide Book

Parts
Part I, Fundamentals of Application Architecture
Part II, Design
Part III, Layers
Part IV, Quality Attributes
Part V, Archetypes - Design and Patterns

Chapters
Introduction
Architecture Best Practices At a Glance
Fast Track - A Guide for Getting Started and Applying the Guidance

Part I, Fundamentals of Application Architecture
Chapter 1 - Fundamentals of Application Architecture
Chapter 2 - .NET Platform Overview
Chapter 3 - Application Archetypes
Chapter 4 - Deployment Patterns
Chapter 5 - Architectural Styles
Chapter 6 - Quality Attributes
Chapter 7 - Layers and Tiers

Part II, Design
Chapter 8 - Designing Your Architecture
Chapter 9 - Architecture and Design Guidelines
Chapter 10 - Designing Services
Chapter 11 - Communication Guidelines

Part III, Layers
Chapter 12 - Presentation Layer Guidelines
Chapter 13 - Business Layer Guidelines
Chapter 14 - Data Access Layer Guidelines
Chapter 15 - Service Layer Guidelines

Part IV, Quality Attributes
Chapter 16 - Performance Engineering
Chapter 17 - Security Engineering

Part V, Archetypes - Design and Patterns
Chapter 18 - Mobile Application
Chapter 19 - Office Business Application (OBA)
Chapter 20 - Rich Client Application
Chapter 21 - Rich Internet Application (RIA)
Chapter 22 - Service Archetype
Chapter 23 - SharePoint LOB Application
Chapter 24 - Web Application

Appendix
Cheat Sheet - patterns & practices Catalog at a Glance
Cheat Sheet - patterns & practices Pattern Catalog
Cheat Sheet - patterns & practices Enterprise Library

Wednesday, October 08, 2008

Browser Independent Web Application

Checklist for making Browser Independent Web Application

http://developer.mozilla.org/En/Migrate_apps_from_Internet_Explorer_to_Mozilla

Mozilla Developer community is recommending following tips to make browser independent web application

General cross-browser coding tips
Differences between Mozilla and Internet Explorer
DOM differences
JavaScript differences
Differences in JavaScript-generating HTML
CSS differences
CSS overflow differences
Quirks versus standards mode
Event differences
XML differences
XSLT differences

Monday, September 08, 2008

C++ to C# Converter Utility

C++ to C# Converter Utility

For migration project from C++ to C# Converter, a online utility might be helpful for getting startup stuff ready.

Check out C++ to C# Converter

Saturday, August 30, 2008

Finding Distance based on Zipcode or City Name for USA

Finding Distance based on Zipcode or City Name for USA
A really good article sharing how to find distance between two zip codes or cities of USA.

For whom this article is useful

  • It finds distance in miles between two zipcodes of USA.
  • It finds distance in miles between two cities of USA.
  • Finding County based on city or zipcode name.
  • Free Zipcode database of USA
  • Article is written in C#
Finding Distance based on Zipcode or City Name for USA

Note: When you will download the Zipcode of USA Cities and Import to SQL Server, it append inverted comma to data, to remove that you might need to run following update cursor script. Remember you need to change name of column as mentioned in script.

DECLARE c1 CURSOR READ_ONLY
FOR
select ZipCode,Latitude,Longitude,City,State,County,ZipClass from Zip_Codes

declare @ZipCodeOriginal varchar(50)
declare @ZipCode varchar(50)
declare @Latitude varchar(50)
declare @Longitude varchar(50)
declare @City varchar(50)
declare @State varchar(50)
declare @County varchar(50)
declare @ZipClass varchar(50)

open c1
FETCH NEXT FROM c1
Into @ZipCode,@Latitude,@Longitude,@City,@State,@County,@ZipClass
WHILE @@FETCH_STATUS = 0

BEGIN
set @ZipCodeOriginal = @ZipCode
set @ZipCode = substring(@ZipCode,2,len(@ZipCode) - 2)
set @Latitude = substring(@Latitude,2,len(@Latitude) - 2)
set @Longitude = substring(@Longitude,2,len(@Longitude) - 2)
set @City = substring(@City,2,len(@City) - 2)
set @State = substring(@State,2,len(@State) - 2)
set @County = substring(@County,2,len(@County) - 2)
set @ZipClass = substring(@ZipClass,2,len(@ZipClass) - 2)


--Update
update Zip_Codes
set ZipCode=@ZipCode,
Latitude = @Latitude,
Longitude = @Longitude,
City = @City,
State = @State,
County = @County,
ZipClass = @ZipClass
where
--Uniqueness Checking
ZipCode = @ZipCodeOriginal


FETCH NEXT FROM c1
Into @ZipCode,@Latitude,@Longitude,@City,@State,@County,@ZipClass
END
CLOSE c1
DEALLOCATE c1

Thursday, August 28, 2008

SQL Server Utility Functions for Searching String in SQL Server 2005

Set of Utility Function for SQL Server 2005

AT(): Returns the beginning numeric position of the nth occurrence of a character expression within another character expression, counting from the leftmost character.
RAT(): Returns the numeric position of the last (rightmost) occurrence of a character string within another character string.
OCCURS(): Returns the number of times a character expression occurs within another character expression (including overlaps).
OCCURS2(): Returns the number of times a character expression occurs within another character expression (excluding overlaps).
PADL(): Returns a string from an expression, padded with spaces or characters to a specified length on the left side.
PADR(): Returns a string from an expression, padded with spaces or characters to a specified length on the right side.
PADC(): Returns a string from an expression, padded with spaces or characters to a specified length on the both sides.
CHRTRAN(): Replaces each character in a character expression that matches a character in a second character expression with the corresponding character in a third character expression.
STRTRAN(): Searches a character expression for occurrences of a second character expression, and then replaces each occurrence with a third character expression. Unlike a built-in function Replace, STRTRAN has three additional parameters.
STRFILTER(): Removes all characters from a string except those specified.
GETWORDCOUNT(): Counts the words in a string.
GETWORDNUM(): Returns a specified word from a string.
GETNUMWORD(): Returns the index position of a word in a string.
GETALLWORDS(): Inserts the words from a string into the table.
PROPER(): Returns from a character expression a string capitalized as appropriate for proper names.
RCHARINDEX(): Similar to the Transact-SQL function Charindex, with a Right search.
ARABTOROMAN(): Returns the character Roman numeral equivalent of a specified numeric expression (from 1 to 3999).
ROMANTOARAB(): Returns the number equivalent of a specified character Roman numeral expression (from I to MMMCMXCIX).

You can get code from this web link for each of this functions http://it.toolbox.com/wiki/index.php/User-Defined_string_Functions_MS_SQL_Server_2005_Transact-SQL_SQLCLR

Tuesday, August 26, 2008

Avoid Insert Record on Page Refresh in asp.net

Avoid Inserting Duplicate Record on Page Refresh

Problem: User Input Form Inserts Duplicate Record on Page Refresh.

Solution:
This Problem can have 4 different solution, as mention in Article Preventing Duplicate Record on Page Refreshed

According to me among all mention solution, Page Redirect Solution is the best.

Use following piece of code, it will work efficient even with URL displayed with URLRewriting
Response.Redirect(Request.UrlReferrer.AbsoluteUri.ToString());

Friday, August 22, 2008

Finding Search Volume of Keyword SEO

Use the Keyword Tool to get new keyword ideas. Select an option below to enter a few descriptive words or phrases, or type in your website's URL. It also display following information.
  • Keyword
  • Monthly Search Volume
  • Suggestion Bid in $ (How much that keyword is worth)
  • And more information.
http://www.google.com/sktool



Finding Search Volume of Keyword SEO
How to find Search Volume of Keyword.

To Find Search Volume of keyword with the help of Google Keyword Tool.

https://adwords.google.com/select/KeywordToolExternal

Saturday, August 09, 2008

Member names cannot be the save as their enclosing type

Error: Member names cannot be the save as their enclosing type

Possible Cause: Unkowingly I declare Method name, same as class name, which pops-up this error. Logically its out of blue to think, declaring method name as class name as it is constructor, but may be because of nature of application i have declare Class Name as Method Name and runs into Error: "Member names cannot be the save as their enclosing type".

Cause of Error:


public class MyClass
{
//Declaring Method Same as Class Name
//Note: its not constructor, constructor don't have return type.
public void MyClass()
{
}
}
 

Solution to Error:


public class MyClass
{
//Change Method Name to Something else
public void MyMethod()
{
}
}

Monday, August 04, 2008

Free EBooks for LINQ, Ajax, Silverlight

Free E-Books for LINQ, Ajax, Silverlight

Free E-Books for New Features of .Net Framework 3.5

Sign up for the free e-book offer

The free e-book from Microsoft Press:

  • Introducing Microsoft LINQ by Paolo Pialorsi and Marco Russo



    It explains Language Integrated Query (LINQ) syntax fundamentals, LINQ to ADO.NET, and LINQ to XML.





This book explains ASP.NET AJAX Extensions 1.0, including an overview and the control toolkit.




This book explains how to use Silverlight to simplify the way you implement compelling user experiences for the Web. Discover how to support an object-oriented program model with JavaScript.

Wednesday, July 30, 2008

Expression Blend WPF Tutorial

Expression Blend WPF Tutorial

1. Overview

2. The User Interface

3. Creating and Importing Assets

4. Using WPF Controls

5. Animating in Blend

6. Data Binding

7. Building a Flickr Browser

8. Other Resources


Thursday, July 24, 2008

URL Rewriting with URLRewriter.Net Simplest Way

URL Rewriting with URLRewriter.Net

URL Rewriting has lots of benefits, listing its main benefits

  • SEO Friendly URL
  • Secured URL
  • No need to change bookmark with change in site structure.

Before URL Rewriting my URL looks like
http://localhost:2661/URLRewrite2/DynamicPage.aspx?MyTitleId=1

After URL Rewriting URL is changed to

http://localhost:2661/URLRewrite2/Article/Asp-Net-website-paths-1.aspx


Lets Understand URL Rewriting with Simple Example

A Website displaying articles list in a gridview on clicking the article link, it will display dynamically generated article content.

Before URL Rewriting when you mouse-over 1st Article Link, "Asp.net Website Path" it uses query string to display the article content.


Dynamic page display Querysting, before URL Rewriting.



After URL Rewriting we will achieve how SEO Friendly URL is used to display article content.


Now, lets understand how we can achieve it.

For URL Rewriting we are using URLRewriter.Net which is available free. Download URLRewriter.Net

Step-by-Step Explanation

Step 1: Download Binary Files for URLRewriter.Net

Step 2: Add Reference to Binary Files, Right click project "Add Reference" and add binary files.


Step 3: Update Web.Config File to make URLRewriter.Net works.
<configuration>

<configSections>
<section name="rewriter"
requirePermission="false"
type="Intelligencia.UrlRewriter.Configuration.RewriterConfigurationSectionHandler, Intelligencia.UrlRewriter" />
</configSections>

<system.web>

<httpModules>
<add name="UrlRewriter" type="Intelligencia.UrlRewriter.RewriterHttpModule, Intelligencia.UrlRewriter" />
</httpModules>

</system.web>

<system.webServer>

<modules runAllManagedModulesForAllRequests="true">
<add name="UrlRewriter" type="Intelligencia.UrlRewriter.RewriterHttpModule" />
</modules>

<validation validateIntegratedModeConfiguration="false" />

</system.webServer>

<rewriter>
<rewrite url="~/Article/(.+)-(.+).aspx" to="~/DynamicPage.aspx?MyTitleId=$2"/>
</rewriter>

</configuration>


Step 4: Adding Function to Generate SEO Friendly URL from given Title


public static string GenerateURL(object Title, object strId)
{
string strTitle = Title.ToString();

#region Generate SEO Friendly URL based on Title
//Trim Start and End Spaces.
strTitle = strTitle.Trim();

//Trim "-" Hyphen
strTitle = strTitle.Trim('-');

strTitle = strTitle.ToLower();
char[] chars = @"$%#@!*?;:~`+=()[]{}|\'<>,/^&"".".ToCharArray();
strTitle = strTitle.Replace("c#", "C-Sharp");
strTitle = strTitle.Replace("vb.net", "VB-Net");
strTitle = strTitle.Replace("asp.net", "Asp-Net");

//Replace . with - hyphen
strTitle = strTitle.Replace(".", "-");

//Replace Special-Characters
for (int i = 0; i < chars.Length; i++)
{
string strChar = chars.GetValue(i).ToString();
if (strTitle.Contains(strChar))
{
strTitle = strTitle.Replace(strChar, string.Empty);
}
}

//Replace all spaces with one "-" hyphen
strTitle = strTitle.Replace(" ", "-");

//Replace multiple "-" hyphen with single "-" hyphen.
strTitle = strTitle.Replace("--", "-");
strTitle = strTitle.Replace("---", "-");
strTitle = strTitle.Replace("----", "-");
strTitle = strTitle.Replace("-----", "-");
strTitle = strTitle.Replace("----", "-");
strTitle = strTitle.Replace("---", "-");
strTitle = strTitle.Replace("--", "-");

//Run the code again...
//Trim Start and End Spaces.
strTitle = strTitle.Trim();

//Trim "-" Hyphen
strTitle = strTitle.Trim('-');
#endregion

//Append ID at the end of SEO Friendly URL
strTitle = "~/Article/" + strTitle + "-" + strId + ".aspx";

return strTitle;
}


Step 5: Changing DataBinder.Eval Function in .Aspx Page to reflect changes in URL of Grid.
Note: Learn more about DataBinder.Eval Function



<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" BackColor="#DEBA84" BorderColor="#DEBA84" BorderStyle="None" BorderWidth="1px" CellPadding="3" CellSpacing="2" Width="788px">
<FooterStyle BackColor="#F7DFB5" ForeColor="#8C4510" />
<Columns>
<asp:TemplateField HeaderText="Title">
<ItemTemplate>
<asp:HyperLink ID="hlTitle" runat="server" Text='<%#DataBinder.Eval(Container.DataItem,"Title")%>' NavigateUrl='<%#GenerateURL(DataBinder.Eval(Container.DataItem,"Title"),DataBinder.Eval(Container.DataItem,"Id"))%>'></asp:HyperLink>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Description">
<ItemTemplate>
<asp:Label ID="lblDesc" runat="server" Text='<%#DataBinder.Eval(Container.DataItem,"Description")%>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
<RowStyle BackColor="#FFF7E7" ForeColor="#8C4510" />
<SelectedRowStyle BackColor="#738A9C" Font-Bold="True" ForeColor="White" />
<PagerStyle ForeColor="#8C4510" HorizontalAlign="Center" />
<HeaderStyle BackColor="#A55129" Font-Bold="True" ForeColor="White" />
</asp:GridView>


Now, Lets Check the stuff so far developed.

Assigning SEO Friendly URL in to grid.


On clicking URL inside grid it will point to Dynamically Generated Page with SEO Friendly URL, rather than QueryString.


Things to consider while URL Rewriting.

Problem 1: Page Postback, will turns User Friendly URL into Original URL.
Problem 2: CSS, Image Files pointing to URL Rewriting Page won't work, as they might be pointing with absolute path.

Problem 1: Page Postback for Page displaying URL Rewritten URL
Page Postback of Page displaying User friendly URL will turns into original state when same page postback occurs. In our example, I am adding one button and trying to make Page Postback. You will notice that Page Postback will turns the User Friendly URL into original URL containing QueryString.


For Resolving Page PostBack problem for Page displaying URL Rewritten URL

This article is inspired from Scott's URL Rewritten article. Adding two files as mentioned by scott. If you are developing code in VB download files from Scott's article, else for C# download files with Sourcecode at the end of this article.



Now, lets test the Page Postback by clicking on Button, you will notice this time, URL remains the same.




Problem 2: Image Display Problem
Now, lets display image on for this page and lets observe what problem we may run into. I have added following line to display image, but it won't works.

<img src="Images/article.gif" />


Resolve Problem, by refrencing file from root.
<img src="../Images/article.gif" />



Download Source-Code for URL Rewriting

Wednesday, July 23, 2008

Generate URL - SEO Friendly Asp.net

Generate SEO Friendly URL from given string in C# for Asp.net Web Application.

Example 1: Simple Test

  • Input: CSS is not working in IE? but working in FireFox... asp.net problem
  • Output: css-is-not-working-in-ie-but-working-in-firefox-Asp-Net-problem

Example 2:
Spaces Testing
  • Input: asp.net problem url re-writing.... testing the basics
  • Output: Untitled PageUntitled PageAsp-Net-problem-url-re-writing-testing-the-basics

Untitled PageExample 3: Special Character Testing
  • Input: 23 asp.net problem ### url re-writing.... testing the basics will pay $1000
  • Output: Untitled PageUntitled PageUntitled Page23-Asp-Net-problem-url-re-writing-testing-the-basics-will-pay-1000


private string GenerateURL(string strTitle)
{
//Trim Start and End Spaces.
strTitle = strTitle.Trim();

//Trim "-" Hyphen
strTitle = strTitle.Trim('-');

strTitle = strTitle.ToLower();
char[] chars = @"$%#@!*?;:~`+=()[]{}|\'<>,/^&"".".ToCharArray();
strTitle = strTitle.Replace("c#", "C-Sharp");
strTitle = strTitle.Replace("vb.net", "VB-Net");
strTitle = strTitle.Replace("asp.net", "Asp-Net");

//Replace . with - hyphen
strTitle = strTitle.Replace(".", "-");

//Replace Special-Characters
for (int i = 0; i < chars.Length; i++)
{
string strChar = chars.GetValue(i).ToString();
if (strTitle.Contains(strChar))
{
strTitle = strTitle.Replace(strChar,string.Empty);
}
}

//Replace all spaces with one "-" hyphen
strTitle = strTitle.Replace(" ", "-");

//Replace multiple "-" hyphen with single "-" hyphen.
strTitle = strTitle.Replace("--", "-");
strTitle = strTitle.Replace("---", "-");
strTitle = strTitle.Replace("----", "-");
strTitle = strTitle.Replace("-----", "-");
strTitle = strTitle.Replace("----", "-");
strTitle = strTitle.Replace("---", "-");
strTitle = strTitle.Replace("--", "-");

//Run the code again...
//Trim Start and End Spaces.
strTitle = strTitle.Trim();

//Trim "-" Hyphen
strTitle = strTitle.Trim('-');

return strTitle;
}

Tuesday, July 22, 2008

Regular Expression Tester

Test your Regular Expression with Regular Expression Tester. Checking your .net regular expression would be easy with Regular Expression Tester.

Regular Expression Tester

Sunday, July 06, 2008

Free Web Services in .Net

List of Free Web Services in .Net, this are some basic utility web services.

New to web service and want to know how you can use web service with your .Net Code

IIS 7 Tutorial

IIS 7.0 Easy Tutorial

Start up article on IIS 7 Part 1

  • Introduction to IIS 7
  • Overview of Architecture
  • Request Processing Pipeline
  • Overview of Application Pool
  • Creating Websites with IIS 7
  • Creating IIS Application

Start up article on IIS 7 Part 2

  • IIS 7 Configuration
  • Inheriting and overriding asp.net configuration
  • Feature Delegation

Wednesday, July 02, 2008

Asp.Net Developer Salaries-Best JOB Search Engine

Indeed.com a good website to find

  • Salaries for IT employee
  • Current Market Trend for adopting New Technology (Finding which Technology is Hot in market)
  • Adding Salary Comparision and making decision.
  • Best JOB Search Engine

A Comparision research from Indeed.com
Salary of Moss Developer In New York, Ny 10001
$112,000


Salary of Asp.net Developer In New York, Ny 10001
$99,000

Salary of C# Developer In New York, Ny 10001
$104,000

Salary of Wcf In New York, Ny 10001
$111,000

So now search jobs on Best Job Search Engine that which Technology is hot in market and which technology can earn you more. Which Technology others are adopting... I feel asp.net is loosing its charm due to high avaibility!!! But it is most stable technology based on number of jobs available.

I found Indeed.com is good search engine to get update on IT Market, rather than relying on News especially which are more general.

Sunday, June 29, 2008

Accordion AJAX Control Runtime Data display from Database

Accordion AJAX Control Example to Create AccordionPane Runtime with Data from Database.

Accordion Control is one of the best AJAX Control as we can use in many different ways to serve our needs. Please refer to this video if you are new to Accordion AJAX Control.

Many time we generate Menu Runtime for that we make use of Treeview Control, but with this example you will understand how Accordion AJAX Control is better than other solution. In this example I have fetch the Country wise data from Northwind Customer Table and display Customer Information CountryWise.

Example 1: Displaying All the customer group by country, belgium



Example 2: Displaying All the customer group by country, brazil


Note: here the content portion is not showing actual customer Id, but you can display easily using the same way i have used to display countries and attach a querystring to display customer information. This piece of code is reusable.

On .aspx page, declare Accordion control.

<asp:Panel ID="pnlShowCountry" runat="server">
<cc1:Accordion ID="acc" runat="server" SelectedIndex="0" AutoSize="none" FadeTransitions="false" FramesPerSecond="50" TransitionDuration="10" HeaderCssClass="AccordionPaneHeaderCSS" ContentCssClass="AccordionPaneContentCSS">
</cc1:Accordion>
</asp:Panel>
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>

On .aspx.cs page (code behind) actual logic to create accordianpane runtime and binding logic.
protected void Page_Load(object sender, EventArgs e)
{
PopulateCountry();
}

private void PopulateCountry()
{
DataTable dtCountry = GetCountry();
DataRow drCountry;
string CountryName, CountryCount;

for(int i=0;i< dtCountry.Rows.Count;i++)
{
drCountry = dtCountry.Rows[i];
CountryName = drCountry["CountryName"].ToString();
CountryCount = drCountry["CountryCount"].ToString();

Label lblHeader = new Label();
lblHeader.ID = "lblHeader" + i.ToString();
lblHeader.Text = "<a href='' onclick='return false;' Class='AccordionLink'>" + CountryName + "</a> (" + CountryCount + ")";

//For Content
int iCountryCount = Convert.ToInt16(drCountry["CountryCount"]);
Label lblContent = new Label();
lblContent.ID = "lblContent" + i.ToString();
for (int j = 1; j <= iCountryCount; j++)
{
if(j==1)
lblContent.Text = "<a href='' onclick='return false;' Class='AccordionLink'>Customer " + j.ToString() + "</a><br>Blah Blah Blah....<br>Blah Blah Blah....Blah Blah Blah....";
else
lblContent.Text = lblContent.Text + "<br><a href='' onclick='return false;' Class='AccordionLink'>Customer " + j.ToString() + "</a><br>Blah Blah Blah....<br>Blah Blah Blah....Blah Blah Blah....";
}

AccordionPane accp = new AccordionPane();
accp.ID = "accp" + i.ToString();
accp.HeaderContainer.Controls.Add(lblHeader);
accp.ContentContainer.Controls.Add(lblContent);

acc.Panes.Add(accp);
}
pnlShowCountry.Controls.Add(acc);
}

private DataTable GetCountry()
{
string strConn = ConfigurationManager.AppSettings["connStr"].ToString();
SqlConnection conn = new SqlConnection(strConn);
conn.Open();
SqlDataAdapter da = new SqlDataAdapter("select Country as 'CountryName', count(customerId) as 'CountryCount' from customers group by country",conn);
DataSet ds = new DataSet();
da.Fill(ds,"Country");
DataTable dtCountry = ds.Tables["Country"];
return dtCountry;
}

Saturday, June 28, 2008

DropShadowExtender AJAX Control Example

DropShadowExtender AJAX Control Example

If you are new to AJAX, Please refer to my Simple AJAX Example to understand how simple to start with AJAX.


Step 1: Add Script Manager

Step 2: Add a pannel control to asp.net page

Step 3: Add all controls inside Pannel Control, that you wish to see in Rounded Corner Box (ie. Applying DropShadow effect)

Note: Good Practise while defining pannel for DropShadowExtender Control

  • Assign Width Property
  • Assign BackColor Property eg: here I have used HotPink Color.
<asp:Panel ID="pnlMyCalcy" runat="server" BackColor="HotPink" Width="300">


Step 4: Adding DropShadowExtender Control, and Initialize
"TargetControlID" Property with Pannel Control Id and Property TrackPosition="true"
<cc1:DropShadowExtender ID="DropShadowExtender1" runat="server" TargetControlID="pnlMyCalcy" Opacity="75" Rounded="true" Radius="10" Trackposition="true"> </cc1:DropShadowExtender> 

ValidatorCalloutExtender AJAX Control Example

ValidatorCalloutExtender AJAX Control Example

If you are new to AJAX, Please refer to my Simple AJAX Example to understand how simple to start with AJAX.



Step 1: Add AJAX Script Manager

Step 2: For using ValidatorCalloutExtender, it is not compulsory to add Update Pannel, as this control is extender for validation control, so you must check 1 ValidatorCalloutExtender must associated with 1 Validation Control.

Step 3: Look a sample code to understand how
ValidatorCalloutExtender works

  • Initialize TargetControlID of ValidatorCalloutExtender control with ID of Validation Control you wish to associate with thatz it, nothing more.

<asp:TextBox ID="txtDigit1" runat="server"></asp:TextBox>

<
asp:RequiredFieldValidator ID="rfvDigit1" runat="server" ErrorMessage="Please Enter Digit1" ControlToValidate="txtDigit1" Display="None"></asp:RequiredFieldValidator>
<cc1:ValidatorCalloutExtender ID="rfvDigit1Ext" runat="server" TargetControlID="rfvDigit1">
</cc1:ValidatorCalloutExtender>

<asp:RegularExpressionValidator ID="revDigit1" runat="server" ErrorMessage="Please enter &lt;b>valid Numeric value</b> " ControlToValidate="txtDigit1" Display="None" ValidationExpression="\d{0,15}"></asp:RegularExpressionValidator>
<cc1:ValidatorCalloutExtender ID="revDigit1Ext" runat="server" TargetControlID="revDigit1">
</cc1:ValidatorCalloutExtender>

Most Recent Post

Community Updates

Subscribe Blog via Email

Enter your email address:



Disclaimers:We have tried hard to provide accurate information, as a user, you agree that you bear sole responsibility for your own decisions to use any programs, documents, source code, tips, articles or any other information provided on this Blog.
Page copy protected against web site content infringement by Copyscape