Uncategorized

Time Localization using .Net TimeZone API in C#

A time zone is a geographical region in which the same time is used.

You can use the TimeZone class to retrieve information about the current time zone, and to convert times from local time to Coordinated Universal Time (UTC) or vice versa. However, you cannot use the TimeZone class to represent time zones other than the local zone or to handle date and time conversions from one time zone to another. For this purpose, use the TimeZoneInfo class. You can use this class to retrieve information on any time zone defined on the local system, to create custom time zones, and to convert times from one time zone to another.
The TimeZone class supports only a single daylight saving time adjustment rule for the local time zone. As a result, the TimeZone class can accurately report daylight saving time information or convert between UTC and local time only for the period in which the latest adjustment rule is in effect. In contrast, the TimeZoneInfo class supports multiple adjustment rules, which makes it possible to work with historic time zone data.

Lets go to an example .

If you have an Application which will be used in so many Countries and every User comments on a Note in your Site and When Another User logs in , He wants to see the comment Time in His own TimeZone , not in your time Zone . Like If a person from Switzerland comments on a Note at 9.00 AM , after that when I log in I want to see that in my Time Zone Of Bangladesh which should be 1.00 PM . I used same concept few years back in one of My Sites and its awesome ūüôā

Its better to Keep the DateTime Columns as UTC Date and Then convert to User’s own TimeZone By his TimeZoneId using .Net TimeZone API .

Your Site Can have a UI which would be used by The User to Set his Own Time Zone when he gets Registered Into your Site. So That UI can be like below :::

ddlTimeZone

And You can easily populate The Time Zone List DropDown .

Here is Asp.Net markup for that :

<asp:DropDownList ID="ddlTimeZoneId" runat="server">
                </asp:DropDownList>

And Binding DropDown Code will be like :::

private void LoadTimeZoneDropDown()
        {
            ddlTimeZoneId.DataSource = clsTimeZone.GetTimeZones();
            ddlTimeZoneId.DataTextField = "TimeZoneName";
            ddlTimeZoneId.DataValueField = "TimeZoneID";
            ddlTimeZoneId.DataBind();
        }

This clsTimeZone is my custom Class which is using .Net APIs . And I used This below Method to Get the Time Zone List .

public static Collection<structTimeZone> GetTimeZones()
        {
            Collection<structTimeZone> structTimeZoneColl = new Collection<structTimeZone>();

            ReadOnlyCollection<TimeZoneInfo> timeZoneInfos = TimeZoneInfo.GetSystemTimeZones();
            foreach (TimeZoneInfo timeZoneInfo in timeZoneInfos)
            {
                structTimeZoneColl.Add(new structTimeZone { TimeZoneName = timeZoneInfo.DisplayName, TimeZoneID = timeZoneInfo.Id });
            }
            return structTimeZoneColl;
        }

public struct structTimeZone
    {
        public string TimeZoneName { get; set; }
        public string TimeZoneID { get; set; }
    }

From here , User can set his Own Time Zone from the List which .Net Framework or Windows or Microsoft supports.

So your User Table should have Column like this :::

TimeZoneIdColumn

So your Initial Setup is done .

Now When Any User from Switzerland saves Note to Notes Table , then don’t Use Local DateTime rather use UTC Time .

It can be done by using this SQL In your StoredProcedure .

GETUTCDATE()

So your DB Table will hold UTC , so you can easily convert that to any Localized format , to any Time Zone by your TimeZoneId of that User .

So When need to show the Time to UI , just call This method which will return Local time Zone Info . In my Case I did something like this :::

DateTime localTime = clsTimeZone.ConvertToLocalTimeFromUtcTime(utcDate, timeZoneId);

And the implementation of the Method is just simple like below :::

public static DateTime ConvertToLocalTimeFromUtcTime(DateTime utcDate, string timeZoneId)   
        {
            TimeZoneInfo cstZone = TimeZoneInfo.FindSystemTimeZoneById(timeZoneId);
            DateTime cstTime = TimeZoneInfo.ConvertTimeFromUtc(utcDate, cstZone);
            return cstTime;
        }

Just Show that Local Time To The UI .
So you are done ūüôā

Cheers

Standard
Uncategorized

