Monday, December 22, 2008

ASP.NET Regular Expression For Replacing Invalid Characters

ASP.NET Regular Expression For Replacing Invalid Characters

Method 1
Names = Regex.Replace(txtName.Text, "[^A-Za-z0-9]+", "");

Method 2
Names = Regex.Replace(txtName.Text, "[\w", "");


These Regular Expressions can be used for Replacing Invalid Characters in a string.

SQL Querys examples Date-Time Difference

SQL Query examples Date-Time Difference

SQL example 1:
select checkindate, isnull(sum(lessthan2), 0) as lessthan2, isnull(sum(Gt2Lt5), 0) as Gt2Lt5, isnull(sum(Gt5Lt10), 0) as Gt5Lt10, isnull(sum(Gt10Lt15), 0) as Gt10Lt15, isnull(sum(Gt15), 0) as Gt15, sum(mins),sum(mins)/(isnull(sum(lessthan2), 0)+isnull(sum(Gt2Lt5), 0)+isnull(sum(Gt5Lt10), 0)+isnull(sum(Gt10Lt15), 0)+isnull(sum(Gt15), 0)) as Mins
from
(
select checkindate, mins,
'lessthan2'=
CASE
WHEN mins >= 0 and mins <>= 2 and mins <>= 5 and mins <>= 10 and mins <>= 15 THEN gt15+1
END

from
(
select lt2=0,lt5=0,lt10=0,lt15=0,gt15=0,checkindate,mins = cast(replace(datediff(mi,logintime,checkintime)%60,'-','') as Int) from tblactivity where (logintime<>'' and checkintime<>'' and checkindate between cast('01/01/2006' as datetime) and cast('07/01/2006' as datetime))
)a

)b group by checkindate




SQL example 2: Time difference calculation

select cast(datediff(mi,'11:00 AM','7:10 PM')/60 as varchar(10))+':'+cast(datediff(mi,'11:00 AM','7:10 PM')%60 as varchar(10))+':00'




SQL example 3: Time difference calculation
select CT,ST,
Mins =cast(replace(datediff(mi,CT,ST)%60,'-','') as varchar(10)),'Hours'=

CASE
WHEN cast(replace(datediff(mi,CT,ST)/60,'-','')as int) < st="substring(flags,charindex('calledforservicetime_flag'," ct="checkintime">''

More SQL Server Examples @: http://silvernight.wordpress.com/

Wednesday, November 05, 2008

Calling Javascript from C#, Calling Javascript from Codebehind ASP.NET

Calling Javascript from C#, Calling Javascript from Codebehind

We can use the following two methods to access Java Script from C#
Page.ClientScript.RegisterStartupScript() Method
Page.ClientScript.RegisterClientScriptBlock() Method

Eg:

string script = "< LANGUAGE='JavaScript'> ";
script += "ApptConfirm()";
script += "</SCRIPT>";

// We use RegisterStartupScript, so that this script is executed after all form elements are rendered.
Page.RegisterStartupScript("ClientScript", script);

Monday, November 03, 2008

loading csv file to SQL Server

loading csv file to SQL Server

CREATE TABLE CSVTest
(FirstName VARCHAR(40),
No1 INT,No2 INT,No3 INT,No4 INT)
GO

select * from CSVTest


BULK
INSERT CSVTest
FROM 'd:\Tesing.csv'
WITH
(
FIELDTERMINATOR = ',',
ROWTERMINATOR = '\n'
)
GO


select * from CSVTest

If there is a error in a particular row that row will not be added.
rest of the rows will be loaded into sql server.

.csv file
vijay,20,19999,90000,8
Jagadeesh,9,111,60000,9

Tuesday, October 21, 2008

Using JavaScript to Display messages in ASP.NET pages

<script language="javascript" src="script/ReasonForVisit.js">

or in aspx page

function setmessage()
{
if(language=='english'){
document.getElementById('header1').innerHTML="No Records found.";
document.getElementById('span1').innerHTML="We are unable to find
your records.";

}
else{
document.getElementById('header1').innerHTML="No Records found.";
document.getElementById('span1').innerHTML="We are unable to find
your records.";
}

}

.aspx pages

<table style="width: 100%;" border="0" cellpadding="0" cellspacing="0" id="Table1">
<tr align="center">
<td id="header1">

</td>
</tr>
<tr align="center">
<td id="span1">

</td>
</tr>
</table>

Using Session Variables in JavaScript - ASP.NET, C#

Using Session Variables in JavaScript - ASP.NET, C#

var apptMultiple ='<%= Session["multipleAppointments"]%>';

function SetRelationOnForm(){
var relation = '<%=Session["consentrelationshipToPatient"] %>';
var isPat = '<%=Session["consentSelIsPatient"] %>';
var isPatRep = '<%=Session["consentIsPatientRepresentative"] %>';
}

Friday, July 11, 2008

Getting Client Host name using Java Script/C#

Getting Client Host name using Java Script

function GetComputerName()
{
try
{
var WshNetwork = new ActiveXObject("WScript.Network");
var hostname = WshNetwork.ComputerName.toLowerCase(); document.getElementById('HdnMachineId').value = hostname;
}
catch(err)
{ }
}

Getting Client Host name using C#

private string getClientHostName()
{
// Get HostName of client computer
string hostname = HttpContext.Current.Request.ServerVariables["REMOTE_HOST"].ToString().ToLower();
try
{
System.Net.IPHostEntry host = System.Net.Dns.GetHostByAddress(hostname);
hostname = host.HostName;
}
catch(Exception exp)
{

}
return hostname;
}

