Friday, August 2, 2013

show popup window minimized

var win;

    function openWindow() {
        if (win == null || win.closed == true) {
            win = window.open('Help.htm', 'Help', 'top=150,left=200,width=450,height=250,resizable=yes,scrollbars=yes');
            win.focus();
            return false;
        } else {
            win.target = "Help.htm";
            win.focus();
            return false;
        }
    }
How to call

OnClientClick="javascript:return openWindow();"

Wednesday, November 28, 2012

Creating multilingual websites

  • To create a multilingual application we need .resx (Resource) file.
  • The .resx file is an XML file, which contains Name and a value.
  • The value in the resource file is substituted at run-time.
  • The file name of the resource file should be name of the aspx file.
e.g. if our aspx file name is Test.aspx, then our resource file name should be Test.aspx.resx(Default resource file for the aspx file).
Test.aspx.en-US.resx (aspx file Name.Culture.resx)

To view the code inside the resx file, Right-click -> View Code

Home US

The data tag contains the string and the value.

To set the culture to the controls and to select the correct resource file we have to set the propertis Culture and UICulture

This two properties are available form the class System.Web.UI.Page

How to attach this value to the server controls?

Import the library
  • System.Threading
  • System.Globalization
There are two types of Asp.Net Folders
  • App_LocalResources
  • App_GlobalResources
App_LocalResources
Resource files for each aspx file
The resource file is embeded with the dll file.
App_GlobalResources
Global resource can be read from any page or code that is in the application.
If we are having some text, which is repeated in most of the pages, have the key and value.

Naming conversion for the resource file
<pagename>.aspx.<language>.resx

Type 1:LocalResources
Implicit coding for App_LocalResources

in the page directive add
Culture="auto:en-US" UICulture="auto"

meta:resourceKey="Label1"
in resx file, we have it as Label1.Text as the key name.

meta:resourceKey is called as ambient language

By default our default language is English
How change the language in Browser Settings
Internet Options -> Languages -> Add -> Chinese [Simplified]
Change the default order

If we are having a Label control, and how can we apply localization,
<asp:Label ID="Label1" runat="server" Text="Label" ForeColor="green"></asp:Label>
<asp:Label ID="Label1" runat="server" meta:resourceKey="Label1"></asp:Label>

In the resx file the name of each property is noted as ControlID.Property



Type 2:App_GlobalResources
App_GlobalResources

Select control -> Press F4 -> Expression -> Text -> Expression Type -> Resource -> ClassKey=Resource,

ResourceKey = We can do this only for the GlobalResources

Title="<%$ Resources:PageTitle %>"

Type 3:Dynamically change the language
Import the library
System.Threading
System.Globalization

Override the page method called InitializeCulture
This is the place where we have to set the culture.

protected override void InitializeCulture()
    {
        string language = Request.Form["ddlLanguage"];
        if (!String.IsNullOrEmpty(language))
        {
            Culture = UICulture = language;

            //For selecting the resource file for the languate
            Thread.CurrentThread.CurrentCulture = new CultureInfo(language);

            //For date and currencies
            //Language + Location => Locale
            Thread.CurrentThread.CurrentUICulture = CultureInfo.CreateSpecificCulture(language);

            WriteCookie("CultureInfo", language);
        }
        base.InitializeCulture();
    }


public void WriteCookie(string name, string value)
    {
        HttpContext.Current.Response.Cookies.Set(new HttpCookie(name, value));
    }

    public string ReadCookie(string name)
    {
        return Request.Cookies["CultureInfo"] != null ?
            Request.Cookies["CultureInfo"].Value : null;
    }

    //This is not needed, since it will be set in the InitializeCulture()
/*
    protected void ddlLanguage_SelectedIndexChanged(object sender, EventArgs e)
    {
        WriteCookie("CultureInfo", ddlLanguage.SelectedValue);
    }
*/

To get the current culture
System.Globalization.CultureInfo currentCulture = 
System.Threading.Thread.CurrentThread.CurrentCulture;

To change the currency symbol
String.Format("{0:c}", 1000.2);

How to get the currency symbol according to the languagecode
Get Currency Symbol by Language-code

How to get the value from a resource file in code behind
private string GetMessage(string resourceKey)
    {
        return Convert.ToString(this.GetLocalResourceObject(resourceKey));
    }

How to get the value from a resource file in JavaScript
alert('<%= Convert.ToString(this.GetLocalResourceObject
("AlertLocationOrCustomer"))%>');