Get connection String from Web.config in ASP.Net and C#

“Human Brain is amazing , When I don’t want to save something inside my Brain , It also does not want to save it and literally it does not do that. ” – This line is true for me ūüôā

And I always go to my previous written Code + Config file (Or Web) to know how to get Connection String from Web.config . I don’t want to use my Processor of the Brain a minimal percentage for this , And I guess , There are also so many people out there in the world , so this Post is for you guys ūüôā

So in my Web.config/App.config file , I will add the below thing .

  <connectionStrings>   
    <add name="connectionStr" connectionString="Data Source=MASOOM-PC;Initial Catalog=ProjectManagerDB;Integrated Security=True" providerName="System.Data.SqlClient" />
  </connectionStrings>

And Below is the C# code for that .

string connectionString = ConfigurationManager.ConnectionStrings["connectionStr"].ConnectionString;

We can also add Node to AppSettings in Web.config and can get it easily .

<appSettings>
    <add key="EmailTo" value="emailid@yahoo.com" />
  </appSettings>

And this is how we can get this in C#

string emailTo = ConfigurationSettings.AppSettings["EmailTo"];

In future , I will definitely come to my own Blog for this ūüôā Cheers

Standard
Uncategorized

Create Dynamic DataTable in C#

Many a time , we need to create DataTable dynamically inside our C# Code . So this is the easiest way how we can create DataTable dynamically and add data to it .

DataTable dtDatabaseInfo = new DataTable("tblData");
            dtDatabaseInfo.Columns.Add("ID", typeof(string));
            dtDatabaseInfo.Columns.Add("Destination", typeof(string));
            dtDatabaseInfo.Columns.Add("ServerName", typeof(string));
            dtDatabaseInfo.Columns.Add("sDB_Name", typeof(string));
            dtDatabaseInfo.Columns.Add("DbUserName", typeof(string));
            dtDatabaseInfo.Columns.Add("DbPassword", typeof(string));

            DataRow row = dtDatabaseInfo.NewRow();

            row["ID"] = "M001";
            row["Destination"] = "MyDestination";
            row["ServerName"] = "MyLocalServer";
            row["sDB_Name"] = "MyDatabase";
            row["DbUserName"] = "MyUser";
            row["DbPassword"] = "MyPassword";
            dtDatabaseInfo.Rows.Add(row);

Standard
AngularJS, HTML5

AngularJS Routing : Part 2 – make # (Hash) invisible from URL in SPA

Before reading this Article , Please check out AngularJS Routing : Part 1 Create a Single Page Application (SPA) first .

Every AngularJS Dev likes the way that the routing of AngularJS works . It uses # (Hash) in the URL like below –

###

But Its not very readable for Public User , non Tech people , mass people of the world , so its better to make the # invisible from the URL . And Yes, Its real EASY !!!

First Set the Html5Mode to true in LocationProvider . Now the app.js file will be like :::

spaApp.config(function ($routeProvider, $locationProvider) {

    $locationProvider.html5Mode(true);

    $routeProvider.when("/", { templateUrl: "/partials/home.html" }).
                   when("/profile", { templateUrl: "/partials/profile.html" }).
                   when("/contact", { templateUrl: "/partials/contact.html" }).
                   otherwise({ redirectTo: '/' });

});

And my index.html code will be like below now :::

<tr>
                <td>
                    <a href="/">Home <i class="icon-arrow-down"></i></a>
                </td>
                <td>
                    <a href="/profile">Profile <i class="icon-arrow-down"></i></a>
                </td>
                <td>
                    <a href="/contact">Contact <i class="icon-arrow-down"></i></a>
                </td>
            </tr>

My SPA Site is now without that # …

#less

Standard
AngularJS, HTML5

AngularJS Routing : Part 1 – Create a Single Page Application (SPA)

A single-page application (SPA), also known as single-page interface (SPI), is a web application or web site that fits on a single web page with the goal of providing a more fluid user experience akin to a desktop application.

And developing SPA has been so easier with AngularJS Route Service .

Application routes in Angular are declared via the $routeProvider, which is the provider of the $route service. This service makes it easy to wire together controllers, view templates, and the current URL location in the browser. Using this feature we can implement deep linking, which lets us utilize the browser’s history (back and forward navigation) and bookmarks.

