Yasserzaid’s Weblog

November 30, 2009

AJAX AsynFile Upload with File Extension Validation

Filed under: AJAX, ASP.Net — Tags: — yasserzaid @ 1:26 am

Hi

try this example to validate uploaded file extenstion using AJAX AsynFileUpload control

    <script type=”text/javascript”>       
        function uploadError(sender, args) {
            //Good practice to put try,catch block. it will avoid javascript error at window status.
            try
            {
                $get(“dvFileErrorInfo”).style.display=’block’;
                $get(“dvFileInfo”).style.display=’none’;
                $get(“<%=lblError.ClientID%>”).innerHTML = “File Not Uploaded” + args.get_errorMessage();
            }
            catch(e)
            {
                alert(e.message);
            }
        }
               
        function uploadComplete(sender, args) {
          try
          {
             var fileExtension=args.get_fileName();
             var gif =fileExtension.indexOf(‘.gif’);
             var png =fileExtension.indexOf(‘.png’);
             var jpg =fileExtension.indexOf(‘.jpg’);
             var jpeg =fileExtension.indexOf(‘.jpeg’);
            if( gif > 0 || png > 0 || jpg > 0 || jpeg > 0)
            {
                $get(“dvFileInfo”).style.display=’block’;
                $get(“dvFileErrorInfo”).style.display=’none’;
                $get(“<%=lblSuccess.ClientID%>”).innerHTML = “File Uploaded Successfully”;
            }
            else
            {
                $get(“dvFileErrorInfo”).style.display=’block’;
                $get(“<%=lblError.ClientID%>”).innerHTML = “Allowed File extension are {.gif,.png,.jpg,.jpeg} supported”;
                $get(“dvFileInfo”).style.display=’none’;
                return;
            }
          
          }
          catch(e)
          {
            alert(e.message);
          }     
        }
    </script>

    <div>
        <asp:ScriptManager runat=”Server” EnablePartialRendering=”true” ID=”ScriptManager1″ />
        <cc1:AsyncFileUpload ID=”afuUpload” OnClientUploadError=”uploadError” OnUploadedComplete=”afuUpload_UploadedComplete”
            OnUploadedFileError=”afuUpload_UploadedFileError” runat=”server” OnClientUploadComplete=”uploadComplete”
            Width=”400px” UploaderStyle=”Modern” UploadingBackColor=”#CCFFFF” ThrobberID=”myThrobber” />
        <asp:Label runat=”server” ID=”myThrobber” Style=”display: none;”>
                     <img align=”absmiddle” alt=”" src=”Images/uploading.gif” />
        </asp:Label>
        <div style=”border-style: solid; display: none; width: 350px” id=”dvFileInfo”>
            <asp:Label ID=”lblStatus” Font-Bold=”true” runat=”server” Text=”Status:-” /><asp:Label
                ID=”lblSuccess” ForeColor=”Green” runat=”server” /><br />
        </div>
        <div style=”border-style: solid; display: none; width: 350px” id=”dvFileErrorInfo”>
            <asp:Label ID=”lblErrorStatus” Font-Bold=”true” runat=”server” Text=”Status:-” /><asp:Label
                ID=”lblError” ForeColor=”Red” runat=”server” /><br />
        </div>
    </div>