How to get the value from a resource file in DropDownList/ListBox asp:ListItem
-Select-

Error

//If no any resource file available
Could not find any resources appropriate for the specified culture or the neutral culture. Make sure "Test.aspx.resources" was correctly embedded or linked into assembly "App_LocalResources.root.uhdc5eth" at compile time, or that all the satellite assemblies required are loadable and fully signed.

Title="<%$ Resources:PageTitle %>"
Error parsing attribute 'title': The resource object with key 'PageTitle' was not found.
  • If there is no default resx file.
  • If there is no resx file for the aspx file.
  • If the aspx file in a sub-folder then we have to create a App_LocalResources in side the sub-folder and create the resx file.

How do I localize the column headers in a gridview?
Curtesy
In your bound field add resource key like this:
In your resource file you need to add a key with name

Product.HeaderText and in Value = ????
Similarly you can do the same for footer

Product.FooterText and in Value = ????

How to localize in external javascript file
In the master page add the hidden control.

In the code behind of the master page set the current langauge.
hdnLang.Value = SessionProxy.Search.Language.ToLower();
eg: for, how to localize in external javascript file?
var locale = ($('#ctl00_hdnLang').val() || "en-us");
var show = { "zh-cn": "顯示", "en-us": "Show" };
var hide = { "zh-cn": "隱藏", "en-us": "Hide" };

$('img.image-selector').toggle(
    function () {
        $(this).attr('src', '../images/Show.JPG');
        $(this).attr('title', show[locale]);
    },
    function () {
        $(this).attr('src', '../images/Hide.JPG');
        $(this).attr('title', hide[locale]);
    }
);
Understanding Globalization and Localization in .NET
Using Resources for Localization with ASP.NET
Extending the ASP.NET 2.0 Resource-Provider Model

Asp.net 3.5 Application Architecture and Design- Chapter 9 Localization

Get Currency Symbol by LanguageCode

Friday, November 9, 2012

Setting minDate and maxDate for jquery datepicker

$(function () {
    var dateToday = new Date();
    var startDate = new Date(dateToday.getFullYear(), 
                 dateToday.getMonth(), dateToday.getDate() - 30);
    $("#txtFromDate").datepicker({
        minDate: startDate,
        maxDate: dateToday
    });
    $("#txtToDate").datepicker({
        minDate: startDate,
        maxDate: dateToday
    });
});

Tuesday, September 25, 2012

Various where types

DECLARE @TEMP TABLE
                    (
                                        Name VARCHAR(50),
                                        Sex  CHAR(1)    ,
                                        Age  INT
                    )

INSERT INTO @Temp
SELECT 'Babu', 'M', 31 UNION ALL
SELECT 'Krishna', 'M', 31 UNION ALL
SELECT 'Kanagu', 'M', 31 UNION ALL
SELECT 'rathinam', 'M', 31 UNION ALL
SELECT 'Kumarasamy', 'M', 31 UNION ALL
SELECT 'Suseela', 'F', 31 UNION ALL
SELECT 'Venkatesh', 'M', 31

DECLARE @Name VARCHAR(50),
        @Sex  CHAR(1),
        @Age  INT,
        @Type VARCHAR(50)

Using boolean logic
SELECT * FROM @Temp
WHERE 1 = 1
AND (@Name IS NULL OR Name = @Name)
AND (@Sex IS NULL OR Sex = @Sex)
AND (@Age IS NULL OR Age = @Age)

SET @Name = 'BABU'

SELECT * FROM @Temp
WHERE 1 = 1
AND (@Name IS NULL OR Name = @Name)
AND (@Sex IS NULL OR Sex = @Sex)
AND (@Age IS NULL OR Age = @Age)

SET @Name = 'BABU'
SET @Sex = 'BABU'

SELECT * FROM @Temp
WHERE 1 = 1
AND (@Name IS NULL OR Name = @Name)
AND (@Sex IS NULL OR Sex = @Sex)
AND (@Age IS NULL OR Age = @Age)

Using boolean logic
SET @Type = 'NAME'

SELECT * FROM @Temp
WHERE (@Type = 'NAME' AND Name = @Name)
OR (@Type = 'SEX' AND Sex = @Sex)
OR (@Type = 'AGE' AND Age = @Age)

