Thursday, July 22, 2010

Radio Button in Grid View

I had use radio button in grid view into my recent development.

Radio button Group problem in Grid view

I found that radio button is not create group when they are render on client side into grid rows because of the automated id and name creation of the

Radio button checked property problem in Grid view on server side code

One more problem I found that when we iterate through grid view rows on server side code. I can find the radio button using the rows[0].findcontrol('id') method but its always give me a checked value false.

Following is solution I applied into my development to get out of this tow.

I replace Radio button server control with the HTML input control with type radio.

<asp:RadioButton ID="RadioButton1" runat="server" />

<input type="radio" runat="server" ID="radio1" class="rbclass" value='<%# Eval("columen name") %>' />

Apply server side binding to the value property of it.

I used jquery to change the name attribute of the radio button to make them grouped. (you can used you own java script code to do that)

$(document).ready(function() {
            $(".rbclass").attr("name", "groupname");

When I want the selected value at time of the postback I used request.form["group name"].

string radiovalue = Convert.ToString(Request.Form["groupname"]);

Tuesday, July 6, 2010

ExecuteScalar function with Generic Data Type

Here is the static function which will Generic Data Type to get the scalar value from the query passed to the ExecuteScalar function of the SqlCommand object.

You have to pass the query and the connection string as parameter to it.

public static T ExecuteScalar<T>(string query, string strConnection)
            SqlConnection con = new SqlConnection(strConnection);

            SqlCommand sc = new SqlCommand();
            sc.CommandText = query;
            sc.Connection = con;
                return (T)(sc.ExecuteScalar());
            catch (Exception ex)
                throw ex;

Monday, May 17, 2010

Convert Generic List to CSV

In my recent development with c#, I have to code for the functionality to Convert one Generic list of class XYZ to CSV downloadable File with dynamically suppress some of the column and different descriptive headers then the properties name for the column.

So I develop one Generic function which will convert List to CSV and return the string, which will then wrapped to Http Response to available as downloadable file.

Here is a Function which will convert List of Generic type T to CVS format string with 2 arguments. First Argument is List of objects to be converted into CSV and second is the 2 dimensional string array with the name of properties of object to be include in conversion with the Header Text for that properties to use while it is converting into CSV.

private static string ListToCsv(ref List<T> list, string[,] HeaderAndColumns)
            if (list == null || list.Count == 0) return "";

            Type t = typeof(T);
            int lenght = HeaderAndColumns.GetLength(0);

            StringWriter sw = new StringWriter();

            // Create Header Row..
            for (int l = 0; l < lenght; l++)
                sw.Write(HeaderAndColumns[l, 0].Replace(',', ' '));
                if (l < lenght - 1)

            //this acts as datarow

            foreach (T item in list)
                for (int i = 0; i < lenght; i++)
                    string whatToWrite =
                        Convert.ToString(item.GetType().GetProperty(HeaderAndColumns[i, 1]).GetValue(item, null)).Replace(',', ' ');

                    if (i < lenght - 1)
                        whatToWrite += ",";


            return sw.ToString();

If we have class XYZ as follow

public class XYZ
        public string prop1 { get; set; }
        public string prop2 { get; set; }

And we want to convert list of XYZ's object (List<XYZ>) to CSV we have to call the function like following

// 2D string arry , 1st is header , 2nd is Property name
    string[,] HeaderAndColumns = new string[,] {
            {"Header 1",      "prop1"},
            {"Header 2","prop2"}

string strCSV = ListToCsv(ref list, HeaderAndColumns);

To warp is with Http Response you can use following code. This will help you to through the converted CSV string as downloadable file.

                "content-disposition", string.Format("attachment; filename={0}", filename));
            HttpContext.Current.Response.ContentType = "application/ms-excel";

            using (StringWriter objSw = new StringWriter())
                   string[,] HeaderAndColumns = new string[,] {
                        {"Header 1",      "prop1"},
                        {"Header 2","prop2"}
                  objSw.Write(ListToCsv(ref list, HeaderAndColumns));

Wednesday, March 24, 2010

How to set culture of page

Here I show you how to set the culture of your page through code.

To do that you have to over ride InitializeCulture mthod of page. And Set the UICultuer and Culture properties of page for the specified culture like 'en-US', 'en-GB' etc.

For example

this.UICulture = “en-GB”;
this.Culture = “en-GB”;

This set you page culture to English UK (GB for grate brighten).

Now all you need is list of cultures available in .net to get that we use following code which will retrieve the list of culture available with the .net.

CultureInfo[] cultures = System.Globalization.CultureInfo.GetCultures(CultureTypes.SpecificCultures);
cultures = cultures.OrderBy(c=>c.EnglishName).ToArray();

Now you can bind these values with the drop down list.

foreach(CultureInfo c in cultures)
    ddlCulture.Items.Add(new ListItem(c.EnglishName + " : " + c.NumberFormat.CurrencySymbol, c.Name));
Get the selection from user and set the Session variable or any other way to set the culture of your page.

Saturday, February 27, 2010

DNN Modules - Google Analytic Dashboard

This is my first DNN related post in this post. Here is a Google Analytic Dashboard DNN Module which contain following sub modules.

  • Visitors Overview
  • World Map Overlay
  • Traffic Sources Overview

Click here to download Installable and source. 

After installing the module you will find listed modules into your module drop down list.Drop module on to the page and then done following setting through setting page of the module.

  • Google Analytic Email id - your Google analytic accounts email id.
  • Google Analytic password - password for the analytic account.
  • Google Analytic Profile id - this is your Google analytic profile id for which you want to display charts.
  • Width and Height - optional.

Note : For the detail of how to get profile id click here and see the bottom parts of the post.

Save this setting and enjoy this module.
There Date range selector which set the date range for the charts, set them to your desire period and click on apply. you can see the result for that date range.

Out puts

Following are the screen shots of the modules out put.




Saturday, February 20, 2010

Google Analytic Helper Class ..

Google analytic is very powerful and handy utility provided by the Google to track your web site traffic from all over the word.

To use this Google analytic with our page we have to put one java script code into the page based on the WebPropertyId of the analytic profile from which we track our site.

Following are the some ready made methods of helper class which help you to play with google analytic into your page

Please download following assembly to use the helper class methods

1) getTrackerCode

GADCAPI.GADCAPIHelper.getTrackerCode(string WebPrppertyId)

This method return the java script which used to place into the page to activate google analytic tracker on that particular page.


var gaJsHost = ((""https:"" == document.location.protocol) ? ""https://ssl."" : ""http://www."");
document.write(unescape(""%3Cscript src='"" + gaJsHost + ""' type='text/javascript'%3E%3C/script%3E""));

try {
var pageTracker = _gat._getTracker(""U-XXXXXXXX-X"");
} catch(err) {}

(script tags are omitted because of post rendering made them activate)

2)  getProfilesList

public static List getProfilesList(string EmailAddress, string Password)

This method get your analytic account user name and password and return generic List of Class ProfileInfo.

ProfileInfo is class which have following properties

1) Url - profile url
2) WebPropertyId - U-XXXXXXXX-X like unique code for profile given by the 
3) ProfileId - this is profile id which is used to get profile data into the Google Analytic Dashboard Controls