Thursday, June 26, 2008

Previewing image while opening ASP.NET

Previewing image while opening

We can use the following code to preview an image while opening it using ASP.NET, C#, Java script.

<SCRIPT>
var lastfieldname = ''
function preview(i)
{
var file = i.value
if (file.length<=0) return;
var ipreview = document.all('ipreview')
ipreview.src ='file://' + file
}
img id="ipreview" border="1" height="120" src="images/spacer.gif" /><br />
adjust image:
<input id="fotofp" runat="server" name="file1" onchange="preview(this)" onfocus="preview(this)" size="25" type="file" />

Tuesday, June 17, 2008

Firefox 3.0 Sets Guinness World Record for Most Software Downloaded in 24 Hours

Firefox 3.0 Sets Guinness World Record for Most Software Downloaded in 24 Hours

Today 17 June, 2008 the most popular web browser Firefox Version 3 is released.

At present Firefox share in web browsing is 15% of Internet users. The release of Firefox 3.0 would further boost its market share.

New features in Firefox Version 3 include automatic warnings when users stray onto webpages booby-trapped with malicious code.

Also in Firefox 3.0 will be "Smart Location Bar" that lets people return to places they have visited even if they have not bookmarked them or cannot remember the full web address.

Firefox 3.0 will work with Windows 2000, XP and Vista and some non-Windows operating systems including Linux.


Download Firefox 3.0 Now http://www.mozilla.com/en-US/firefox/
or here
http://www.spreadfirefox.com/en-US/worldrecord



The count down started ;)

AccessDataSource UpdateCommand Gridview Asp.Net AccessDatabase

Updating Access Database using Asp.Net Gridview - AccessDataSource, UpdateCommand

We can use the following code to update Access Database using Asp.Net Gridview...

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" CellPadding="4"
DataKeyNames="ID" DataSourceID="AccessDataSource1" AutoGenerateDeleteButton="true" AutoGenerateEditButton="true" ForeColor="#333333" GridLines="None">
<FooterStyle BackColor="#990000" Font-Bold="True" ForeColor="White" />
<Columns>
<asp:BoundField DataField="ID" HeaderText="ID" InsertVisible="False" ReadOnly="True"
SortExpression="ID" />
<asp:BoundField DataField="Country" HeaderText="Country" SortExpression="Country" />
</Columns>
<RowStyle BackColor="#FFFBD6" ForeColor="#333333" />
<SelectedRowStyle BackColor="#FFCC66" Font-Bold="True" ForeColor="Navy" />
<PagerStyle BackColor="#FFCC66" ForeColor="#333333" HorizontalAlign="Center" />
<HeaderStyle BackColor="#990000" Font-Bold="True" ForeColor="White" />
<AlternatingRowStyle BackColor="White" />
</asp:GridView>
<asp:AccessDataSource ID="AccessDataSource1" runat="server" DataFile="~/App_Data/mReachTV_DB.mdb"
SelectCommand="SELECT [ID], [Country] FROM [TV_Streams]"
UpdateCommand="UPDATE [TV_Streams] SET [Country] = @Country WHERE [ID] = @ID">
</asp:AccessDataSource>

Is it Looking similar to the code you had written??

Thats where the trick is... The number of parameters in Select and Update command should be equal.

Monday, June 09, 2008

Message Boxes, Popup in ASP.NET

Displaying Message Boxes, Popup in ASP.NET using Java Script

The following code samples can be used to display message boxes in ASP.NET webpages.

mes = chpwd.updat(txtrpwd.Text, txtuname.Text);
if (mes)
{

string script = "alert('New Password is Created');\n";
script += "var f='" + Session["flag"].ToString() + "';\n";
script += "if (f == 'L')\n";
script += "location.href='loginpage.aspx';\n";

Page.ClientScript.RegisterStartupScript(GetType(), "msgbox", script, true);
}

----------------------------------------------------------------------------------------
Response.Write("<script>alert('New Password is created')</script>");
----------------------------------------------------------------------------------------
if (mes)
{
StringBuilder sb = new StringBuilder();
sb.Append("<script type='text/javascript'>");
sb.Append("alert('New Password is Create');");

if (Session["flag"].ToString() == "L")
{
sb.Append("window.location = 'loginpage.aspx';");
}

sb.Append("");

Page.RegisterClientScriptBlock("mes", sb.ToString());
}
----------------------------------------------------------------------------------------

Page.ClientScript.RegisterStartupScript(this.GetType(), "myAlertBox", "alert('New Password is Created'); window.location = 'loginpage.aspx';", true);

or

ClientScript.RegisterClientScriptBlock(this.GetType(), "myAlertBox", "alert('New Password is Created'); window.location = 'loginpage.aspx';", true);

----------------------------------------------------------------------------------------

For POP Ups:

We can use Javascript function window.Open or target="_blank" for popups.

If we want to open a popup in form another popup window? we can use Java script function window.location.

------------------------------------------------------------------------

Another Method to Display Message boxes in ASP.NET

protected void btnSubmit_Click(object sender, EventArgs e)

{

string script = "alert('Are U sure? ');";

System.Web.UI.ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "Test", script, true);

}

------------------------------------------------------------------------

Another Method to Display Message boxes in ASP.NET

