Search This Blog

Tuesday 30 October 2012

Create water mark text box in asp.net/C# using javascript within a single step


How to create a water mark text box in asp.net/C# using javascript 
In some scenario in the project, we need to implement water mark text for each textboxes in the form. It will help user to give right direction to enter proper and valid entries for each textboxes. We can achieve this water mark text boxes easily by using javascript methods.
Javascript method to create water mark text boxes in ASP.Net/C# using javascript
Here we are going to create a small asp.net application to show example of water mark text box creation. In aspx page we are having a textbox for username and a button. In the textbox it will show ‘Enter username’ as water mark style with gray color. When a user click mouse on to the textbox it will hide. Once the user leave the mouse pointer from the textbox without enter any data, it will display water mark text.
ASPX PAGE WITH JAVASCRIPT FOR WATER MARK TEXTBOX
<!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">
 <title>Watermark Textbox Using JavaScript</title>
 <script language="javascript" type="text/javascript">
 function WaterMark(txtName, event) {
 var defaultText = "Enter Username";
 // Condition to check textbox length and event type
 if (txtName.value.length == 0 & event.type == "blur") {
 //if condition true then setting text color 
 //and default text in textbox
 txtName.style.color = "Gray";
 txtName.value = defaultText;
 }
// Condition to check textbox value and event type
 if (txtName.value == defaultText & event.type == "focus") {
 txtName.style.color = "black";
 txtName.value = "";
 }
 }
function WaterMarkPwd(txtName, Password) {
 var defaultText = "Enter Password";
 // Condition to check textbox length and event type
 if (txtName.value.length == 0 & event.type == "blur") {
 //if condition true then setting text color and 
 //default text in textbox
 txtName.style.color = "Gray";
 txtName.value = defaultText;
 }
// Condition to check textbox value and event type
 if (txtName.value == defaultText & event.type == "focus") {
 txtName.style.color = "black";
 txtName.value = "";
 }
 }
 </script>
</head>
<body>
 <form id="form1" runat="server">
 <div>
 <b>UserName:</b>
 <asp:TextBox ID="txtUserName" runat="server" Text="Enter Username" ForeColor="Gray"
 onblur="WaterMark(this, event);" onfocus="WaterMark(this, event);" />
 <asp:Button runat="server" ID="btnLogin" Text="Login" />
 </div>
 </form>
</body>
</html>

Tuesday 23 October 2012

How to maintain scrollposition after post back?


How to maintain scroll position in ASP.Net Pages
When web pages are posted back to the server, by default user is returned to the top of the page. On a large web page, you might have a requirement to scroll down the user automatically to the last position on the page.
MaintainScrollPositionOnPostBack page property can be used to achieve this  in one of the following ways.
  1. Application level:To set the property by default for all pages in the website, open web.config and add the attribute to the pages node.<pages maintainScrollPositionOnPostBack=”true”>
  2. Page Level:for a particular page, open the aspx and set the property<%@ Page MaintainScrollPositionOnPostback=”true” …
  3. Code level: to set the property programmaticallyPage.MaintainScrollPositionOnPostBack = true;

Tuesday 16 October 2012

Import contacts from Gmail using ASP.Net/C# Application


How to import contacts from GMAIL into ASP.Net/C# application
Some of the application especially social network application needs to have the feature for import contacts from our gmail account. By using this feature we can easily import all contacts from our gmail account and can send bulk mail to all or groups in our gmail account
 Is it possible import contacts from GMAIL account using ASP.Net/C# Application?
Of course, we can access and import our gmail contacts into our ASP.Net/C# application using gmail API. GMAIL itself providing some APIs to access gmail accounts from an external applications like ASP.Net or C#. We can call this API from our application by passing our gmail credentials, then will access our account from the application. Here we are demonstrating how we can use GMAIL API to get contacts in GMAIL account using ASP.Net/C# application.
 Very simple Steps to import GMAIL contacts from ASP.Net/C# application
Step-1:  Download Google data API setup.
 Here is the proper link for downloading particular API.
 In this link GMAIL providing so many APIs for communicating with their different project.
 Google.GData.Apps.dll, Google.GData.Client.dll, Google.GData.Contacts.dll, Google.GData.Extensions.dll are the major dll that’s should use for our application.
 Step-2:  Create a very simple ASP.Net application to import contacts from GMAIL. For a simple application, aspx page looks like this
 <html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>IMport Gmail Contacts</title>