I am gonna show how to build simple SPA within 1 hour ūüôā

Here is my index.html Code ::: (ASP.Net developers can think this index.html as MasterPage)

<!DOCTYPE html>
<html ng-app="SpaApp">
<head>
    <meta charset="utf-8" />
    <title>My SPA Site</title>
    <script src="lib/angular.min.js" type="text/javascript"></script>    
    <script src="app/app.js" type="text/javascript"></script>
    <link href="styles/bootstrap.css" rel="stylesheet" type="text/css" />
</head>
<body>
    <div>
        <a href="/">
            <h1>My SPA Site</h1>
        </a>
        <br />
        <table>
            <tr>
                <td>
                    <a href="/">Home <i class="icon-arrow-down"></i></a>
                </td>
                <td>
                    <a href="#/profile">Profile <i class="icon-arrow-down"></i></a>
                </td>
                <td>
                    <a href="#/contact">Contact <i class="icon-arrow-down"></i></a>
                </td>
            </tr>
        </table>
        <br />
         <div ng-view></div>
    </div>
</body>
</html>

The $route service is usually used in conjunction with the ngView directive. The role of the ngView directive is to include the view template for the current route into the layout template, which makes it a perfect fit for our index.html template.

(This ngView directive can be compared as Main ContentPlaceHolder of ASP.Net , just saying for .Net Devs )

My app.js code is like below :::

var spaApp = angular.module('SpaApp', []);

spaApp.config(function ($routeProvider) {

    $routeProvider.when("/", { templateUrl: "/partials/home.html" }).
                   when("/profile", { templateUrl: "/partials/profile.html" }).
                   when("/contact", { templateUrl: "/partials/contact.html" }).
                   otherwise({ redirectTo: '/' });

});

In this RouteProvider we can define URL and HTML Template .

And For this App , I have 3 Partial Views . The codes of these views are like below :::

home.html
———-

<div>
    <h2>This is Home Page</h2>
</div>

profile.html
————-

<div>
    <h2>This is Profile Page</h2>
</div>

contact.html
————-

<div>
    <h2>This is Contact Page</h2>
</div>

So Here , you are done with the simple SPA Site ūüôā

The Site will look like – >

#

To Read Part 2 -> Please Click AngularJS Routing : Part 2 ‚Äď make # (Hash) invisible from URL in SPA

Standard

My Index.html looks like :::

<!DOCTYPE html>
<html ng-app="myModule">
<head>
    <title>Dom Magic</title>   
    <script src="lib/jquery-1.9.1.min.js"></script>
    <script src="lib/angular.min.js"></script>
    <script type="text/javascript" src="dom.js"></script>
    <link rel="stylesheet" href="styles/dom.css">
</head>
<body>
<my-widget>
    <div id="one" class="RedBox"></div>
    <div id="two" class="GreenBox"></div>
</my-widget>
</body>
</html>

After running this WebApp , We will see the UI like this Image …

Blog

My dom.css has this style :::

.RedBox
{
    position: relative;
    background-color: RED;
    width: 100px;
    height: 100px;
    float: left;
    margin: 5px;
    cursor: pointer
}

.GreenBox
{
    position: relative;
    background-color: GREEN;
    width: 100px;
    height: 100px;
    float: left;
    margin: 5px;
    cursor: pointer
}

My dom.js has the directive (Custom HTML Tag) which is used at index.html page .

var myModule = angular.module('myModule',[]);

myModule.directive('myWidget', function () {
    linkFn = function (scope, element, attrs) {

        var boxOne = element.children()[0];
        var boxTwo = element.children()[1];

        var animateRight = function () {
            $(this).animate({
                left: '+=50'
            })
        }

        var animateDown = function () {
            $(this).animate({
                top: '+=50'
            })
        }

        $(boxOne).click(animateDown);
        $(boxTwo).click(animateRight);
    };

    return {
        restrict: 'E',
        link: linkFn
    }
});

AngularJS

AngularJS – DOM Manipulation With Custom Directive and jQuery Animation

Image
AngularJS

Custom HTML Tag !!! Shocked ? Easy with AngularJS – Directive