<asp:Button ID="button1" OnClientClick="return confirm('Are you sure?');" runat="server" />

or

<asp:LinkButton
ID="ibtnDelete"
runat="server"
Text="Delete"
CommandName="Delete"
OnClientClick="javascript:return confirm('Are you sure you want to delete this class?');">
</asp:LinkButton>

Restricting File Upload size using ASP.NET C#

We can use the following code to restrict the File upload size using Asp.Net, C#.


We can set the maximum upload limit for the file, using maxRequestLength in web.config of your ASP.NET web application.

Here is the sample code for this...


protected void btnUpload_Click(object sender, System.EventArgs e)
{
string fileName = FileSelector.PostedFile.FileName;
int fN = fileName.LastIndexOf("\\");
string newFileName = fileName.Substring(fN).ToLower();

if (newFileName.EndsWith(".m4v") || newFileName.EndsWith(".mp3") || newFileName.EndsWith(".mp4") || newFileName.EndsWith(".mov"))
{
if (this.FileSelector.PostedFile.ContentLength < 210000)
{
FileSelector.PostedFile.SaveAs(
Server.MapPath("../audioFiles/") + newFileName);

lblWarn.Text = "File uploaded";
lblWarn.ForeColor = System.Drawing.Color.Green;
lblWarn.Visible = true;
}
else
{
lblWarn.Text = "File cannot exceed 350MB";
lblWarn.Visible = true;
lblWarn.ForeColor = System.Drawing.Color.Red;
}
}
else
{
lblWarn.Text = "Only extensions .m4v, .mp4, mp3, or .mov";
lblWarn.Visible = true;
lblWarn.ForeColor = System.Drawing.Color.Red;
}
}

Also default upload limit is 4MB in asp.net. You can change this value in ur web.config file.

<httpRuntime maxRequestLength="210000"/>

Include this in your webconfig file in the system.web section

You can also use FileUpload1.PostedFile.ContentLength to calculate the length of the file after it is uploaded to server.

Image size, type Upload Validation

protected void Button1_Click(object sender, EventArgs e)
{
string fileFullname = this.File1.PostedFile.FileName;


if (File1.PostedFile.ContentType.ToUpper().IndexOf("IMAGE") > -1)
{
System.Drawing.Image img = System.Drawing.Image.FromStream(File1.PostedFile.InputStream);
int Width = img.Width;
int Height = img.Height;

if (Width > 200 || Height > 200 || File1.PostedFile.ContentLength > 1024 * 1024 * 200)
{
Response.Write("<script language='javascript'>alert('your image don not confirm the with and height.!');</script>");
}
else
{
if (type == "jpg" || type == "gif" || type == "bmp" || type == "JPG" || type == "GIF")
{

string sPath = Server.MapPath("images/") + dataName + fileName;

string imgPath = "pic/" + dataName + fileName;

this.File1.PostedFile.SaveAs(sPath);

Response.Write("<script language='javascript'>alert('suceed!!!');</script>");


this.Image1.ImageUrl = imgPath;


this.Button1.Enabled = false;
this.Button1.Text = "suceed!";
this.Button1.Enabled = true;

}
else
{
Response.Write("<script language='javascript'>alert('your file type wrong!');</script>");
}
}
}
else
{

Response.Write("<script language='javascript'>alert('please choice the image to upload!');</script>");
}
}

Validations::
We can also use RegularExpressionValidator to validate the file (extensions) which you are uploading. The RE will look like this ^(([a-zA-Z]:)|(\\{2}\w+)\$?)(\\(\w[\w].*))(.jpg|.JPG)$

and now you have to set RequiredFieldValidator for fileUpload. It stops you from proceeding further if you do not upload a file.

Getting Geographic Location(country) of internet user ASP.NET C#

Here is a FREE web service that will give you Country information from IP address.
http://www.webservicex.net/WS/WSDetails.aspx?WSID=64&CATID=12

But if you want to pay and get more featured service, then you may check here
http://www.ip2country.net/ip2country/lookup.html
This website does not sell Web Service, rather they sell lookup DataBase. You will need to purchase a database from them and then use your ASP.NET look up query to get county information.

Getting Client IP address using ASP.NET C#

You can use the following three ways to get the client IP address using C#

string test = Request.UserHostAddress.ToString();
string test2 = Request.ServerVariables["REMOTE_ADDR"].ToString();
string test3 = Context.Request.UserHostAddress.ToString();

All are returning the same values...

Some times client can mask their IP behind a router/nat and it's spoofable.


Friday, June 06, 2008

Menu Control (Tab View) Placing TabContainer inside another TabContainer

   <form id="form1" runat="server">
    
    <asp:Menu
        ID="Menu1"
        Width="168px"
        runat="server"
        Orientation="Horizontal"
        StaticEnableDefaultPopOutImage="False"
        OnMenuItemClick="Menu1_MenuItemClick">
    <Items>
        <asp:MenuItem ImageUrl="~/selectedtab.gif" 
                      Text=" " Value="0"></asp:MenuItem>
        <asp:MenuItem ImageUrl="~/unselectedtab.gif" 
                      Text=" " Value="1"></asp:MenuItem>
        <asp:MenuItem ImageUrl="~/unselectedtab.gif" 
                      Text=" " Value="2"></asp:MenuItem>
    </Items>
</asp:Menu>
    <div><PRE lang=html id=pre1 style="MARGIN-TOP: 0px" nd="35">
