2012-08-27

How to get date and time in a different Time Zone

To get the Date and time for a different time zone, first we need to create a TimeZoneInfo object from the required time zone, as below

TimeZoneInfo timezone = TimeZoneInfo.FindSystemTimeZoneById("Central Time zone");

Here I’m passing the Central Time Zone as the Time zone. To get the equivalent date time representation of a particular date time, we have to use the ConvertTime method and pass the TimeZoneInfo object as shown below

DateTime dateTime = TimeZoneInfo.ConvertTime(DateTime.Now, timezone);

So altogether, to get the current date and time for the Central Time zone, the final code looks like below

TimeZoneInfo timezone = TimeZoneInfo.FindSystemTimeZoneById("Central Time zone");

DateTime dateTime = TimeZoneInfo.ConvertTime(DateTime.Now, timezone);

2012-08-24

Programmatically load a video to embedded Windows Media player

To load video from code behind to the embedded windows media player in a web page, you can refer to the sample code below.

ASPX

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="WebApplication1.WebForm1" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
</head>
<body>
    <form id="form1" runat="server">
    <object id="MediaPlayer" width="192" height="190" classid="CLSID:22D6F312-B0F6-11D0-94AB-0080C74C7E95"
        standby="Loading Windows Media Player components..." type="application/x-oleobject">
        <param name="FileName" id="file" runat="server" />
        <param name="ShowControls" value="true" />
        <param name="ShowStatusBar" value="false" />
        <param name="ShowDisplay" value="false" />
        <param name="autostart" value="false" />
    </object>
    </form>
</body>
</html>

Code behind (C#)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace WebApplication1
{
    public partial class WebForm1 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            file.Attributes.Add("value", @"E:\MyHardDisk\Videos\English\where.have.you.been.avi");
        }
    }
}

How to grant folder permissions to the IUSR

To perform certain tasks we need to grant read/write access to the IUSR for some folders in our website. I will describe how to grant write permission for the IUSR for particular folder.

1. Right click on the folder and choose ‘Properties’

1

2. Select ‘Security’ tab  and click ‘Edit…’ button

2

3. Then Click ‘Add…’ button. On the dialog box, type IUSR and click OK

3

4. Now you can see the IUSR in the ‘Groups or user names:’ list. Select that user and tick the ‘Write’ permission checkbox. And then click OK for both and you are done.

4

2012-08-14

Change the background color of Visual Studio

Sometimes, to save the energy and all, we need to change the default background color of the Visual Studio Editor (When the screen is dark, the light emitting from the monitor isn’t powerful so it preserve the energy). So to do that, you can follow the below instructions

Go to Tools->Options->Fonts and Colors

From the Show Settings for: dropdown list, select Text Editor. From the list, select Plain Text. Now you can change the Item background from the drop down list or by pressing the Custom... button.

2012-08-13

How to programmatically add users and assign them to roles in asp.net membership provider

First of all we have to import the Security namespace as below

using System.Web.Security;

By using the below line, we can create users programmatically. Below I’m creating a user named “Ruchira” with password “Password”.

MembershipUser newUser = Membership.CreateUser("Ruchira", "Password");

By using the below line, we can programmatically assign the user to a particular role. Here I’m assigning the user named “Ruchira” (Which I created above) to the role named “RoleName”

Roles.AddUserToRole("Ruchira", "RoleName");

So altogether, the code would be looks like below

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Security;

namespace WebApplication2
{
    public partial class WebForm1 : System.Web.UI.Page
    {

        protected void Page_Load(object sender, EventArgs e)
        {
            MembershipUser newUser = Membership.CreateUser("Ruchira", "Password");
            Roles.AddUserToRole("Ruchira", "Role");
        }

    }
}

How to set Default Document from web.config file

Apart from setting the default document in IIS, we can directly set the default document for a particular website from the web.config file.

<system.webServer>
  <defaultDocument>
    <files>
      <clear />
      <add value="Test.aspx" />
    </files>
  </defaultDocument>
</system.webServer>

Here, I clear all the other pages in the default document list and add the Test.aspx file to the list.

2012-08-10

How to rotate an asp:Lable

There is actually no one perfect code which works in every browser. We have to make use of few codes together in order to get it work in all the major browsers. Following demonstrates how to rotate a label text by 90 degrees.

