Pages

Monday, May 30, 2011

Importank Links

Uploading Excel file to SQL Server using SqlBulkCopy

string strConnection = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
protected void Page_Load(object sender, EventArgs e)
{

}
protected void btnUpload_Click(object sender, EventArgs e)
{
//Create connection string to Excel work book
string excelConnectionString
=@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Details.xls;
Extended Properties=""Excel 8.0;HDR=YES;""";

//Create Connection to Excel work book
OleDbConnection excelConnection =new OleDbConnection(excelConnectionString);

//Create OleDbCommand to fetch data from Excel
OleDbCommand cmd = new OleDbCommand("Select [ID],[Name],[Location] from [Detail$]",excelConnection);

excelConnection.Open();
OleDbDataReader dReader;
dReader = cmd.ExecuteReader();

SqlBulkCopy sqlBulk = new SqlBulkCopy(strConnection);
sqlBulk.DestinationTableName = "Details";
sqlBulk.ColumnMappings.Add("ID", "ID");
sqlBulk.ColumnMappings.Add("Name", "Name");
sqlBulk.WriteToServer(dReader);
}

Import Gmail Contacts in Asp.Net

First of all download Google Data API and install to get following dlls
1. Google.GData.Client
2. Google.GData.Contacts
3. Google.GData.Extensions
Put these 3 dlls in BIN folder of application also add reference to your project for them.

using Google.Contacts;
using Google.GData.Client;
using Google.GData.Contacts;
using Google.GData.Extensions;
<b>Email: </b>

<asp:TextBox ID="txtEmail" runat="server"> </asp:TextBox>
<b>Password : </b>
<asp:TextBox ID="txtPassword" runat="server" TabIndex="1" TextMode="Password">
</asp:TextBox>
<asp:Button ID="btnContacts" runat="server"  onclick="btnContacts_Click"
TabIndex="2" Text="Import Contacts"  Width="125px" />
<asp:ListBox ID="lstContacts" runat="server" Height="176px" Width="229px">
 </asp:ListBox>

protected void btnContacts_Click(object sender, EventArgs e)
    {
        //Provide Login Information
        RequestSettings rsLoginInfo = new RequestSettings("", txtEmail.Text, txtPassword.Text);
        rsLoginInfo.AutoPaging = true;

        // Fetch contacts and dislay them in ListBox
        ContactsRequest cRequest = new ContactsRequest(rsLoginInfo);
        Feed <contact> feedContacts = cRequest.GetContacts();
        foreach (Contact gmailAddresses in feedContacts.Entries)
        {
            Console.WriteLine("\t" + gmailAddresses.Title);
            lstContacts.Items.Add(gmailAddresses.Title);
            foreach (EMail emailId in gmailAddresses.Emails)
            {
                Console.WriteLine("\t" + emailId.Address);
                lstContacts.Items.Add(" " + emailId.Address);
            }
        }

    }

Display Auto Number Column in Gridview

<asp:TemplateField HeaderText="Serial Number">
    <ItemTemplate>
        <%# Container.DataItemIndex + 1 %>
    </ItemTemplate>

Check NULL value at serverside using EVAL in Itemtemplate Gridview

<ItemTemplate>
<asp:Label ID="Label1" runat="server" 
           Text='<%# CheckNull(Eval("Location")) %>'>
</asp:Label>
</ItemTemplate>
protected string CheckNull(object objGrid)    
{ if (object.ReferenceEquals(objGrid, DBNull.Value))        
{ return "No Record Found"; }        
else { return objGrid.ToString(); }     
}

Merge gridview headers

Here is the code to merge header of the gridview













<asp:GridView ID="grvMergeHeader" runat="server">
<Columns>
<asp:BoundField DataField="DepartMentID"HeaderText="DepartMentID"SortExpression="DepartMentID" />
<asp:BoundField DataField="DepartMent"HeaderText="DepartMent"SortExpression="DepartMent" />
<asp:BoundField DataField="Name"HeaderText="Name"SortExpression="Name" />
<asp:BoundField DataField="Location"HeaderText="Location"SortExpression="Location" />
</Columns>
</asp:GridView>

protected void grvMergeHeader_RowCreated
(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.Header)
{
GridView HeaderGrid = (GridView)sender;
GridViewRow HeaderGridRow =
new GridViewRow(0, 0, DataControlRowType.Header,
DataControlRowState.Insert);
TableCell HeaderCell = new TableCell();
HeaderCell.Text = "Department";
HeaderCell.ColumnSpan = 2;
HeaderGridRow.Cells.Add(HeaderCell);

HeaderCell = new TableCell();
HeaderCell.Text = "Employee";
HeaderCell.ColumnSpan = 2;
HeaderGridRow.Cells.Add(HeaderCell);

grvMergeHeader.Controls[0].Controls.AddAt
(0, HeaderGridRow);
}
}

Check to see if refresh button is clicked to avoid click event fired again


When we click submit button it runs the code and does its job now, when we press refresh button of the browser it again fires the click event and the code reruns causing the duplicate entry in the database or so.

So to avoid this here is the code-
protected void Page_Load(object sender, EventArgs e)
{
 if (!IsPostBack){Session["CheckRefresh"] =
 Server.UrlDecode(System.DateTime.Now.ToString());
}

}
protected void Button1_Click(object sender, EventArgs e)
{
 if (Session["CheckRefresh"].ToString() ==ViewState["CheckRefresh"].ToString())
 {
  Label1.Text = "Hello";
  Session["CheckRefresh"] =Server.UrlDecode(System.DateTime.Now.ToString());
 }
 else
 {
  Label1.Text = "Page Refreshed";
 }
}

protected void Page_PreRender(object sender, EventArgs e)
{
 ViewState["CheckRefresh"] = Session["CheckRefresh"];
}

Friday, May 27, 2011

Code to upload multiple files using javascript like Gmail

Here is the code to upload multiple files using javascript
Default.aspx
<head runat="server"><title>Untitled Page</title><script language="javascript" type="text/javascript">var counter = 0;
var counter2 = 0;
function AddFileUpload()
{
var div = document.createElement('DIV');
div.innerHTML = '<input id="file' + counter + '" name = "file' + counter +
'" type="file" />' +
'<input id="Button' + counter + '" type="button" ' +
'value="Remove" onclick = "RemoveFileUpload(this)" />';
document.getElementById("FileUploadContainer").appendChild(div);
counter++;
counter2++;
document.getElementById("btnAdd").style.visibility = "visible";
}
function RemoveFileUpload(div)
{
counter2--;
if(counter2 == 0)
document.getElementById("btnAdd").style.visibility = "hidden";
document.getElementById("FileUploadContainer").removeChild(div.parentNode);
}
function DeleteConfirmation()
{
if(confirm('Are You Sure To Delete?'))
return true;
else
return false;
}
</script>head>body><form id="form1" runat="server" enctype="multipart/form-data" method="post"><input id="Button1" type="button" class="inputButton" value="Add New File To Upload"onclick="AddFileUpload()" /><br /><div id="FileUploadContainer"><!--FileUpload Controls will be added here --></div><asp:button id="btnUpload" runat="server" text="Upload" onclick="btnUpload_Click" /></form>body>
</
Default.aspx.cs
protected void btnUpload_Click(object sender, EventArgs e)
{
for (int i = 0; i < Request.Files.Count; i++)
{
HttpPostedFile PostedFile = Request.Files[i];
if (getFileType(PostedFile.FileName) == "Image")
{
if (PostedFile.ContentLength > 0)
{
string FileName = System.IO.Path.GetFileName(PostedFile.FileName).ToString();
int size = PostedFile.ContentLength;
PostedFile.SaveAs(Server.MapPath("Uploads\\") + FileName);
}
}
}
}
string getFileType(string fileName)
{
string ext = Path.GetExtension(fileName);
switch (ext.ToLower())
{
case ".gif":
return "Image";
case ".png":
return "Image";
case ".jpg":
return "Image";
case ".jpeg":
return "Image";
default:
return "Not known";
}
}

</
<

Code to create capcha image using javascript with sound effect

Here are few things that you need to do before you run this code.
1. Create a folder "SoundFiles" at the root of the project.
2. Add reference of "Interop.SpeechLib.dll" file so that it is added in the bin folder.
3. Place the "q.wav" and "sound.png" file at the root of the project.
Here is the code to create capcha image using javascript with sound effect
Default.aspx
<head runat="server"><title>Untitled Page</title>
<script type="text/javascript" language="javascript">
function show()
{
var chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz";

var string_length = 5;
var randomstring = '';
for (var i=0; i<string_length; i++)
{
var rnum = Math.floor(Math.random() * chars.length);
randomstring += chars.substring(rnum,rnum+1);
}
var main = document.getElementById('txt1');
main.value = randomstring;
document.getElementById("Button1").click();

}
</script>
<body>
    <form id="form1" runat="server">
    <div>
        <input type="text" runat="server" id="txt1"  style="border-style: none; border-color: inherit;
            border-width: medium; background-color: black; color: red; font-family: 'Curlz MT';
            font-size: x-large; font-weight: bold; font-variant: normal; letter-spacing: 10pt;padding-left:10px;
            width: 135px;"  />
        <input type="button" onclick="show()" value="Change Capcha Image" />
        <img alt="" src="sound.png" onclick="javascript:playSound();" />      
    </div>
    <asp:TextBox ID="txtverification" runat="server"></asp:TextBox>
    &nbsp;&nbsp;&nbsp;&nbsp;
    <asp:Button ID="Button1" runat="server" Text="Verification" style="display:none" OnClick="btn1_Click" />
    <asp:Button ID="Button2" runat="server" Text="Verification" OnClick="Button2_Click" />
    &nbsp;&nbsp;&nbsp;&nbsp;
    <asp:Label ID="lblmsg" runat="server" Font-Bold="True" ForeColor="Red"></asp:Label>
    <div id="divsound" ></div>
    </form>
</body>
Default.aspx.cs

protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
string script = "<script language='javascript' type='text/javascript'>show();</script>";
ClientScript.RegisterStartupScript(this.GetType(), "script", script);
}
}
protected void Button2_Click(object sender, EventArgs e)
{
if (txtverification.Text == txt1.Value)
{
lblmsg.Text = "Successfull";
}
else
{
lblmsg.Text = "Failure";
}
}
protected void btn1_Click(object sender, EventArgs e)
{
SpeechLib.SpFileStream spfilestream;
string WAVFileName=Convert.ToDateTime(DateTime.Now).ToString("MMddyyyymmss") + ".wav";
File.Copy(MapPath("q.wav"), MapPath("SoundFiles/" + WAVFileName), true);
string filename = MapPath("SoundFiles/" + WAVFileName);
spfilestream = new SpFileStreamClass();
spfilestream.Open(filename, SpeechStreamFileMode.SSFMCreateForWrite, false);
SpeechLib.ISpeechVoice ispvoice1 = new SpVoiceClass();
ispvoice1.AudioOutputStream = spfilestream;
ispvoice1.Speak(txt1.Value.ToString(), SpeechVoiceSpeakFlags.SVSFDefault);
ispvoice1.Rate =10000;
ispvoice1.WaitUntilDone(-1);
spfilestream.Close();
string script = "<script language='javascript' type='text/javascript'> "+
" function playSound() {"+
" document.getElementById('divsound').innerHTML=\"<embed src='SoundFiles/" + WAVFileName + "' hidden='true' autostart='true' loop='false' />\"" +
" } </script>";
ClientScript.RegisterStartupScript(this.GetType(), "script", script);
}

Wednesday, May 25, 2011

Calling a function written in C# from the Vb.net having the same name for two functions but differ by case having the same signature

Calling a function written in C# from the Vb.net having the same name for two functions but differ by case having the same signature.
In this case, we need to use Reflection.
Suppose my C# assembly code looks like:
namespace Test
{
 
public class Class1
  {
    public string hello()
    {
      return "hello";
    }
    public string Hello()
    {
      return "Hello";
    }
  }
}

To call the function "Hello" in vb.net do this:
Dim obj As New Test.Class1
Dim ReturnValue As Object
ReturnValue = obj.GetType.InvokeMember("Hello", _
              System.Reflection.BindingFlags.Instance Or _
              BindingFlags.Public Or BindingFlags.InvokeMethod, _
              Nothing, obj, Nothing, Nothing, Nothing, Nothing)
TextBox1.Text = ReturnValue


InvokeMember function used here Invokes the specified member, using the specified binding constraints and matching the specified argument list. You can find more information on MSDN.
To pass parameters, create an array of Object. Insert parameters required to call the function in the array. Pass the array as a parameter in the InvokeMethod function.

Insert image in SQL Server in binary format without frontend

There are various ways to insert images into the database
CREATE TABLE myTable(Document varbinary(max))
INSERT INTO myTable(Document)
SELECT * FROM
OPENROWSET(BULK N'C:\Image1.jpg', SINGLE_BLOB)

-- or --
UPDATE table
SET column =
(SELECT * FROM
OPENROWSET(BULK N'D:\Filename.aspx', SINGLE_BLOB) AS ORS)
WHERE ID = 2

-- or --
You can also loop to insert images from a particular folder too
DECLARE @imgString varchar(80)
DECLARE @insertString varchar(3000)
SET @imgNumber = 1
WHILE @imgNumber &amp;lt; 101
BEGIN
SET @imgString = 'E:\images\Picture' + CONVERT(varchar,@imgNumber) + '.jpg'
SET @insertString = N'INSERT INTO images(imageData)
SELECT * FROM OPENROWSET(BULK N''' + @imgString + ''', SINGLE_BLOB) as tempImg'

EXEC(@insertString)
SET @imgNumber = @imgNumber + 1
END
GO

Inherit multiple interfaces conflicting method names

To descibe this scenario, I have created a class called ExampleClass that is inheriting two interface IExampleClass1 and IExampleClass2. Both interfaces have same method name and Signature CurrentDateTime(). See the code snippet for them below.


public interface IExampleClass1
{
    string CurrentDateTime();
}
public interface IExampleClass2
{
    string CurrentDateTime();
    string CurrentDateTime(DateTime thisDateTime);
}
public class ExampleClass : IExampleClass1, IExampleClass2
{
    #region IExampleClass2 Members
    public string CurrentDateTime()
    {
        return "Interface 2 : " + DateTime.Now.ToString();
    }
    public string CurrentDateTime(DateTime thisDateTime)
    {
        return "Interface 2 : " + thisDateTime.ToLongDateString();
    }
    #endregion

    #region IExampleClass1 Members
    string IExampleClass1.CurrentDateTime()
    {
        return "Interface 1 : " + DateTime.Now.ToString();
    }
    #endregion
}



ExampleClass ex = new ExampleClass();
lblMessage1.Text = ex.CurrentDateTime();
lblMessage1.Text += "<br />" + ex.CurrentDateTime(DateTime.Now);

IExampleClass1 ex1 = new ExampleClass();
lblMessage2.Text = ex1.CurrentDateTime();

IExampleClass2 ex2 = new ExampleClass();
lblMessage3.Text = ex2.CurrentDateTime();
lblMessage3.Text += "<br />Overload method: " + ex2.CurrentDateTime(DateTime.Now);


OUTPUT:
Interface 2 : 30/08/2012 10:02:20
Interface 2 : 30 August 2012

Interface 1 : 30/08/2012 10:02:20

Interface 2 : 30/08/2012 10:02:20
Overload method: Interface 2 : 30 August 2012

If we inherit these two interfaces into the same class then we will have to implement all the methods defined in these interfaces. Lets see the ways of implementing interface into our class. There are two ways we can implement interfaces into a class.

1. Implement Interface - When we choose this option of implementing interface, we need to define methods name that interface has and need to implement those methods. By default these methods modifiers will be public. This is also called Implicitely implementation of the interface.

#region IExampleClass2 Members
public string CurrentDateTime()
{
    return "Interface 2 : " + DateTime.Now.ToString();
}
public string CurrentDateTime(DateTime thisDateTime)
{
    return "Interface 2 : " + thisDateTime.ToLongDateString();
}
#endregion

2. Implement Interface Explicitely - When you choose this option, you need to define method names that interface has by prefixing the interface name. Notice that there is no access modifier for this method implementation so by default its scope will be internal. Internal is the access modifier for the method or class that is only accessible from the class in same assembly.

#region IExampleClass1 Members
string IExampleClass1.CurrentDateTime()
{
    return "Interface 1 : " + DateTime.Now.ToString();
}
#endregion

If you try to change its access modifier to public in this scenario, you will get "CS0106: The modifier 'public' is not valid for this item" error while running your application. Because there is a public method with the same name and signature already implemented (for IExampleClass2 interface) in the class.

In the above code snippet, you can see that I have instantiated ExampleClass in three different ways. Lets see them one by one.

1. ExampleClass ex = new ExampleClass(); - When we are instantiating the class by specifying the object as the class name, we will be able to call methods for the interface that is implicitely implemented. In this case IExampleClass2.


2. IExampleClass1 ex1 = new ExampleClass(); - If we want to call the method that is explicitely implemented, we need to specify the object as the interface name and instantiate the class then we will be able to call the method of this interface. In this case IExampleClass1.

3. IExampleClass2 ex2 = new ExampleClass(); - You can call methods of the interface that is implicitely implemented by specifying the name of the Interface as the object name (The way we have done in the 2nd point). This will give the same result as the 1st point above.

Now, lets play with the code and remove the implementation of the Interface 1 (IExampleClass1) and then try to run the code. You will see that you are not getting any error even if there is not implementation for the IExampleClass1 interface. This is because the implementation of the method (CurrentDateTime) for IExampleClass2 will be shared for both interfaces. In this case even if we will instantiated the ExampleClass by specifying IExampleClass as the object (point 2 above), we will see that the implementation of IExampleClass2 method is being called.
OUTPUT
Interface 2 : 30/08/2012 10:03:56
Interface 2 : 30 August 2012

Interface 2 : 30/08/2012 10:03:56

Interface 2 : 30/08/2012 10:03:56
Overload method: Interface 2 : 30 August 2012 


Using the cast method
ImplementationClass obj = new ImplementationClass();
IInterface1 if1 = (IInterface1)obj;
if1.MyMethod();

IInterface2 if2 = (IInterface2)obj;
if2.MyMethod();