<asp:MultiView 
    ID="MultiView1"
    runat="server"
    ActiveViewIndex="0"  ><asp:View ID="Tab1" runat="server"  ><table width="600" height="400" cellpadding=0 cellspacing=0><tr valign="top"><td class="TabArea" style="width: 600px"><br /><br />TAB VIEW 1 INSERT YOUR CONENT IN HERE CHANGE SELECTED IMAGE URL AS NECESSARY </td></tr></table></asp:View> <asp:View ID="Tab2" runat="server">
        <table width="600px" height="400px" cellpadding=0 cellspacing=0>
            <tr valign="top">
                <td class="TabArea" style="width: 600px">
                <br />
                <br />
                    TAB VIEW 2
                    INSERT YOUR CONENT IN HERE
                    CHANGE SELECTED IMAGE URL AS NECESSARY
                </td>
            </tr>
        </table>
    </asp:View> <asp:View ID="Tab3" runat="server">
        <table width="600px" height="400px" cellpadding=0 cellspacing=0>
            <tr valign="top">
                <td class="TabArea" style="width: 600px">
                <br />
                <br />
                 
        <asp:Menu
        ID="Menu2"
        Width="168px"
        runat="server"
        Orientation="Horizontal"
        StaticEnableDefaultPopOutImage="False"
        OnMenuItemClick="Menu2_MenuItemClick">
    <Items>
        <asp:MenuItem ImageUrl="~/selectedtab.gif" 
                      Text=" " Value="0"></asp:MenuItem>
        <asp:MenuItem ImageUrl="~/unselectedtab.gif" 
                      Text=" " Value="1"></asp:MenuItem>
        <asp:MenuItem ImageUrl="~/unselectedtab.gif" 
                      Text=" " Value="2"></asp:MenuItem>
    </Items>
</asp:Menu>
    <div><PRE lang=html id=pre2 style="MARGIN-TOP: 0px" nd="35"><asp:MultiView 
    ID="MultiView2"
    runat="server"
    ActiveViewIndex="0"  >
   <asp:View ID="View1" runat="server"  >
        <table width="600" height="400" cellpadding=0 cellspacing=0>
            <tr valign="top">
                <td class="TabArea" style="width: 600px">
                    <br />
                    <br />
                    TAB VIEW 1
                    INSERT YOUR CONENT IN HERE
                    CHANGE SELECTED IMAGE URL AS NECESSARY
                </td>
            </tr>
        </table>
     </asp:View>
    <asp:View ID="View2" runat="server">
        <table width="600px" height="400px" cellpadding=0 cellspacing=0>
            <tr valign="top">
                <td class="TabArea" style="width: 600px">
                <br />
                <br />
                    TAB VIEW 2
                    INSERT YOUR CONENT IN HERE
                    CHANGE SELECTED IMAGE URL AS NECESSARY
                </td>
            </tr>
        </table>
    </asp:View>
    <asp:View ID="View3" runat="server">
        <table width="600px" height="400px" cellpadding=0 cellspacing=0>
            <tr valign="top">
                <td class="TabArea" style="width: 600px">
                <br />
                <br />
                  TAB VIEW 3
                  INSERT YOUR CONENT IN HERE
                  CHANGE SELECTED IMAGE URL AS NECESSARY
                </td>
            </tr>
        </table>
    </asp:View>
</asp:MultiView>
 </td>
            </tr>
        </table>
    </asp:View></asp:MultiView></PRE></div>
    </form>

