Tuesday, August 30, 2011

Show client side alert message from server side code even when update panel is used

Developers might want to display client side message with information from server side to their users when they have completed some execution at server side. People may try in different way for this purpose.
For example:
Response.Write() method with JavaScript code inside the method:

string mes = "Hello Dhaka";
        Response.Write("<script language=\"javascript\"  type=\"text/javascript\">alert('" + mes + "');</script>");

or ClientScript.RegisterStartupScript() method:

string message = "<script language=\"javascript\"  type=\"text/javascript\">alert('Hello Dhaka');</script>";
        if (!ClientScript.IsStartupScriptRegistered("mes"))
        {
            ClientScript.RegisterStartupScript(this.GetType(), "mes", message);
        }

But these code doesn't work when you use update panel in your page. So better solution is to use ScriptManager.RegisterStartupScript() method. This works whether update panel is used or not. So let's see the code snippet below:

string message = string.IsNullOrEmpty(TextBox1.Text) ? "Please give a text to textbox." : "You have given: " + TextBox1.Text.Trim();
        string script = "<script language=\"javascript\"  type=\"text/javascript\">;alert('" + message + "');</script>";
        ScriptManager.RegisterStartupScript(Page, this.GetType(), "AlertMessage", script, false);

With this code snippet you can display a modal message that their data was saved or updated successfully or not.

Monday, August 29, 2011

How can I show multiple database columns in gridview databound column?


Solution:

GridView BoundField can only bind to a single field. If you want to do this, you can do so by one of the following ways:
> use calculated column in your database query i.e. concatenate multiple columns to a single column. For example: Select housenumber+', '+street as Address from client
 
> use GridView TemplateField. You can bind individual template in a single TempalteField. Following code snippet shows the trick:

<asp:GridView ID="GridView1" runat="server">
    <Columns>
        <asp:TemplateField HeaderText="Address">
            <ItemTemplate>
                <%#Eval("housenumber")%>, <%#Eval("street")%>
            </ItemTemplate>
        </asp:TemplateField>
    </Columns>
</asp:GridView> 

Friday, August 26, 2011

What are the differences between an interface and abstract class?


Differences between an interface and abstract class:

Interface contains method definition - there is no implementation.  An abstract class some methods can be concrete.  In an interface, no accessibility modifiers are allowed.  An abstract class may have accessibility modifiers. 
Feature
Interface
Abstract class
Multiple inheritance
A class may inherit several interfaces.
A class may inherit only one abstract class.
Default implementation
An interface cannot provide any code, just the signature.
An abstract class can provide complete, default code and/or just the details that have to be overridden.
Constants
Only Static final constants.
Both instance and static constants are possible.
Core VS Peripheral
Interfaces are used to define the peripheral abilities of a class. In other words both Human and Vehicle can inherit from an IMovable interface.
An abstract class defines the core identity of a class and there it is used for objects of the same type.
Homogeneity
If the various implementations only share method signatures then it is better to use Interface.
If the various implementations are of the same kind and use common behavior or status then abstract class is better to use.
Speed
Requires more time to find the actual method in the corresponding classes.
Fast
Adding functionality
If we add a new method to an Interface then we have to track down all the implementations of the interface and define implementation for the new method.
If we add a new method to an abstract class then we have the option of providing default implementation and therefore all the existing code might work properly.

Thursday, August 25, 2011

How can I add external java script and css file dynamically in asp.net?

Problem: 
 I need to add a .css and .js file based on the user logged in. I have the css class attributeds added to all of the elements I need to style. What I need to do now is add the .css and .js file to the page on page load based on logged in user.

Solution:
The conventional way to loading external JavaScript (ie: .js) and CSS (ie: .css) files on a page is to stick a reference to them in the <head> section of your page, for example:
 
<head>
<script type="text/javascript" src="myscript.js"></script>
<link rel="stylesheet" type="text/css" href="main.css" />
</head>

 But keeping JavaScript and CSS functions in a separate file (a .js and .css file) is highly recommended. Once they are in a separate file and part of a project, the file can be imported into a page using RegisterClientScriptBlock method.