Directives are a way to teach HTML new tricks. During DOM compilation directives are matched against the HTML and executed. This allows directives to register behavior, or transform the DOM.

Directives can be used to create custom HTML tags that serve as new, custom widgets. They can also be used to ‚Äúdecorate‚ÄĚ elements with behavior and manipulate DOM attributes in interesting ways.

First We need to Add AngularJS Library , and add reference on our Index.html Page . Index.html page code looks like below :::

<!DOCTYPE html>
<html ng-app="HelloWorldApp">
<head>
    <title>My Custom HTML Tag Directive</title>
    <script type="text/javascript" src="lib/angular.min.js"></script>
    <script src="app/MyDirective.js" type="text/javascript"></script>
</head>
<body>
<hello-world></hello-world>
</body>
</html>

Here We can see is not an HTML tag , but we can create a custom HTML tag easily by using AngularJS Directive.

Here is my AngularJS code of MyDirective.js :::

angular.module('HelloWorldApp', [])
    .directive('helloWorld', function () {
        return {
            restrict: 'E',
            template: '<div style="background-color:#D8D8D8;">Hello World By Shahjada</div>'
        }
    });

Standard
Uncategorized

Binding ASP.Net GridView with Custom Columns

In ASP.Net( aspx ) Markup will be like below :::

<asp:GridView ID="gvTicketDetails" runat="server" AutoGenerateColumns="false">       
                 <Columns>           
            
                       <asp:TemplateField HeaderText="Tk#" >
                            <ItemTemplate>
                                <asp:Label ID="lblTicketNo" runat="server" Text='<%#Bind("TicketNum") %>'></asp:Label>            
                            </ItemTemplate>       
                       </asp:TemplateField>
                    
                        <asp:TemplateField HeaderText="Ticket Title">
                            <ItemTemplate>            
                                <asp:Label ID="lblTaskTitle" runat="server" Text='<%#Bind("TicketTitle") %>'></asp:Label>            
                            </ItemTemplate>       
                       </asp:TemplateField>        
                  
                        <asp:TemplateField HeaderText="Responsible Person" >
                            <ItemTemplate>            
                                <asp:Label ID="lblComment" runat="server" Text='<%#Bind("FirstName") %>'></asp:Label>            
                            </ItemTemplate>       
                       </asp:TemplateField>

                        <asp:TemplateField HeaderText="">
                            <ItemTemplate>
                              <a href="ViewTicketNotes.aspx?TicketNum=<%# Eval("ProjectTicketNum") %>&&ProjectID=<%# Eval("tblProjects_ID") %>&&TblTicketsDetails_ID=<%# Eval("tblTicketsDetails_ID") %>&&TicketTitle=<%# Eval("TicketTitle") %>" target="_blank" >View Ticket Note(s)</a>
                            </ItemTemplate>       
                       </asp:TemplateField>

               </Columns>         
            </asp:GridView>

And The C# code for binding The ASP.Net Grid will be like below :::

DataTable ticketDetaisDT = TicketGateway.GetTicketDetailsForDashboard(projectId, taskStatus);
            gvTicketDetails.DataSource = ticketDetaisDT;
            gvTicketDetails.DataBind();

Standard
Uncategorized

Populate DropDownList from List in SharePoint 2010 Visual Web Part

SPWeb web = SPControl.GetContextWeb(HttpContext.Current);
                SPList supervisorList = web.Lists["SupervisorList"];

                if(supervisorList !=null)
                {
                    ddlSupervisor.Items.Clear();
                    foreach (SPListItem items in supervisorList.Items)
                    {
                        string supervisorName = items["SupervisorName"].ToString();
                        ddlSupervisor.Items.Add(supervisorName);
                    }
                    ddlSupervisor.DataBind();
                }

Standard
SharePoint

Get Current LoggedIn User without Domain Name in SharePoint 2010

private string ReturnCurrentUserWithoutDomainName()
        {
            string currentUserWithDomainName = SPContext.Current.Web.CurrentUser.Name.ToString();
            if (currentUserWithDomainName.Contains("\\"))
            {
                string[] words = currentUserWithDomainName.Split('\\');
                return words[1];
            }
            else
            {
                return currentUserWithDomainName;
            }
        }

Standard