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);