To find more utility control please refer the post Google Analytic Dashboard Controls into the category web control

Tuesday, January 12, 2010

Google Analytic Dashboard Controls

"Google Analytic Dashboard Controls" is costume controls library which contain ASP.NET costume controls which generate different types of charts like Google analytic dashboard using Google analytic data export api. Its include following controls.

  1. Visitors overviews
  2. Word map overview
  3. Traffic source overview
  4. Content overview

Followings are the images of the resulting graphs using them

Visitors Overview

Traffic Source Overview

Word Map Overview

Content Visits Overview

To use this controls into your ASP.NET projects follow the below steps.

2. Add reference of "Google Analytics Desbord Controls.dll" to your project.

3. In toolbox add controls by Right Click -> Choose Items -> browse dll.

4. Now Drag and drop control to your .aspx file.

5. Set Properties GAEmailAddress to your Google Analytic account email id, GAPassword to password , GAProfileId to analytic profile id for which you want to show report, FromDate to start date, ToDate to end date.

Following is the example code for VisitorOverview control.

In .aspx file

<cc1:VisitorsOverview ID="VisitorsOverview1" runat="server">

In .aspx.cs file

VisitorsOverview1.GAEmailAddress = "EmailAddress";
VisitorsOverview1.GAPassword = "Password";
VisitorsOverview1.AnalyticsProfileId = "23177177";
VisitorsOverview1.FromDate = new DateTime(2009, 11, 1);
VisitorsOverview1.ToDate = new DateTime(2010, 1, 8);

I found that many user use the Web Property ID (UA-XXXXXXXX-X) as AnaliticsProfileId and get error.
Following are the step to get your desire profile id from your analytic account

1) Go to the edit profile on analytic home page after login.

2) the page display your profile detail and you get your profile id over here
Use this id with the AnalyticsProfileId property of control to display the data.