Thursday, November 25, 2010

Bind Dropdownlist dynamically with Country Names in ASP.NET

Hello Friends


Today i am read article, i see good article about fill drop down with country list which are publish on codgain is Good site

please refer following link to know how we fill country drop down list in asp.net using using culture.

we  also bind country in drop down list using database table or array in JavaScript function to fill country.

link

http://www.codegain.com/articles/aspnet/globalizationandlocalization/how-to-bind-dropdownlist-dynamically-with-country-names-in-aspnet.aspx

Happy Codding

Thank You

Kirti M. Darji

Tuesday, September 28, 2010

New feature available in asp.net 4.0

Today I am giving you introduction for what’s new in asp.net 4.0.I hope this would help you.There are many enhancement made in asp.net 4.0

Setting Meta tag with Page

Asp.net 4.o added two new property like MetaKeyWords and MetaDescription. This property represents corresponding Meta tag in your Page

<head id="Head1" runat="server">
  <title>My Page Title</title>
  <meta name="keywords" content="Asp.net,Net,MVC,new' />
  <meta name="description" content="My asp.net 4.o new feature article" />
</head>

Content of description metatag are use for search listing preview for google.

ViewStateMode Property (for Enable view state for individual control)

By default view state is enable for page, with the result each control of page are potentially store view state data in page so page size is increase that’s why performance is degrade. In earlier virsion developer can do that thing to disable view state but he want to disable for all control. Now in asp.net 4.0 new viewstatemode property introduce which take following enumerated data type like Enable, Disable, Inherit.

For disable viewstatemode for page set viewstatemode property is disabling then whatever control you need viewstatemode enable this property for that control.


See following example

<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent" ViewStateMode="Disabled"  >

<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent" ViewStateMode="Disabled"  >
<div>
    No of item :
    </div>
<div>
<asp:TextBox ID="txtNoitem" runat="server"  onchange="intOnly(this)"  onkeypress="showSaveCancel();intOnly(this);" onkeyup="intOnly(this)" />
    </div>
<div id="divSaveCancel">
    <asp:Button ID="btnSave" runat="server" Text=" Save " />&nbsp;
    
        <asp:Button ID="btnCancel" runat="server" Text="Cancel" />
    </div>
       
    



No of item :


See above example ViewStateMode is Desable so for all control



Changes to Browser Capabilities



ASP.NET determines the capabilities of the browser that a user is using to browse your site by using a feature called browser capabilities. Browser capabilities are represented by the HttpBrowserCapabilities object (exposed by the Request.Browser property). For example, you can use the HttpBrowserCapabilities object to determine whether the type and version of the current browser supports a particular version of JavaScript. Or, you can use the HttpBrowserCapabilities object to determine whether the request originated from a mobile device.
The HttpBrowserCapabilities object is driven by a set of browser definition files. These files contain information about the capabilities of particular browsers. In ASP.NET 4, these browser definition files have been updated to contain information about recently introduced browsers and devices such as Google Chrome, Research in Motion BlackBerry smartphones, and Apple iPhone.



Routing in ASP.NET 4

Asp.net add built in support for using routing in web farm.Routing is nothing it just configure URL does not map with physical URll, you can use routing for display URl in meaningful way. For Example you want to display article for cshap category 

By routing you can configure Application can accept below URL to render same information above URL



 

Setting Client IDs


Client ID I already explain in my previous article

ASP.NET Chart Control

The ASP.NET Chart control expands the data-visualization offerings in the .NET Framework. Using the Chart control, you can create ASP.NET pages that have intuitive and visually compelling charts for complex statistical or financial analysis. The ASP.NET Chart control was introduced as an add-on to the .NET Framework version 3.5 SP1 release and is part of the .NET Framework 4 release.


The ability to persist selected rows in data controls

Gridview and listview control eable user to select row.In previous version of asp.net row selection is based on row index on page. For example if you select page1 item no 3 and move to page 2 then on page 2 item no 3 is selected, so it is not desirable.now in asp.net 4.0 support Persisted Selection, a new feature in asp.net 4.0 using PersistedSelection property of grideview or listview if property is true then if you go to page 2 then no item is selected if you go back to page 1 then item no 3 is selected.
<asp:GridView id="gdEmployee" runat="server" PersistedSelection="true">
</asp:GridView>

More control over rendered HTML in the FormView and ListView controls.