For instance, a .js file can be included in an ASP.NET page using the following code:

Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "MyScript",
   "<script language=javascript src='MyJSFile.js'>");

 and for including a .css file same code should rewrite as follows:

Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "MyCSS", 
 "<link rel=\"stylesheet\" type=\"text/css\" href=\"css/MyCSSFile.css\"/>");

 Once the .js file or .css is imported into the ASP.NET page, any of the JavaScript functions, css class and selectors can be called as before.

Tuesday, August 23, 2011

How can I query from multiple sql server database that exist on different machine?

Problem: 
Some questions like following are often asked in communities:
> How can I query from multiple sql server database?
> How can I query from multiple sql server database that exist on different location?
> How to copy one data of one table from one database to another database on different server?


Solution:
The solution for working with multiple database that exist on different server is Four Part Naming. The structure of four part naming is: 
ServerName.DatabaseName.Schema.TableName                         - for multiple database on same server
Linked_Server_Name.DatabaseName.Schema.Object_Name      - for multiple database on different server


First part is your server name or linked server name.
Part two is your database name or catalog name.
Part three is Schema or Database owner name.
Part four is your object or table name.

When you want to query on two database that exist on same server you can try query as follows:

SELECT E.EmployeeId, E.EmployeeName, D.Designation
FROM MyServer.EmployeeInfo.dbo.Employee E, MyServer.HRInfo.dbo.Designation D


But in case of different server you have to create Linked server. You have to add all servers that you want to query to Linked Server list even though it is your local machine. You can visit here to know more about how to create linked server.

When your server is linked they you can query as follows:


SELECT E.EmployeeId, E.EmployeeName, D.Designation

FROM 192.168.102.101.EmployeeInfo.dbo.Employee E, 115.130.18.38.HRInfo.dbo.Designation D

Here IP addresses are name of linked servers.

Hope this will help.
Thanks.

How to add a newline or line break of type nvarchar in sql server?

Problem:
I want to add a newline in a content of sql column.

Solution:
You can use CHAR(13) to insert a carriage return into the string. Following query shows how to insert carriage return to a column:

INSERT INTO Employee(EmployeeId, EmployeeName, Address)
VALUES(1,'Scott Allen','36 Wall Street,'+CHAR(13)+'Onterio, CA')

Sunday, August 21, 2011

How can I measure my web page performance?

Web site speed & performance tuning tool:

There is some excellent tools for web developers for analyzing their web site performance and speed. Two grate tools are YSlow by Yahoo and Google Page Speed. These are found as browser extension or add-on. Another greate one is http://gtmetrix.com/ which combines both Google Page Speed and YSlow into an easy to read, tabbed, table of recommendations.

GTmetrix uses Google Page Speed and Yahoo! YSlow to grade your site's performance and provides actionable recommendations to fix these issues. However, it ranks the groupings of recommendations from low to high so that you can decide which one should be solved first.

If page speed is a fact to you, then these must be useful for you.

How can I convert html web site to asp.net website without loosing existing page ranks?

Problem: 
 I have to convert an existing html website to asp.net website. The thing is that existing website has page rank (PR) for almost all of its pages. Now the challenge is to convert existing website to asp.net without loosing the page ranks.

Solution:
Page ranks can be maintained by permanently redirecting the page to new page. For implementing permanent redirect to a new page you can use 301 redirect. 301 redirect allows visitors and search engines to access a web page after it has been moved. Please visit How Do I Implement a 301 Redirect? to know more details on 301 redirect.

How can I get latest currencry conversion rate?

Problem: 
 I want to build a currency converter on my web page. How can I get latest currency conversion rate from internet?

Solution:

To achieve it you can use web service which provides exchanging rate of currencies or develop this utility by yourself.

Using Web Service please check the links below:

http://www.codeproject.com/KB/webservices/currency_convertor_ws.aspx

You can also implement a custom currency converter:

http://www.codeproject.com/KB/cs/CurrencyConverter_Class.aspx

Saturday, August 20, 2011

How to convert a string to a byte array and a byte array to a string?

Convert from string to byte array:

string strToConvert = "This text need to converted to byte array";
System.Text.UTF8Encoding encoding=new System.Text.UTF8Encoding();
byte[] bArray = encoding.GetBytes(strToConvert);


Convert from byte array to string:

string strToConvert = "This text need to converted to byte array";
System.Text.UTF8Encoding encoding=new System.Text.UTF8Encoding();
byte[] bArray = encoding.GetBytes(strToConvert);System.Text.UTF8Encoding enco =new System.Text.UTF8Encoding();
string strConvertedString = enco.GetString(bArray);