<style>
  .test
  {
    -moz-transform: rotate(90deg); /* FF3.5+ */
    -o-transform: rotate(90deg); /* Opera 10.5 */
    -webkit-transform: rotate(90deg); /* Saf3.1+, Chrome */
    filter: progid:DXImageTransform.Microsoft.BasicImage(rotation=90); /* IE6,IE7 */
    -ms-filter: "progid:DXImageTransform.Microsoft.BasicImage(rotation=90)"; /* IE8 */
    -sand-transform: rotate(90deg);
  }
</style>

<asp:Label ID="lblCaseIDVert" runat="server" style="z-index: 100; left: 33px; position: relative; top: 98px" Height="1px" Width="192px" CssClass="test"></asp:Label>

Add a new option for an asp:DropDownList from javascripts

With using pure javascripts, we can add a new option dynamically to a dropdown list. Below is an example I’ve created. I’m adding the option ‘Hi’ to the dropdown list on click of the Button.

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="WebApplication2.WebForm1" %>

<!DOCTYPE html>
<html>
<head>
    <script type="text/javascript">
        function addItem() {
            var option = document.createElement("option");
            option.text = "Hi";
            try {
                // for IE earlier than version 8
                document.getElementById("<%=DropDownList1.ClientID%>").add(option, x.options[null]);
            }
            catch (e) {
                document.getElementById("<%=DropDownList1.ClientID%>").add(option, null);
            }
        }
    </script>
</head>
<body>
    <form id="Form1" runat="server">
    <asp:Button ID="Button1" runat="server" Text="Button" OnClientClick="addItem(); return false;" />
    <p>
        Options-
        <asp:DropDownList ID="DropDownList1" runat="server">
        </asp:DropDownList>
    </p>
    </form>
</body>
</html>

How to get the User ID of currently logged in user

When using asp.net membership provider, sometimes we need to get the user ID of the logged in user. We can get it like below.

Guid userGuid = (Guid)Membership.GetUser().ProviderUserKey;

Convert image to a byte array in ASP.Net

Following example shows how to take the byte representation of an image.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;

namespace WebApplication2
{
    public partial class _Default : System.Web.UI.Page
    {

        protected void Page_Load(object sender, EventArgs e)
        {
            string strPhoto = (@"C:\\Webcam.jpg");
            FileStream fs = new FileStream(strPhoto, FileMode.Open, FileAccess.Read);

            Byte[] imgByte = new byte[fs.Length];

            fs.Read(imgByte, 0, System.Convert.ToInt32(fs.Length));
        }

    }
}

2012-08-06

How to access a controller inside an asp:CreateUserWizard

In C#

Label lbl = (Label)RegisterUser.CreateUserStep.ContentTemplateContainer.FindControl("DisplayWelcomeMessageLabel"));

Here the RegisterUser is the ID of the asp:CreateUserWizard control.

<asp:CreateUserWizard ID="RegisterUser" runat="server" EnableViewState="false" OnCreatedUser="RegisterUser_CreatedUser">

……….

</asp:CreateUserWizard>

Get source code of a webpage using jQuery

With the help of below jQuery snippet, we can get the source code of a particular webpage.

<script type="text/javascript">
    var url = "test.html";

    $.get(url, function (data) {
        alert("Page Source: " + data);
    });
</script>

2012-08-01

How to make asp:TextBox to enter only numbers and round up to two decimal points

With the use of two javascript functions, we can achieve this. First, we should prohibit the user from entering non numeric characters. For that, we can use the below javascript function

function isNumberKey(sender, evt) {
    var txt = sender.value;
    var dotcontainer = txt.split('.');
    var charCode = (evt.which) ? evt.which : event.keyCode;
    if (!(dotcontainer.length == 1 && charCode == 46) && charCode > 31 && (charCode < 48 || charCode > 57))
        return false;

    return true;
}

This function will not allow user to enter anything other than numbers. So the ASPX markup of the textbox should looks like below

<asp:TextBox ID="txtTaxRate" runat="server" OnKeyPress="return isNumberKey(this, event);"></asp:TextBox>

Now, since we allow only numbers in that textbox, we can perform the round up operation for the value.

For that, we can use the below javascript function

function mathRoundForTaxes(source) {
    var txtBox = document.getElementById(source);
    var txt = txtBox.value;
    if (!isNaN(txt) && isFinite(txt) && txt.length != 0) {
       var rounded = Math.round(txt * 100) / 100;
       txtBox.value = rounded.toFixed(2);
    }
}

This function will round up the entered numeric value. So altogether, final markup for the textbox should looks like below

<asp:TextBox ID="txtTaxRate" runat="server" OnKeyPress="return isNumberKey(this, event);" onchange="mathRoundForTaxes(this.id);"></asp:TextBox>