</head>
<body>
<form id="frmGmailContacts" runat="server">
<div>
<table>
<tr>
<td>
UserName</td>
<td>
<asp:TextBox ID="txtUsername" runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td>
Password</td>
<td>
<asp:TextBox ID="txtPassword" runat="server" TextMode="Password">
</asp:TextBox>
</td>
</tr>
<tr>
<td>
</td>
<td>
<asp:Button ID="btnImport" runat="server" Text="Import"
onclick="btnImport_Click" />
</td>
</tr>
</table>
</div>
<div>
<asp:GridView ID="gdvContacts" runat="server"></asp:GridView>
</div>
</form>
</body>
</html>
 
Step 3 : In code behind we have to call API for getting contacts on button click event, and assign result set to gridview.

public static DataSet GetGmailContacts(string App_Name, string Uname,
string UPassword)
{
DataSet ds = new DataSet();
DataTable dt = new DataTable();
DataColumn C2 = new DataColumn();
C2.DataType = Type.GetType("System.String");
C2.ColumnName = "EmailID";
dt.Columns.Add(C2);
RequestSettings rs = new RequestSettings(App_Name, Uname, UPassword);
rs.AutoPaging = true;
ContactsRequest cr = new ContactsRequest(rs);
Feed<Contact> f = cr.GetContacts();
foreach (Contact t in f.Entries)
{
foreach (EMail email in t.Emails)
{
DataRow dr1 = dt.NewRow();
dr1["EmailID"] = email.Address.ToString();
dt.Rows.Add(dr1);
}
}
ds.Tables.Add(dt);
return ds;
}
protected void Button1_Click(object sender, EventArgs e)
{
DataSet ds = GetGmailContacts("Import GMAIL Contacts",
txtUsername.Text, txtPassword.Text);
gdvContacts.DataSource = ds;
gdvContacts.DataBind();
}

Tuesday 9 October 2012

How to deploy sync framework to windows azure/Deploy sync framework project to windows azure


Deployment of sync framework workerrole / webrole project into azure environment
The article is going to explain that how we can deploy sync framework worker role or webrole projects created in Visual Studio into azure environment. We have created a worker role application that sync azure databases frequently. We are using Sync Framework 2.1 for sync database in the azure. Once it is completed the application, the challenge was to deploy this sync framework to azure platform. We have to include some dlls and also need to do some configuration settings to deploy project into Windows Azure platform
 Steps to do for deploying Sync Framework Project into Azure
 1.Open your Windows Azure Cloud Service project in Visual Studio >> In the Solution Explorer, right-click the
Web Role project, point to Add, and then click Add Reference.
2.Add references to Microsoft.Synchronization.dll, Microsoft.Synchronization.Data.dll, and Microsoft.Synchronization.Data.SqlServer.dll from Sync Framework 2.1
installation folder most of the time it is C:\Program Files (x86)\Microsoft Sync Framework\2.1.
3.Select all files and take the Properties window, then set the value of Aliases property to global and
Copy Local property to True.
4.Create a class file named activationcontext.cs file with the following content and add the file to
Workerrole/Webrole project.
 using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Runtime.InteropServices;
using System.IO;

namespace Microsoft.Samples.Synchronization
{
    public class ActivationContext
    {
        // Activation Context API Functions

        [DllImport("Kernel32.dll", SetLastError = true)]
        private extern static IntPtr CreateActCtx(ref ACTCTX actctx);

        // Activation context structure
        private struct ACTCTX
        {
            public int cbSize;
            public uint dwFlags;
            public string lpSource;
            public ushort wProcessorArchitecture;
            public ushort wLangId;
            public string lpAssemblyDirectory;
            public string lpResourceName;
            public string lpApplicationName;
        }

        private const int ACTCTX_FLAG_ASSEMBLY_DIRECTORY_VALID = 0x004;
        private const int ACTCTX_FLAG_SET_PROCESS_DEFAULT = 0x00000010;
        private IntPtr m_hActCtx = (IntPtr)0;
        public const UInt32 ERROR_SXS_PROCESS_DEFAULT_ALREADY_SET = 14011;