The FormView control is enhanced to make it easier to style the content of the control with CSS. In previous versions of ASP.NET, the FormView control rendered it contents using an item template. This made styling more difficult in the markup because unexpected table row and table cell tags were rendered by the control. Now in asp net 4.o  have RenderTable property which can set true or false if we set false then control are not rendered as table and row html format so it is easier to apply css style on content of control.


<asp:FormView ID="FrvEmployee" 
runat="server" RenderTable="false">

ListView

In ASP.NET 4, the ListView control does not require a layout template.

<asp:ListView ID="LvEmployee" runat="server">
    <ItemTemplate>
        <% Eval("LastName")%>
    </ItemTemplate>
</asp:ListView>

CheckBoxList and RadioButtonList Control Enhancements

In ASP.NET 3.5, you can specify layout for the CheckBoxList and RadioButtonList using the following two settings:

  • Flow. The control renders span elements to contain its content.
  • Table. The control renders a table element to contain its content.
In ASP.NET 4, the CheckBoxList and RadioButtonList controls support the following new values for the RepeatLayout property:

  • OrderedList – The content is rendered as li elements within an ol element.
  • UnorderedList – The content is rendered as li elements within a ul element.

Menu Control Improvements

Before ASP.NET 4, the Menu control rendered a series of HTML tables. This made it more difficult to apply CSS styles outside of setting inline properties and was also not compliant with accessibility standards.
In ASP.NET 4, the control now renders HTML using semantic markup that consists of an unordered list and list elements. The following example shows markup in an ASP.NET page for the Menu control.

<asp:Menu ID="MainMenu" runat="server"> 
  <Items> <asp:MenuItem Text="Home" Value="Home" /> 
  </Items> 

</asp:Menu>
When the page renders, the control produces the following HTML (the onclick code has been omitted for clarity):
<div id="Menu1"> 
  <ul> 
    <li><a href="#" onclick="...">Home</a></li> 
 </ul> 

</div> 
<script type="text/javascript"> 
  new Sys.WebForms.Menu('Menu1');
</script>

Wizard and CreateUserWizard Controls

ASP.NET 4, you can create a LayoutTemplate template and insert PlaceHolder controls (using reserved names) to specify how you want the Wizard control to render. The following example shows this:

<asp:CreateUserWizard ID="CreateUserWizard1" runat="server" ActiveStepIndex="1">
  <LayoutTemplate> 
    <asp:PlaceHolder ID="headerPlaceholder" runat="server" /> 
    <asp:PlaceHolder ID="sideBarPlaceholder" runat="server" /> 
    <asp:PlaceHolder id="wizardStepPlaceholder" runat="server" /> 
    <asp:PlaceHolder id="navigationPlaceholder" runat="server" /> 
  </LayoutTemplate> 
  <HeaderTemplate> 
    Header 
  </HeaderTemplate>
  <WizardSteps>
    <asp:CreateUserWizardStep runat="server"> 

      <ContentTemplate> 
      </ContentTemplate>     </asp:CreateUserWizardStep>     <asp:CompleteWizardStep runat="server">       <ContentTemplate>       </ContentTemplate>     </asp:CreateUserWizardStep>   </WizardSteps> </asp:CreateUserWizard>

Reference:

so guys we meet in few day with new topit
Thank you for Reading


Kirti M Darji

Sunday, September 12, 2010

How Debug Asp.Net Application when large scale project.

This article is dedicated to developer work on small size project development where project is not large. Large project or enterprise level project means project contain Five or six another Project webservices and all, generally we are run project and there we can debug our application right, but large scale projects it take more time debug application to using run mode. So here I am explain how we debug large scale projects.
Generally we generally run project and debug application but large and enterprise level project take more time to run and process for debugging application.

Step1. Open project which you want to debug.

Step-2.Open project with URL in any Browser

                      eg http://localhost/MyBlog/Artical/Default.aspx

Step-3 Open page of your project which you want to debug now attach debugger in your project using alt+D then press P

Or

Debug Attach to Process

Following Screen You see on your Screen



Select aspnet_wp.exe Worker Process and click on attach button dialog box will disappear now our debugger is attached now put break point (using f9) on method you want to check

Process for event or method you want to debug in your project, now you application ready for debug. So that the way you can debug your application.

I thing it save your lot of time for development process. Here I am trying share my experience about we can make a work fast with debugging in your in project. my aim is whatever you find new one write some where so you can useful for some one else it a really good work so keep helping our friends

Thanks for reading. See you with new topic as soon as possible

Kirti M Darji

Monday, August 30, 2010

How Change keyboard layout with Windows 7