and in code behind :-

    public void afuUpload_UploadedComplete(object sender, AsyncFileUploadEventArgs e)
    {
        try
        {
            string savePath = MapPath(“~/Images/” + Path.GetFileName(e.filename));
            /*Validation for file extension*/
            bool gif =Path.GetExtension(e.filename).Contains(“.gif”);
            bool png =Path.GetExtension(e.filename).Contains(“.png”);
            bool jpg =Path.GetExtension(e.filename).Contains(“.jpg”);
            bool jpeg =Path.GetExtension(e.filename).Contains(“.jpeg”);
            if (gif || png || jpg || jpeg)
            {
                afuUpload.SaveAs(savePath);
            }
            else
            {
                return;
            }
          
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }

    public void afuUpload_UploadedFileError(object sender, AsyncFileUploadEventArgs e)
    {
        //ScriptManager.RegisterClientScriptBlock(this, this.GetType(), “error”, “top.$get(\”" + lblErrorStatus.ClientID + “\”).innerHTML = ‘Error: ” + e.statusMessage + “‘;”, true);
    }

Hope this helps

Good Luck

November 29, 2009

Add DropdownList to Header of Gridview

Filed under: ASP.Net — yasserzaid @ 3:56 pm

Hi

try this example to Add DropdownList to Header of Gridview :-

protected void GridView1_RowCreated(object sender, GridViewRowEventArgs e)
{
    // check if its a header row, if so then add the ddl
    if (e.Row.RowType == DataControlRowType.Header)
    {
        // create the new ddl
        DropDownList ddl = new DropDownList();
        //add items here
        ddl.AutoPostBack = true;
        ddl.SelectedIndexChanged += new EventHandler(ddl_SelectedIndexChanged);
        // add the ddl to the row and cell of the header
        e.Row.Cells[0].Controls.Add(ddl);
    }
}

Hope this helps

Good Luck

November 27, 2009

Using Transaction with Linq

Filed under: ASP.Net, Linq — yasserzaid @ 2:02 am

Hi

try the following example to use Transaction with Linq :

– First Example :-

      DataClasses1DataContext db = new DataClasses1DataContext();
       // Get all customers list
      IQueryable<Customer> list = from x in db.Customers
                                  where x.Code > 0
                                  select x;
      Customer cust1 = list.Single<Customer>(x => x.Code == 1);
      Customer cust2 = list.Single<Customer>(x => x.Code == 2);
      // Update the first customer object
      cust1.FirstName = “yasser”;
      cust1.LastName = “zaid”;
      // Delete the second customer object
      db.Customers.Remove(cust2);
      // The update & delete operation will execte
      // in the same transaction       
      db.Connection.Open();
      db.Transaction = db.Connection.BeginTransaction();
      try
      {
          db.SubmitChanges();
          db.Transaction.Commit();
      }
      catch
      {
          db.Transaction.Rollback();
          // And do some error handling…
      }
      finally
      {
          db.Connection.Close();
          db.Transaction = null;
      }

– Second Example :-

      DataClasses1DataContext db = new DataClasses1DataContext();
      // Get all customers list
      IQueryable<Customer> list = from x in db.Customers
                                  select x;
      Customer cust1 = list.Single<Customer>(x => x.Code == 1);
      Customer cust2 = list.Single<Customer>(x => x.Code == 2);
      // Update the first customer object
      cust1.FirstName = “yasser”;
      cust1.LastName = “zaid”;
      // Delete the second customer object
      db.Customers.Remove(cust2);
      using (TransactionScope ts = new TransactionScope())
      {
          // The update & delete operation will execte in
          //the same transaction       
          db.SubmitChanges();
          ts.Complete();
      }

Hope this helps

Good Luck

November 26, 2009

Multiple Delete with Linq

Filed under: ASP.Net, Linq — yasserzaid @ 6:26 pm

Hi

try this example for Multiple Delete with Linq :-

MyAppDataContext db = new MyAppDataContext();
var objCarFeature = db.CarFeatures.Where(p=> p.Car_ID == CarID);
Dt.DataTire.db.CarFeatures.DeleteAllOnSubmit(objCarFeature);
Dt.DataTire.db.SubmitChanges();

//— another way

NorthwindDataContext context = new NorthwindDataContext();
var products = context.Products.Where(p => p.CategoryID == 1);
context.Products.DeleteAllOnSubmit(products);
context.SubmitChanges();

//— another way

MyAppDataContext db = new MyAppDataContext();
var deleteRelatedRecords = from relatedRecords in db.RelatedRecords
    where relatedRecords.MyForeignKeyID == MyPrimaryKeyID
    select relatedRecords;
foreach (var relatedRecords in deleteRelatedRecords)
{
db.RelatedRecords.DeleteOnSubmit(RelatedRecords);
}
db.SubmitChanges();

Hope this helps

Good Luck

November 23, 2009

Set default date parameter in Linq DataSource

Filed under: ASP.Net, Linq — yasserzaid @ 9:23 am

Hi

try this example

<asp:LinqDataSource ID=”LinqDataSource1″ runat=”server”
    ContextTypeName=”newDataContext” TableName=”Lists”
    Where=”startDate >= DateTime.Now”>
</asp:LinqDataSource>

another way

IF you wanted to do it completely in the codebehind, you can too (refer example)
and IF you want a Default date on a parameter:

<asp:LinqDataSource ID=”LinqDataSource1″ runat=”server”
    ContextTypeName=”newDataContext” TableName=”Lists”
    Where=”startDate &gt;= @startDate”>
    <WhereParameters>
        <asp:Parameter DefaultValue=”<%# DateTime.Now %>” Name=”startDate” Type=”DateTime” />
    </WhereParameters>
</asp:LinqDataSource>

Hope this helps

Good Luck

November 19, 2009

Send Asynchronous Email using Gmail Account

Filed under: ASP.Net — Tags: — yasserzaid @ 7:16 pm

Hi

try this example to Send Asynchronous email

1) Create a new web site