How to send attachment with email?


To attach a file with your mail, add it to the mail by MailMessage.Attachments.Add() method.  The simple way to add a file to mail is to specify the file name.
MailMessage mail = new MailMessage();
 mail.Attachments.Add(new Attachment("FileName.txt"));

You can also specify a MIME content type which requires System.IO and System.Net.Mime namespace in addition to System.Net.Mail. The following code sample demonstrates how to use a Stream as a file attachment and how to specify MIME type:
MailMessage mail = new MailMessage();
Stream sr= new FileStream(@"FileName.txt", FileMode.Open, FileAccess.Read);
Mail.Attachments.Add(new Attachment(sr,” FileName.txt”, MediaTypeNames.Application.Octet));

How can I get a delivery failed notification to sender email when sent email fails to deliver?


MailMessage class have a property named “DeliveryNotificationOptions” and an enumeration of type “DeleiveryNotificationOptions”. DeleiveryNotificationOptions enumeration have values: OnSuccess, OnFailure, Delay, None and Never. You can instruct the SMTP server to send a message to the address of email sender specified in MailMessage.From if message delivery fails, delayed or successfully delivered etc. Following code snippet shows how to set for OnFailure:
MailMessage mail = new MailMessage();
mail.DeliveryNotificationOptions = DeliveryNotificationOptions.OnFailure;

Sending mail to multiple recipient


For sending mail to multiple recipients you can use BCC to send Blind Carbon Copy to each recipient. When you specify recipient in Bcc they will receive message, but the names will not be visible to other recipients.
But instead of using BCC, you should send a separate copy of your message to each recipient that you want to receive blind copy. The problem with BCC is that spam filters frequently block messages that do not have recipient’s email address in the From header. Therefore, if you use BCC, the message will very likely be filtered.
In my previous post I have shown how to send email. Here I would like to rewrite BuildMail() method for sending mail to multiple recipient at a time:
    private MailMessage BuildMail()
    {
        string from, to, bcc, cc, subject, body;
        from = "uniquesaiful@gmail.com";   //Email Address of Sender
        to = "tips.asp.net@gmail.com,saifulondotnet@gmail.com,uniquesaiful@gmail.com";   //Email Address of Receiver
        bcc = "";
        cc = "";
        subject = "This is a test email. I am just checking whether email client is working properly.";
 
        StringBuilder sb = new StringBuilder();
        sb.Append("Hi Scott,<br/>");
        sb.Append("This is a test email. We are testing out email client. Please don't mind.<br/>");
        sb.Append("We are sorry for this unexpected mail to your mail box.<br/>");
        sb.Append("<br/>");
        sb.Append("Thanking you<br/>");
        sb.Append("Tips.Asp.Net");
        
        body =sb.ToString() ;
 
        MailMessage mail = new MailMessage();
        mail.From = new MailAddress(from);
        if (to.Contains(","))
        {
            string[] tos = to.Split(',');
            for (int i = 0; i < tos.Length; i++)
            {
                mail.To.Add(new MailAddress(tos[i]));
            }
        }
        else
        {
            mail.To.Add(new MailAddress(to));
        }
 
        if (!string.IsNullOrEmpty(bcc))
        {
            if (bcc.Contains(","))
            {
                string[] bccs = bcc.Split(',');
                for (int i = 0; i < bccs.Length; i++)
                {
                    mail.Bcc.Add(new MailAddress(bccs[i]));
                }
            }
            else
            {
                mail.Bcc.Add(new MailAddress(bcc));
            }
        }
        if (!string.IsNullOrEmpty(cc))
        {
            if (cc.Contains(","))
            {
                string[] ccs = cc.Split(',');
                for (int i = 0; i < ccs.Length; i++)
                {
                    mail.CC.Add(new MailAddress(ccs[i]));
                }
            }
            else
            {
                mail.CC.Add(new MailAddress(bcc));
            }
            mail.CC.Add(new MailAddress(cc));
        }
 
        mail.Subject = subject;
        mail.Body = body;
        mail.IsBodyHtml = true;
        mail.DeliveryNotificationOptions = DeliveryNotificationOptions.OnFailure;
 
        return mail;
    }