Hello Guys on week end I am out of station where I am face a problem with laptop (with Windows 7 operating system) keyboard, some key are different where mention in keyboard.

“Main problem with ‘@’,’”’ Keys is not real place it will on different location”

I am thinking couple of minutes, suddenly I get roughly idea this may be the issue of regional setting.

but i am not aware how check keyboard and layout in Windows 7 because I am using first time, after some time digging on net I got following link which explain how change keyboard layout in windows 7.



When I am check on laptop Keyboards and Language, the default language is selected as United Kingdom that’s why our key board some keys are different,so finally change united states and it working fine for me.


I hope this would help you

Thank you for Reading


Kirti M Darji

Sunday, August 15, 2010

ClientID Mode in ASP.NET 4.0 AND JAVASCRIPT OR JQUERY

Introduction

Hello Guys, I am writing my experience about creating new website and simple functionality about call multiple JavaScript function on same event I am already publish in my previous article. ASP.NET 4.0 new properties ClientIDMode, which can be used to force controls to generate clean Client IDs that don’t follow ASP. Net’s Naming Container ID conventions. Now it is possible to set ClientIDMode Property so developer can set control name in better way but this one create a problem for new developer which are new and switch to asp.net 4.0

Technologies

ASP.NET 4.0, JQuery, JavaScript

Language

C#

Prerequisite

Visual web developer 2010 Express

Implementation

Open visual studio 2010 project and Create new website

we are use JavaScript function for client side validation minimal, use of post back of page or asynchronous post back.

I am creating one JavaScript function like GetTextValue which are use get value from Textbox