In C#

    protected void Menu1_MenuItemClick(object sender, MenuEventArgs e)
    {
        MultiView1.ActiveViewIndex = Int32.Parse(e.Item.Value);
        int i;
        // Make the selected menu item reflect the correct imageurl
        for (i = 0; (i <= (Menu1.Items.Count - 1)); i++)
        {
            if (e.Item.Value.Equals(i+""))
            {
                Menu1.Items[i].ImageUrl = "selectedtab.gif";
            }
            else
            {
                Menu1.Items[i].ImageUrl = "unselectedtab.gif";
            }
        }
    }
    protected void Menu2_MenuItemClick(object sender, MenuEventArgs e)
    {
        MultiView2.ActiveViewIndex = Int32.Parse(e.Item.Value);
        int i;
        // Make the selected menu item reflect the correct imageurl
        for (i = 0; (i <= (Menu1.Items.Count - 1)); i++)
        {
            if (e.Item.Value.Equals(i + ""))
            {
                Menu2.Items[i].ImageUrl = "selectedtab.gif";
            }
            else
            {
                Menu2.Items[i].ImageUrl = "unselectedtab.gif";
            }
        }

Crystal Reports asks for Username and Password while loading - ASP.NET 2.0

Here is the code for that in VB.NET:

On the page load or button click or whatever you want to run the report on you need to add the following: configureCRYSTALREPORT()

Private Sub configureCRYSTALREPORT()
Dim myConnectionInfo As New ConnectionInfo()
myConnectionInfo.DatabaseName = "DatabserName"
myConnectionInfo.UserID = "UID"
myConnectionInfo.Password = "PWD"
setDBLOGONforREPORT(myConnectionInfo)
End Sub

Private Sub
setDBLOGONforREPORT(ByVal myconnectioninfo As ConnectionInfo)
Dim mytableloginfos As New TableLogOnInfos()
mytableloginfos = CrystalReportViewer1.LogOnInfo
For Each myTableLogOnInfo As TableLogOnInfo In mytableloginfos
myTableLogOnInfo.ConnectionInfo = myconnectioninfo
Next

End Sub

-------------------------------------------------------------------------------------------------------------------------------------------------

Here is the code for that in C#:

private void setDBLOGONforREPORT(ConnectionInfo myconnectioninfo)
{
TableLogOnInfos mytableloginfos = new TableLogOnInfos();
mytableloginfos = CrystalReportViewer1.LogOnInfo;
foreach (TableLogOnInfo myTableLogOnInfo in mytableloginfos)
{
myTableLogOnInfo.ConnectionInfo = myconnectioninfo;
}

}

In Page Load....
ConnectionInfo myConnectionInfo = new ConnectionInfo();
myConnectionInfo.ServerName = "serverName";
myConnectionInfo.DatabaseName = "DatabaseName";
myConnectionInfo.UserID = "sa";
myConnectionInfo.Password = "pwd";
setDBLOGONforREPORT(myConnectionInfo);

Go back to previous page without Loosing Data ASP.NET

We can use client-side script (JS) for this purpose...

<input type="button" value="Click here to go back" onclick="javascript: return history.back();" /> 
or

<input type="button" value="Click here to go back" onclick="javascript: return history.go(-1);" />

or

javascript: return history.go(-1);

or

http://www.aspdotnetfaq.com/Faq/How-to-make-Cross-Page-Postback-in-ASP-Net.aspx

Useing HTML tags in C# or VB.Net codebehind

Its simple to use HTML tags in Code behind and display in ASP.NET web pages....

Method 1:

in .cs page

string t = txtBody.Text;
MyEmailBody.InnerHtml = Server.HtmlDecode(t);

in .aspx page

<div id="MyEmailBody" runat="server"></div>

It may some times require to change the ValidateRequest="false".

Method 2:

we can use Literal controls, to view HTML tags in .aspx pages from code behind.

in . aspx page

<asp:Literal runat="server"></asp:Literal>

in .cs page

this.Controls.Add(new LiteralControl("<b>This is Bold</b>"));

Hope this helps you in using HTML tags in codebehind.

Sending HTML Emails using ASP.NET, C# with embedded images

Today I found these useful links that helps us to embed the images in the HTML emails we are sending using ASP.NET & C#.

Simple HTML Format emails::

private void SendClick() {
MailMessage mailMsg = new MailMessage();
try {
mailMsg.To = "";
mailMsg.From = "";
mailMsg.BodyFormat = MailFormat.Html;
mailMsg.Subject = "Statistics Report";
mailMsg.Body ="content";
SmtpMail.SmtpServer ="serverHost";
SmtpMail.Send(mailMsg);
}
catch (Exception ex) {
Response.Write(ex.Message);
}
}

You can download the example code of sending HTML emails using ASP.NET here...

http://www.asp101.com/Samples/email_html_aspx.asp

http://download.microsoft.com/download/d/f/c/dfc7a022-3426-4868-b23c-3818a6e54305/HtmlEmail.zip

Links to Embed Images in HTML Emails Using ASP.NET & C#

To have a basic idea of mailing with an embedded image or object from ASP.NET 2.0 using SMTP Client. You can visit the following links...

http://aspalliance.com/1354_Sending_HTML_Mail_with_Embedded_Image_in_NET.8

http://www.codeproject.com/kb/IP/EmailByjebarson.aspx

http://www.codeproject.com/KB/aspnet/inkrajesh.aspx

Sending emails using ASP.NET, C# or VB.NET

For sending mails from asp.net, C# Using System.Web.Mail name space.

using System.Web.Mail;

public static string SendMail(int pintUserID, string pstrMailTo, string pstrMailBcc,string pstrMailCc,string pstrMailSubject,string pstrMailBody,string pstrAttachFilePath)

{

try

{

MailMessage objMail = new MailMessage();

objMail.From = System.Configuration.ConfigurationSettings.AppSettings["FromEmailID"];

//objMail.From =System.Web.HttpContext.Current.Session["OfficeEmailID"].ToString() ;

objMail.To = pstrMailTo;

objMail.Bcc = pstrMailBcc;

objMail.Cc = pstrMailCc;

objMail.Subject = pstrMailSubject;

MailAttachment Attachment = null;if (File.Exists(pstrAttachFilePath))

{

Attachment =
new MailAttachment(pstrAttachFilePath);

}

objMail.Attachments.Add(Attachment);

SmtpMail.SmtpServer = "localhost";//System.Configuration.ConfigurationSettings.AppSettings["SMTPServerIP"];

SmtpMail.Send(objMail);return "TRUE";

}

catch(Exception Ex)

{

return Ex.Message;

}

}

In Config file

<add key="SMTPServerIP" value="192.168.1.11"> </add>

Call this function SendMail & enable your system SMTP server.

Useful links for sending email

http://www.asp101.com/Samples/email_html_aspx.asp

http://download.microsoft.com/download/d/f/c/dfc7a022-3426-4868-b23c-3818a6e54305/HtmlEmail.zip

http://www.codeproject.com/KB/aspnet/Email_Sending_Programme.aspx

http://www.codersource.net/csharp_sending_emails.aspx

How to Embed Flash, Videos in ASP.Net web pages

To embed flash and videos we can use simple HTML embed tag for this purpose.

For example.

<embed src="images/flash02.swf" quality="high" bgcolor="#ffffff" width="775" height="24" name="flash" align="middle" allowScriptAccess="sameDomain" allowFullScreen="false" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer" />

enables us to display flash files in Asp.net web pages.

Using JavaScript to display flash in Webpages.


1. <script type="text/javascript" src="FlashSwfObject.js"></script>

Use div tag where you want to display the SWF, use a unique id:


<div id="flashbanner">Your SWF will display here!!.</div>
We can instantiate the FlashSwfObject using below code.

<script type="text/javascript">
var so = new SWFObject('MyMedia.swf','mpl','300','250','7');
so.addParam('allowfullscreen','true');
so.addVariable('file','playlist.xml');
so.addVariable('backcolor','0x000000');
so.addVariable('autostart','true');
so.write('flashbanner');
</script>

Image Resize using ASP.NET C# and displaying as Thumbnails dynamically

The following code helps us to Resize images and display them as thumbnails dynamically using ASP.NET C#.

protected void Page_Load(object sender, EventArgs e)
{
string BasePath = Server.MapPath(".");
Bitmap Img, ImgTemp;

ImgTemp = new Bitmap(BasePath + "\\images\\Balaji.jpg");
Img = new Bitmap(ImgTemp, 200, 300);

Graphics Graph;
Graph = Graphics.FromImage(Img);

Img.Save(Response.OutputStream, ImageFormat.Jpeg);
Graph.DrawImage(Img, 0, 0);

ImgTemp.Dispose();

Img.Dispose();
}

This function helps us to set the height and width of the new image Bitmap(ImgTemp, 200, 300);

Tuesday, April 01, 2008

.NET Interview questions and Answers: 14

Localization/Globalization

  1. What is Unicode and why was it introduced?
  2. Does .NET support UNICODE and how do you know it supports?
  3. What’s the difference between localization and globalization?
  4. What architecture decisions you should consider while planning for international software’s?
  5. How do we get the current culture of the environment in windows and ASP.NET?
  6. Which are the important namespaces during localization and globalization?
  7. What are resource files and how do we generate resource files?
  8. Can resource file be in any other format other than resx extensions?
  9. How is resource files actually used in project?
  10. How can we use Culture Auto in project?
  11. What are satellite assemblies?
  12. How do we generate Satellite assemblies?
  13. What is AL.EXE and RESGEN.EXE?
  14. What’s the use of resource manager class?
  15. What precautions do we need to take while deploying satellite assemblies?
  16. Can we get a strongly typed resource class rather than using resource manager?
  17. Explain fundamentals of “GetGlobalResourceObject” and “GetLocalResourceObject” functions?
  18. Can we sign a satellite assembly?
  19. Can you explain collation sequence in sql server?
  20. How do we define collation sequence for database and tables?
  21. Can we change the order in a select query with a specified collation sequence?
  22. What are the best practices to be followed while implementing globalization and localization?
  23. Why is the culture set to the current thread?

.NET Interview questions and Answers: 13

XML

  1. What is XML?
  2. What is the version information in XML?
  3. What is ROOT element in XML?
  4. If XML does not have closing tag will it work?
  5. Is XML case sensitive?
  6. What’s the difference between XML and HTML?
  7. Is XML meant to replace HTML?
  8. Can you explain why your project needed XML?
  9. What is DTD (Document Type definition)?
  10. What is well formed XML?
  11. What is a valid XML?
  12. What is CDATA section in XML?
  13. What is CSS?
  14. What is XSL?
  15. What is Element and attributes in XML?
  16. Which are the namespaces in .NET used for XML?
  17. What are the standard ways of parsing XML document?
  18. In What scenarios will you use a DOM parser and SAX parser?
  19. How was XML handled during COM times?
  20. What’s the main difference between MSML and .NET Framework XML classes?
  21. What are the core functionalities in XML .NET framework? Can you explain in detail
  22. those functionalities?
  23. What is XSLT?
  24. Define XPATH?
  25. What’s the concept of XPOINTER?
  26. What is an XMLReader Class?
  27. What is XMLTextReader?
  28. How do we access attributes using “XmlReader”?
  29. Explain simple Walk through of XmlReader ?
  30. What does XmlValidatingReader class do?

.NET Interview questions and Answers: 12

Project Management

  1. What is project management?
  2. Is spending in IT project’s constant through out the project?
  3. Who is a stakeholder ?
  4. Can you explain project life cycle ?
  5. Twist :- How many phases are there in software project ?
  6. Are risk constant through out the project ?
  7. Can you explain different software development life cycles ?
  8. What is triple constraint triangle in project management ?
  9. What is a project baselines ?
  10. What is effort variance?
  11. How is normally a project management plan document organized ?
  12. How do you estimate a project?
  13. What is CAR (Causal Analysis and Resolution)?
  14. What is DAR (Decision Analysis and Resolution)?
  15. What is a fish bone diagram ?
  16. Twist:- What is Ishikawa diagram ?
  17. What is pareto principle ?
  18. Twist :- What is 80/20 principle ?
  19. How do you handle change request?
  20. What is internal change request?
  21. What is difference between SITP and UTP in testing ?
  22. What are the software you have used for project management?
  23. What are the metrics followed in project management?
  24. Twist: - What metrics will you look at in order to see the project is moving successfully?
  25. You have people in your team who do not meet there deadlines or do not perform what are the actions you will take ?
  26. Twist :- Two of your resources have conflict’s between them how would you sort it out ?
  27. What is black box testing and White box testing?
  28. What’s the difference between Unit Testing, Assembly Testing and Regression testing?
  29. What is V model in testing?
  30. How do you start a project?
  31. How did you do resource allocations?
  32. How do you do code reviews ?
  33. What is CMMI?
  34. What are the five levels in CMMI?
  35. What is continuous and staged representation?
  36. Can you explain the process areas?
  37. What is SIX sigma?
  38. What is DMAIC and DMADV ?
  39. What are the various roles in Six Sigma implementation?
  40. What are function points?
  41. Twist: - Define Elementary process in FPA?
  42. What are different types of elementary process in FPA?
  43. What are the different elements in Functions points?
  44. Can you explain in GSC and VAF in function points?
  45. What are unadjusted function points and how is it calculated?
  46. Can you explain steps in function points?
  47. What is the FP per day in your current company?
  48. Twist :- What is your company’s productivity factor ?
  49. Do you know Use Case points?
  50. What is COCOMO I, COCOMOII and COCOMOIII?
  51. What is SMC approach of estimation?
  52. How do you estimate maintenance project and change requests?

.NET Interview questions and Answers: 11

UML

  1. What is UML?
  2. How many types of diagrams are there in UML ?
  3. Twist :- Explain in short all types of diagrams in UML ?
  4. What are advantages of using UML?
  5. Twist: - What is Modeling and why UML ?
  6. What’s the sequence of UML diagrams in project?
  7. Twist: - How did you implement UML in your project?
  8. Just a small Twist: - Do I need all UML diagrams in a project?
  9. Give a small brief explanation of all Elements in activity diagrams?
  10. Explain Different elements of a collaboration diagram ?
  11. Explain Component diagrams ?
  12. Explain all parts of a deployment diagram?
  13. Describe various components in sequence diagrams?
  14. What are the element in State Chart diagrams ?
  15. Describe different elements in Static Chart diagrams ?
  16. Explain different elements of a Use Case ?
  17. Twist: - What’s difference between Activity and sequence diagrams?(I leave this to the readers)

.NET Interview questions and Answers: 10

SQL SERVER

  1. What is normalization? What are different type of normalization?
  2. What is denormalization ?
  3. What is a candidate key ?
  4. What are different types of joins and whats the difference between them ?
  5. What are indexes and What is the difference between clustered and nonclustered indexes?
  6. How can you increase SQL performance ?
  7. What is the use of OLAP ?
  8. What's a measure in OLAP ?
  9. What are dimensions in OLAP ?
  10. What are levels in dimensions ?
  11. What are fact tables and dimension tables in OLAP ?
  12. Twist :- can you explain the star schema for OLAP ?
  13. What is DTS?
  14. What is fillfactor ?
  15. Twist :- When does plage split occurs ?
  16. What is RAID and how does it work ?
  17. What's the difference between DELETE TABLE and TRUNCATE TABLE commands?
  18. What are the problems that can occur if you do not implement locking properly in SQL SERVER ?
  19. What are different transaction levels in SQL SERVER ?
  20. Twist :- what are different types of locks in SQL SERVER ?
  21. What are different locks in SQL SERVER ?
  22. Can we suggest locking hints to SQL SERVER ?
  23. What is LOCK escalation?
  24. What are the different ways of moving data/databases between servers and databases in SQL Server?
  25. What are advantages of SQL 2000 over SQl 7.0 ?
  26. What is the difference between a HAVING CLAUSE and a WHERE CLAUSE?
  27. What is difference between UNION and UNION ALL SQL syntax ?
  28. How can you raise custom errors from stored procedure ?
  29. What is ACID fundamental and what are transactions in SQL SERVER ?
  30. What is DBCC?
  31. What is purpose of Replication ?
  32. What are different type of replication supported by SQL SERVER ?
  33. What is BCP utility in SQL SERVER ?
  34. What are different types of triggers in SQl SERVER 2000 ?
  35. If we have multiple AFTER Triggers on table how can we define the sequence of the triggers ?
  36. What is SQl injection ?
  37. What’s the difference between Stored Procedure (SP) and User Defined Function (UDF)?

.NET Interview questions and Answers: 9

ADO.NET

  1. What is the namespace in which .NET has the data functionality classes ?
  2. Can you give a overview of ADO.NET architecture ?
  3. What are the two fundamental objects in ADO.NET ?
  4. What is difference between dataset and datareader ?
  5. What are major difference between classic ADO and ADO.NET ?
  6. What is the use of connection object ?
  7. What is the use of command objects and what are the methods provided by the command object ?
  8. What is the use of dataadapter ?
  9. What are basic methods of Dataadapter ?
  10. What is Dataset object?
  11. What are the various objects in Dataset ?
  12. How can we connect to Microsoft Access , Foxpro , Oracle etc ?
  13. How do we connect to SQL SERVER , which namespace do we use ?
  14. How do we use stored procedure in ADO.NET and how do we provide parameters to the stored procedures?
  15. How can we force the connection object to close after my datareader is closed ?
  16. I want to force the datareader to return only schema of the datastore rather than data ?
  17. How can we fine tune the command object when we are expecting a single row or a single value ?
  18. Which is the best place to store connectionstring in .NET projects ?
  19. What are steps involved to fill a dataset ?
  20. Twist :- How can we use dataadapter to fill a dataset ?
  21. What are the various methods provided by the dataset object to generate XML?
  22. How can we save all data from dataset ?
  23. How can we check that some changes have been made to dataset since it was loaded ?
  24. Twist :- How can we cancel all changes done in dataset ? , How do we get values which are changed in a dataset ?
  25. How can we add/remove row’s in “DataTable” object of “DataSet” ?
  26. What’s basic use of “DataView” ?
  27. What’s difference between “DataSet” and “DataReader” ?
  28. Twist :- Why is DataSet slower than DataReader ?
  29. How can we load multiple tables in a DataSet ?
  30. How can we add relation’s between table in a DataSet ?
  31. What’s the use of CommandBuilder ?
  32. What’s difference between “Optimistic” and “Pessimistic” locking ?
  33. How many way’s are there to implement locking in ADO.NET ?
  34. How can we perform transactions in .NET?
  35. What’s difference between Dataset. clone and Dataset. copy ?
  36. Can you explain the difference between an ADO.NET Dataset and an ADO Recordset?
  37. Explain in detail the fundamental of connection pooling?
  38. What is Maximum Pool Size in ADO.NET Connection String?
  39. How to enable and disable connection pooling?

.NET Interview questions and Answers: 8

.NET Architecture

  1. What are design patterns ?
  2. What’s difference between Factory and Abstract Factory Pattern’s?
  3. What’s MVC pattern?
  4. Twist: - How can you implement MVC pattern in ASP.NET?
  5. How can we implement singleton pattern in .NET?
  6. How do you implement prototype pattern in .NET?
  7. Twist: - How to implement cloning in .NET ? , What is shallow copy and deep copy ?
  8. What are the situations you will use a Web Service and Remoting in projects?
  9. Can you give a practical implementation of FAƇADE patterns?
  10. How can we implement observer pattern in .NET?
  11. What is three tier architecture?
  12. Have you ever worked with Microsoft Application Blocks, if yes then which?
  13. What is Service Oriented architecture?
  14. What are different ways you can pass data between tiers?
  15. What is Windows DNA architecture?
  16. What is aspect oriented programming?

.NET Interview questions and Answers: 7

ASP.NET Interview questions and Answers

  1. What’s the sequence in which ASP.NET events are processed ?
  2. In which event are the controls fully loaded ?
  3. How can we identify that the Page is PostBack ?
  4. How does ASP.NET maintain state in between subsequent request ?
  5. What is event bubbling ?
  6. How do we assign page specific attributes ?
  7. Administrator wants to make a security check that no one has tampered with ViewState , how can he ensure this ?
  8. What’s the use of @ Register directives ?
  9. What’s the use of SmartNavigation property ?
  10. What is AppSetting Section in “Web.Config” file ?
  11. Where is ViewState information stored ?
  12. What’s the use of @ OutputCache directive in ASP.NET?
  13. How can we create custom controls in ASP.NET ?
  14. How many types of validation controls are provided by ASP.NET ?
  15. Can you explain what is “AutoPostBack” feature in ASP.NET ?
  16. How can you enable automatic paging in DataGrid ?
  17. What’s the use of “GLOBAL.ASAX” file ?
  18. What’s the difference between “Web.config” and “Machine.Config” ?
  19. What’s a SESSION and APPLICATION object ?
  20. What’s difference between Server.Transfer and response.Redirect ?
  21. What’s difference between Authentication and authorization?
  22. What is impersonation in ASP.NET ?
  23. Can you explain in brief how the ASP.NET authentication process works?
  24. What are the various ways of authentication techniques in ASP.NET?
  25. How does authorization work in ASP.NET?
  26. What’s difference between Datagrid , Datalist and repeater ?
  27. From performance point of view how do they rate ?
  28. What’s the method to customize columns in DataGrid?
  29. How can we format data inside DataGrid?
  30. How will decide the design consideration to take a Datagrid , datalist or repeater ?
  31. Difference between ASP and ASP.NET?
  32. What are major events in GLOBAL.ASAX file ?
  33. What order they are triggered ?
  34. Do session use cookies ?
  35. How can we force all the validation control to run ?
  36. How can we check if all the validation control are valid and proper ?
  37. If you have client side validation is enabled in your Web page , Does that mean server side code is not run?
  38. Which JavaScript file is referenced for validating the validators at the client side ?
  39. How to disable client side script in validators?
  40. I want to show the entire validation error message in a message box on the client side?
  41. You find that one of your validation is very complicated and does not fit in any of the validators , so what will you do ?
  42. What is Tracing in ASP.NET ?
  43. How do we enable tracing ?
  44. What exactly happens when ASPX page is requested from Browser?
  45. How can we kill a user session ?
  46. How do you upload a file in ASP.NET ?
  47. How do I send email message from ASP.NET ?
  48. What are different IIS isolation levels?
  49. ASP used STA threading model , whats the threading model used for ASP.NET ?
  50. Whats the use of <%@ page aspcompat=true %> attribute ?
  51. Explain the differences between Server-side and Client-side code?
  52. Can you explain Forms authentication in detail ?
  53. How do I sign out in forms authentication ?
  54. If cookies are not enabled at browser end does form Authentication work?
  55. How to use a checkbox in a datagrid?
  56. What are the steps to create a windows service in VB.NET ?
  57. What’s the difference between “Web farms” and “Web garden”?
  58. How do we configure “WebGarden”?
  59. What is the main difference between Gridlayout and FlowLayout ?