2) In Web.Config file add this :-

<system.net>
  <mailSettings>
   <smtp from=”youremail@gmail.com”>
    <network host=”smtp.gmail.com” defaultCredentials=”false” port=”587″ userName=”youremail@gmail.com” password=”xxxxx”/>
   </smtp>
  </mailSettings>
 </system.net>

3) Add new web page and in code behind :-

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Net.Mail;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
      
    }

    protected void Button1_Click(object sender, EventArgs e)
    {
        try
        {
            System.Net.Mail.MailMessage mailMessage = new System.Net.Mail.MailMessage();
            mailMessage.To.Add(new MailAddress(“any email”));
            mailMessage.To.Add(new MailAddress(“any email”));
            mailMessage.From = new MailAddress(“any email”);
            mailMessage.Subject = “my subject”;
            mailMessage.Body = “my body”;
            mailMessage.IsBodyHtml = true;
            SmtpClient smtpClient = new SmtpClient();
            smtpClient.EnableSsl = true;
            object userState = mailMessage;
            smtpClient.SendCompleted += new SendCompletedEventHandler(smtpClient_SendCompleted);
            smtpClient.SendAsync(mailMessage, userState);
        }
        catch
        {

        }
    }

    void smtpClient_SendCompleted(object sender, System.ComponentModel.AsyncCompletedEventArgs e)
    {
        try
        {
            MailMessage mailMessage = default(MailMessage);
            mailMessage = (MailMessage)e.UserState;
            if ((e.Cancelled))
            {
                lblMessage.Text = “Sending of email message was cancelled. Address=” + mailMessage.To[0].Address;
            }
            if ((e.Error != null))
            {
                lblMessage.Text = “Error occured, info :” + e.Error.Message;
            }
            else
            {
                lblMessage.Text = “Mail sent successfully”;
            }
        }
        catch (Exception ex)
        {

        }
    }   
}

Hope this helps

Good Luck

November 10, 2009

Finding IP and IP Location

Filed under: ASP.Net — Tags: — yasserzaid @ 10:40 am

Hi

try this Example to Find IP and IP Location:-

1. Create new website project and Go to solution explorer.

2. Right-click on your project name

3. Click on ‘Add Web Reference’

4. Enter this address: http://tools.webmastermafia.com/GeoIPChecker.asmx

5. Drow some Button control and TextBox Control named txtIP

6. Enter this code into button_click event:

C#:
com.webmastermafia.tools.GeoIPChecker GEO = new com.webmastermafia.tools.GeoIPChecker();
lblResult.Text = GEO.GetCountry(“test@webmastermafia.com”, “test”, txtIP.Text, “CountryName”);

Visual Basic:
Dim GEO As com.webmastermafia.tools.GeoIPChecker = new com.webmastermafia.tools.GeoIPChecker();
lblResult.Text = GEO.GetCountry(“test@webmastermafia.com”, “test”, txtIP.Text, “CountryName”)

This is for check country name by IP. If you want to check City name, than use this code:

C#:
com.webmastermafia.tools.GeoIPChecker GEO = new com.webmastermafia.tools.GeoIPChecker();
lblResult.Text = GEO.GetCity(“test@webmastermafia.com”, “test”, txtIP.Text, “City”);

Visual Basic:
Dim GEO As com.webmastermafia.tools.GeoIPChecker = new com.webmastermafia.tools.GeoIPChecker();
lblResult.Text = GEO.GetCity(“test@webmastermafia.com”, “test”, txtIP.Text, “City”)

Hope this helps

Good Luck.

November 2, 2009

Close Popup window When Press Esc Key

Filed under: ASP.Net, Javascript — Tags: — yasserzaid @ 8:17 pm

Hi

try this Example to Close Popup window When Press Esc Key using Javascript

<script type=”text/javascript” language=”javascript”>
        function doClose(e) // note: takes the event as an arg (IE doesn’t)
        {
            if (!e) e = window.event; // fix IE

            if (e.keyCode) // IE
            {
                if (e.keyCode == “27″) window.close();
            }
            else if (e.charCode) // Netscape/Firefox/Opera
            {
                if (e.keyCode == “27″) window.close();
            }
        }
        document.onkeypress = doClose;
</script>

Hope this helps

Good Luck

Blog at WordPress.com.