Using the Case expression
SET @Name = NULL
SET @Sex = NULL
SET @Age = NULL
SELECT * FROM @Temp
WHERE 1 = 1
AND Name = CASE WHEN @Name IS NOT NULL THEN @Name ELSE Name END
AND Sex = CASE WHEN @Sex IS NOT NULL THEN @Sex ELSE Sex END
AND Age = CASE WHEN @Age IS NOT NULL THEN @Age ELSE Age END

SET @Name = 'BABU'
SET @Sex = 'M'
SET @Age = NULL
SELECT * FROM @Temp
WHERE 1 = 1
AND Name = CASE WHEN @Name IS NOT NULL THEN @Name ELSE Name END
AND Sex = CASE WHEN @Sex IS NOT NULL THEN @Sex ELSE Sex END
AND Age = CASE WHEN @Age IS NOT NULL THEN @Age ELSE Age END

SET @Name = 'BABU'
SET @Sex = 'BABU'
SET @Age = NULL
SELECT * FROM @Temp
WHERE 1 = 1
AND Name = CASE WHEN @Name IS NOT NULL THEN @Name ELSE Name END
AND Sex = CASE WHEN @Sex IS NOT NULL THEN @Sex ELSE Sex END
AND Age = CASE WHEN @Age IS NOT NULL THEN @Age ELSE Age END

Using the ISNULL and NULLIF
SET @Name = NULL
SET @Sex = NULL
SET @Age = NULL
SELECT * FROM @Temp
WHERE 1 = 1
AND Name = ISNULL(NULLIF(@Name, NULL), Name)
AND Sex = ISNULL(NULLIF(@Sex, NULL), Sex)
AND Age = ISNULL(NULLIF(@Age, NULL), Age)

SET @Name = 'BABU'
SET @Sex = 'M'
SET @Age = NULL
SELECT * FROM @Temp
WHERE 1 = 1
AND Name = ISNULL(NULLIF(@Name, NULL), Name)
AND Sex = ISNULL(NULLIF(@Sex, NULL), Sex)
AND Age = ISNULL(NULLIF(@Age, NULL), Age)

SET @Name = 'BABU'
SET @Sex = 'BABU'
SET @Age = NULL
SELECT * FROM @Temp
WHERE 1 = 1
AND Name = ISNULL(NULLIF(@Name, NULL), Name)
AND Sex = ISNULL(NULLIF(@Sex, NULL), Sex)
AND Age = ISNULL(NULLIF(@Age, NULL), Age)

Execution plans


Monday, September 24, 2012

Get Currency Symbol by LanguageCode

Tutorial on using CultureInfo and RegionInfo

Creating multilingual websites

Code to set the culture and get the currency symbol for that culture.
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

using System.Threading;
using System.Globalization;

/// 
/// Set the culture and get the currency symbol
/// 
public sealed class MyCulture
{
    public MyCulture()
    {
        //
        // TODO: Add constructor logic here
        //
    }

    public void SetCulture(string CultureCode)
    {
        Thread.CurrentThread.CurrentCulture = 
            CultureInfo.CreateSpecificCulture(CultureCode);

        Thread.CurrentThread.CurrentUICulture = 
            new CultureInfo(CultureCode);
    }

    public string GetCurrencySymbol(string CultureCode)
    {
        SetCulture(CultureCode);

        CultureInfo UsersCulture = Thread.CurrentThread.CurrentCulture;
        RegionInfo myRegion = new RegionInfo(UsersCulture.LCID);

        return myRegion.CurrencySymbol;
    }
}
How to pass the input?
MyCulture obj = new MyCulture();
String symbol = obj.GetCurrencySymbol("ta-IN");

When we are passing the input culture is necessary.
i.e. we have to pass "ta-IN" or "ta" but not "IN".


List of CultureCodes
How to add currency symbol in the gridview?
We can do it both from the server side or from the client side.
//Setting currency symbol from the service side
        protected void grdWithCurrencySign_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow || e.Row.RowType == DataControlRowType.Header)
            {
                MyCulture obj = new MyCulture();
                string symbol = obj.GetCurrencySymbol("ta-in");

                e.Row.Cells[1].Text = symbol + " " + e.Row.Cells[1].Text;
            }
        }

        public string AddCurrency(string amount)
        {
            MyCulture obj = new MyCulture();
            return amount + " " + obj.GetCurrencySymbol("ta-in");
        }

                
                    
                    
                    
                        
                            <%# AddCurrency(Convert.ToString(Eval("Salary")))%>
                        
                    
                
            