I am trying to get value using jquery$(“#textboxname”) and getting null object with master page.

I found something happen due to clientIDMode in asp.net 4.0 let me explain in detail.

If you place the any control inside the content placeholder of a master page, its id will be generated as ctl00$MainContent$txtboxname.

Ctl00 : Random ID generate for Every Master Page You nest like ctl00,ctl01..
MainContent: It Represent ID of master page here is Main Content
Txtboxname: This is the actual ID of Control

you can see depending on master page ID control ID is change if it is nested master page ID is also change. is we change to nested master page case JavaScript return null element so because ID is change that case you have to changes in all place where you write ID to get Element. It is very tedious job.

We can get texbox object using following two way

var txtBoxName = document.getElementById("ctl00$MainContent$txtboxname ");
or
var txtBoxName = document.getElementById("<%=txtboxname.ClientID>");
using jquery
var txtBoxName=$(‘#txtBoxName’)
If we go for first way then it may be issue like nested master page id is change that case second declaration is better.

Second declaration is like mix-up with client side block and server side block and it would be avoided.

In both limitation resolve here in ClientIDMode Property in asp.net 4.0

Asp.net 4.0 new clientIDMode page attribute have following four value we can set.

AutoID

AutoId places one Unique Sequence page id AutoId places one Unique Sequence page id of the controls using ctl00, ctl01 .. .This is the existing behavior in ASP.NET 1.x-3.x where full naming container .it is Default clientIDMode.

Static

This option forces the control’s ClientID to use its ID value directly. No naming container naming at all is applied and you end up with clean client ids:

This option is what most of us want to use, but you have to be clear on that this can potentially cause conflicts with other control on the page. If there are several instances of the same naming container so client ID naming conflict, It’s basically up to you to decide whether this is a problem or not.

Predictable

The key that makes this value a bit confusing is that it relies on the parent NamingContainer’s ClientID to build it’s own client ID value.
For our simple textbox example, if the ClientIDMode property of the parent naming container (Page in this case) is set to “Predictable” you’ll get this:

The most common use however for Predictable will be for DataBound controls, which results in a each data bound item to get a unique ClientID.

Inherit

The final setting is Inherit which is the default for all controls except Page. This means that controls by default inherit the naming container’s ClientIDMode setting. Inherit is slightly different than the AutoId..
AutoId places one Unique Sequence page id of the controls using ctl00, ctl01 .. In case of Inherit mode, it only places the inherited control id for each controls.

within the masterpage, it will give you “MainContent_ txtboxName”. So the only difference between inherit mode and AutoId is that AutoId places the unique PageId like ctl00,ctl01while Inherits doesn’t..

Conclusion

using this article I am trying to ClientIDmode Property which are new features in asp.net 4.0. How all asp.net developer handle the clientIDs batter way using clientIDmode Property.
I hope this would help you
Thank you for Reading

Kirti M Darji

Tuesday, August 10, 2010

Call more then one JavaScript function on same event

Introduction

Today I am working on how call more then one JavaScript function on same event. To achieve this I make some goggling and find solution, which I am sharing with you guys. My Basic requirement is when user enters value in text box the value must be numeric and if text box is not blank then it show save and cancel else hide save cancel button. So this can be achieved by two ways. So here I am representing both way.

Technologies


ASP.NET 4.0, JQuery, JavaScript

Language


C#

Prerequisite

Visual Studio 2005 and Later, my project definition in visual studio 2010.

Implementation

Step-1

Open visual studio 2010 project and Create new website

You can notice one thing there is Scripts file folder are included in project with Jquery virsion 1.4.1 and Default style sheet style.css in visual studio 2010 when we create new website project.
Step-2
Open Default.aspx Source view. Add one Textbox Server control and two Button for Save and cancel..

Default.aspx
<%@ Page Title="Home Page" Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true"

    CodeFile="Default.aspx.cs" Inherits="_Default" ClientIDMode="Static" %>










No of item :
 

Above code snipped you notice one thing like ClientIDMode="Static” why I am put that will explain in next article


You can achieve this functionality without call two function on same event like this way call showSaveCancel() function inside intOnly() function like

function intOnly(i) {
 if (i.value.length > 0) 
{ 
i.value = i.value.replace(/[^\d]+/g, '');showSaveCancel(); 
} 
}

Conclusion

Here I am trying to share how call more then one JavaScript function on same event.

Happy Coding

Thank you for Reading

Kirti M Darji

Tuesday, July 27, 2010

Validate XML over DTD using .net

Introduction

We can Easily Export data from Excel, CSV file into individual Xml per Record. There is multiple xml file generated per record. This article explains how to validate xml over DTD (Document Type Definition).

Technologies
.NET

Language

C#

Prerequisite

Visual Studio 2005 and Later

Implementation

Step-1

 open .net Visual studio 2005 or latter create new project  select window project and language is c#
Step-2

Following name space will added
using System.Xml;
using System.Xml.Schema;
Step-3
Take one window form and  put one Textbox, open Button(for Open file Dialog box), validate button and fileopenDialogbox place on form.like


when we click open button one dialog box open and take xml path for validate xml
Step-4
Define Following Variable Global in form Class
private static bool isValid = true;
String StrErrorPath = Application.StartupPath + "/ValidateError.log"
Put Following code in open button click Event

private void btnoutput_Click(object sender, EventArgs e)

{
String strFolderName;
FDBrowserDL.ShowNewFolderButton = true;
FDBrowserDL.ShowDialog();
strFolderName = FDBrowserDL.SelectedPath;
Txtoutputpath.Text = strFolderName;
Txtoutputpath.Text = Convert.ToString(strFolderName);

}
Put Following code in Validate buttion Click event
private void btnValidate_Click(object sender, EventArgs e)
{
ValiDateXML(Convert.ToString(Txtoutputpath.Text));
}
Following are function Validate Xml over DTD. If there is error in file means if Xml file not match over DTD then it Give Error and Write Error in Error file with Description.

private void ValiDateXML(String StrFilePath)
{
Int64 i=0;

String[] fileEntries = Directory.GetFiles(StrFilePath);
foreach (String Sfile in fileEntries)  Application.DoEvents();  
XmlTextReader r = new XmlTextReader(Sfile);  
r.WhitespaceHandling = WhitespaceHandling.None;  
XmlValidatingReader v = new XmlValidatingReader(r);  
v.ValidationType = ValidationType.DTD;  
v.ValidationEventHandler += MyValidationEventHandler;   
i = i + 1;  
Resume:  
try  { 
 while (v.Read())   {  }  
lblMessage.Text = "Validating File : " + i.ToString();  }  
catch (Exception Ex)  
{ 
WriteError(Sfile, Ex.Message);  goto Resume;  } v.Close(); 
} 
lblMessage.Text = "Check Validation Complete";  
} 
public void MyValidationEventHandler(object sender,ValidationEventArgs args)

{

isValid = false;

WriteError(sender.ToString(),args.Message);

}
private void WriteError( String StrFilename, String Ex)
{
try
{
StreamWriter sw;
if (File.Exists(StrErrorPath)==false)
{
   sw = new StreamWriter(StrErrorPath);
}
else
{
sw = new StreamWriter(StrErrorPath, true);

}
sw.WriteLine(StrFilename + " " +Ex);
sw.WriteLine("From the StreamWriter class");
sw.Close();
}
catch (Exception ex)

{
MessageBox.Show("Error occurred at writting to Error Log file. -- " + ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);

}

}
Conclusion

I have tried best to explain how validate bunch of xml file which have same DTD(Document Type Definition)


Happy Codding

Thank you

Sunday, July 25, 2010

Create Zip file using .net (c#)

Introduction

This article explain you about how to create zip file programmatically  using .net

Technologies

.NET Framework 2.0 or later


Language
C#

Prerequisite
Visual Studio 2005 and Later


Implementation
Open Visual studion and create website projects
1.Right click on project and click on Add References.
2.Add vjslib Reference are in Project

Add following namespace
using System.IO;
using java.io;
using java.util.zip;
Step-1
Put one button name like btnZip
  in aspx Page

Step-2

copy Past Following code in Button click event like 
protected void btnZip_Click(object sender, EventArgs e)
{
StringBuilder sb = new StringBuilder();
string ZFileName = String.Format(@"C:\zipfolder\{0}.zip", DateTime.Now.ToString("yyyyMMdd"));
string strDirectory = @"C:\Kirti";
try
{
sb.Append(String.Format("Directory To Zip \n", strDirectory));
sb.Append(String.Format("Zip file: {0}\n", ZFileName));
string[] allFiles = Directory.GetFiles(strDirectory, "*.*", SearchOption.AllDirectories);
if (System.IO.File.Exists(ZFileName))
{
System.IO.File.Delete(ZFileName);
sb.Append(String.Format("Deleted Zip file: \n", ZFileName));
}
FileOutputStream Flostr = new FileOutputStream(ZFileName);
ZipOutputStream Zpoutstr = new ZipOutputStream(Flostr);
Zpoutstr.setLevel(9);
for (int i = 0; i < allFiles.Length; i++)
{
string sourceFile = allFiles[i];
FileInputStream Finstr = new FileInputStream(sourceFile);
ZipEntry ze = new ZipEntry(sourceFile.Replace(strDirectory + @"\", ""));
Zpoutstr.putNextEntry(ze);
sbyte[] buffer = new sbyte[1024];
int len;
while ((len = Finstr.read(buffer)) >= 0)
{
Zpoutstr.write(buffer, 0, len);
}
Finstr.close();
}
Zpoutstr.closeEntry();
Zpoutstr.close();
Flostr.close();
sb.Append(String.Format("Folder {0} Zipped successfuly to File {1}.", strDirectory, ZFileName));
}
catch (Exception eX)
{
sb.Append(String.Format("Error zipping folder {0}. Details: {1}. Stack Trace: {2}.", strDirectory, eX.Message, eX.StackTrace));
}
lbReport.Text = sb.ToString();
}
Conclusion
This is reference article code for you get some idea about how create zip file. you can make customization on your way like give path dynamic and select zip folder path dynamically etc..

Happy Coding.
Enjoy!!!!!!

Encrypting and Decrypting Configuration Section in web.config file

Introduction

This article explains about how to encrypt and Decrypt web.config file in web application. In web Application Sometime we put come confidential information in configuration section like (appsetting, Connectionstring)

Technologies

.NET Framework 2.0 or later

Language

C#

Prerequisite

Visual Studio 2005 and Later

Implementation

Following namespace will added
using System.Web.Configuration;

Step-1

Take two buttons name like btnEncrypt and btnDyscrypt  in aspx Page

Step-2

Copy-past bellow in btnEncrypt Click Event


try
{
Configuration confg = WebConfigurationManager.OpenWebConfiguration(Request.ApplicationPath);
ConfigurationSection confStrSect = confg.GetSection("connectionStrings");
if (confStrSect != null)
{
onfStrSect.SectionInformation.ProtectSection("RsaProtectedConfigurationProvider");

confg.Save();

}
}
catch (Exception ex)
{
throw
}

Copy-past bellow in btnDyscrypt Click Event

try

{

Configuration confg = WebConfigurationManager.OpenWebConfiguration(Request.ApplicationPath);
ConfigurationSection confStrSect = confg.ConnectionStrings; 
if (confStrSect != null && confStrSect.SectionInformation.IsProtected)
{
confStrSect.SectionInformation.UnprotectSection();
confg.Save();
}
}
catch (Exception ex)
{ 
throw
}
Conclusion

This is My First article on my blog  so any comment related to writing on blog are acceptable.so we can easily encrypt web.config file at client place for some confidential information.

Happy Coding!!!