     /// <summary>
     /// Explicitly load a manifest and create the process-default activation
     /// context. It takes effect immediately and stays there until the process exits.
    /// </summary>
        static public void CreateActivationContext()
        {
            string rootFolder = AppDomain.CurrentDomain.BaseDirectory;
            string manifestPath = Path.Combine(rootFolder, "webapp.manifest");
            UInt32 dwError = 0;

            // Build the activation context information structure
            ACTCTX info = new ACTCTX();
            info.cbSize = Marshal.SizeOf(typeof(ACTCTX));
            info.dwFlags = ACTCTX_FLAG_SET_PROCESS_DEFAULT;
            info.lpSource = manifestPath;
            if (null != rootFolder && "" != rootFolder)
            {
                info.lpAssemblyDirectory = rootFolder;
                info.dwFlags |= ACTCTX_FLAG_ASSEMBLY_DIRECTORY_VALID;
            }

            dwError = 0;

            // Create the activation context
            IntPtr result = CreateActCtx(ref info);
            if (-1 == result.ToInt32())
            {
                dwError = (UInt32)Marshal.GetLastWin32Error();
            }

            if (-1 == result.ToInt32() &&
ActivationContext.ERROR_SXS_PROCESS_DEFAULT_ALREADY_SET != dwError)
            {
                string err = string.Format("Cannot create process-default win32 sxs context,
error={0} manifest={1}", dwError, manifestPath);
                ApplicationException ex = new ApplicationException(err);
                throw ex;
            }
        }
    }
}
5.Add a folder named synchronization.assemblies to the Web Role/ Worker Role project and add the following five files to the folder.
 Microsoft.Synchronization.dll
Microsoft.Synchronization.Data.dll
Microsoft.Synchronization.Data.SqlServer.dll
Synchronization21.dll
 Create a file named synchronization.assemblies.manifest, add the following content, and add the file to this folder.
 <?xml version='1.0' encoding='UTF-8' standalone='yes'?>
<assembly xmlns='urn:schemas-microsoft-com:asm.v1' manifestVersion='1.0'>
<assemblyIdentity
type="x64"
name="synchronization.assemblies"
version="2.1.0.0"/>
<file name = "synchronization21.dll">
<comClass clsid="{EC413D66-6221-4ebb-AC55-4900FB321011}"
threadingModel="Both"/>   
</file>
</assembly>
6.Multiple-select all files under synchronization.assemblies folder, right-click, and then click Properties.
Set the value of Build Action property to Content and Copy To Output Directory to Copy Always.
7.Create a file named webapp.manifest, add the following content, and add the file to the Web Role project.
<?xml version='1.0' encoding='UTF-8' standalone='yes'?>
<assembly xmlns="urn:schemas-microsoft-com:asm.v1" manifestVersion="1.0">
<assemblyIdentity name="webapp" version="8.0.0.0" type="x64"/>
<dependency>
<dependentAssembly>
<assemblyIdentity name="synchronization.assemblies" version="2.1.0.0" type="x64"/>
</dependentAssembly>
</dependency>
</assembly>
 8.Set the value of Build Action property to Content and Copy To Output Directory to Copy Always for the webapp.manifest file using Properties window.
9.Add the following statement to the OnStart method before base.OnStart method call in the WebRole.cs file.
 Microsoft.Samples.Synchronization.ActivationContext.CreateActivationContext();

Tuesday 2 October 2012

How to implement leading zero to the variable in the SQL Server/Azure


Leading zero to the variable in SQL Server
To implement leading zero to the variable in SQL Server 2008, we can use following script. In some scenario we have to leading zero to the selected values from SQL server table as per the number of digits in the selected value.
 Create a table in SQL Server  
CREATE TABLE Employee(Code INT);
We can insert values in to the age column of the Employee table
    INSERT Employee VALUES(’13′);
    INSERT Employee VALUES(’111′);
    INSERT Employee VALUES(’12′);
    INSERT Employee VALUES(’322′);
    INSERT Employee VALUES(’422′);
1 row(s) affected.
1 row(s) affected.
1 row(s) affected.
1 row(s) affected.
1 row(s) affected.
 Select Code from Employee table
 SELECT * FROM Employee;
 Code
13
111
12
322
422
5 row(s) affected.
 How to Format column value foor leading zero in SQL Server
Now we are going to implement leading zero to each code up to the 4 digits.
 SELECT RIGHT('0000'+ CONVERT(VARCHAR,Code),4) AS EmployeeCode FROM Employee;
 EmployeeCode
0013
0111
0012
0322
0422
 If we want to format with 6 digits can use following scripts
SELECT RIGHT('000000'+ CONVERT(VARCHAR,Code),6) AS EmployeeCode FROM Employee;