Friday, September 21, 2012

GROUP BY and DISTINCT

DECLARE @Team TABLE(EventDate DATETIME, Seconds BIGINT)

INSERT INTO @Team
SELECT '2012-08-25',440 UNION ALL
SELECT '2012-08-25',1232 UNION ALL
SELECT '2012-08-25',1232 UNION ALL
SELECT '2012-08-25',1232 UNION ALL
SELECT '2012-08-25',1232 UNION ALL
SELECT '2012-08-25',1232 UNION ALL
SELECT '2012-08-25',1232 UNION ALL
SELECT '2012-08-25',7740 UNION ALL
SELECT '2012-08-25',18640 UNION ALL
SELECT '2012-08-25',18640 UNION ALL
SELECT '2012-08-25',18640 UNION ALL
SELECT '2012-08-25',512 UNION ALL
SELECT '2012-08-25',512 UNION ALL
SELECT '2012-08-25',512 UNION ALL
SELECT '2012-08-25',512 UNION ALL
SELECT '2012-08-25',512 UNION ALL
SELECT '2012-08-25',512

SELECT EventDate, Seconds FROM @Team

Sum the column Seconds for the group EventDate
SELECT EventDate, SUM(Seconds) Seconds
FROM @Team
GROUP BY EventDate
The value in the column Seconds is summed with the duplicate value.


How to sum the column without duplicate
SELECT EventDate, Sum(DISTINCT Seconds) Seconds 
FROM     @Team 
GROUP BY EventDate

SELECT   EventDate, Sum(Seconds) AS Seconds 
FROM     ( SELECT EventDate, Seconds 
                  FROM @Team 
                  GROUP BY EventDate, Seconds ) AS T 
GROUP BY EventDate

SELECT   EventDate, Sum(Seconds) AS Seconds 
FROM     ( SELECT DISTINCT EventDate, Seconds 
           FROM @Team ) AS T 
GROUP BY EventDate

Thursday, August 30, 2012

Get only business days in a month in SQL SERVER

DECLARE @Start_Date DATETIME
SET @Start_Date = GETDATE()
SET @Start_Date = CONVERT(VARCHAR(25),DATEADD(dd,-(DAY(@Start_Date)-1),@Start_Date),101)

DECLARE @Holiday TABLE(HoliDay DATETIME)

INSERT INTO @Holiday(HoliDay) VALUES('2012-08-15')
 
;WITH MonthDays(day_num, calendar_dt) AS
     ( SELECT 1                                        AS day_num,
             DATEADD(d, -DAY(@Start_Date)+1, @Start_Date ) AS calendar_dt
     
     UNION ALL
     
     SELECT day_num + 1,
            DATEADD(d, 1, calendar_dt)
     FROM   MonthDays
     WHERE  MONTH(DATEADD(d, 1, calendar_dt)) = MONTH(@Start_Date)
     )
--SELECT * FROM MonthDays 

/*
SELECT *, datename(dw, calendar_dt), (DATEDIFF(week, DATEADD(MONTH, DATEDIFF(MONTH, 0, calendar_dt), 0), calendar_dt) +1) as [Week]
FROM MonthDays
WHERE ((DATEPART(dw, calendar_dt) + @@DATEFIRST) % 7) NOT IN (1)
-- 0 for saturday, 1 for sunday

--WHERE ((DATEPART(dw, calendar_dt) + @@DATEFIRST) % 7) NOT IN (0, 1)
--http://msdn.microsoft.com/en-us/library/ms174420(v=sql.90).aspx
*/

SELECT day_num    ,
       calendar_dt,
       WeekDayName,
       [Week]
FROM  ( SELECT day_num                                 ,
               calendar_dt                             ,
               DATENAME(dw, calendar_dt)                                                            AS WeekDayName,
               (DATEDIFF(week, DATEADD(MONTH, DATEDIFF(MONTH, 0, calendar_dt), 0), calendar_dt) +1) AS [Week]
       FROM    MonthDays
       WHERE   ((DATEPART(dw, calendar_dt) + @@DATEFIRST) % 7 ) NOT IN (1)
       ) AS T
WHERE  ( WeekDayName != 'Saturday' 
   OR     [Week] NOT IN (1, 3, 5)
       )
       --To remove the holiday
AND    day_num NOT IN
       (SELECT DATEPART(DD, HoliDay)
       FROM    @Holiday
       )