Archive

Archive for November, 2009

Change Font Dynamically using Javascript

November 30, 2009 Leave a comment

Hi

you can check this previous post

Dynamic font size change using javascript

now i’m going to provide second way to change font dynamically using Javascript

Javascript Function :-

<script type="text/javascript">
    //Specify affected tags. Add or remove from list:
        var tgs = new Array( 'div','td','tr', 'p', 'span', 'font');
        //Specify spectrum of different font sizes:
        var szs = new Array( 'xx-small','x-small','small','medium','large','x-large','xx-large' );
        var startSz = 2;
        function ts( trgt,inc )
        {
         if (!document.getElementById) return
         var d = document,cEl = null,sz = startSz,i,j,cTags;
         sz += inc;
         if ( sz < 0 ) sz = 0;
         if ( sz > 6 ) sz = 6;
         startSz = sz;
         if ( !( cEl = d.getElementById( trgt ) ) ) cEl = d.getElementsByTagName( trgt )[ 0 ];
         cEl.style.fontSize = szs[ sz ];
         for ( i = 0 ; i < tgs.length ; i++ ) {
          cTags = cEl.getElementsByTagName( tgs[ i ] );
          for ( j = 0 ; j < cTags.length ; j++ ) cTags[ j ].style.fontSize = szs[ sz ];
         }
        }
    </script>

HTML Page :-

 <div style =" text-align:left; width:100%; padding:0; margin:0">
      <a href="javascript:ts('main',1)" ><img src="zoom-in.gif" alt="Zoom In" /></a> |
      <a href="javascript:ts('main',-1)"><img src="zoom-out.gif"  alt="Zoom Out" /></a>
   </div>
   <div id="dvKeys" style="display:none">
   </div>
   <div id="main">
    any text here
</div>

Hope this helps

Good Luck

Categories: ASP.Net, Javascript

AJAX AsynFile Upload with File Extension Validation

November 30, 2009 Leave a comment

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

Categories: AJAX, ASP.Net Tags:

Add DropdownList to Header of Gridview

November 29, 2009 4 comments

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

Categories: ASP.Net

Using Transaction with Linq

November 27, 2009 Leave a comment

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

Categories: ASP.Net, Linq

Multiple Delete with Linq

November 26, 2009 Leave a comment

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

Categories: ASP.Net, Linq

Set default date parameter in Linq DataSource

November 23, 2009 Leave a comment

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

Categories: ASP.Net, Linq

Send Asynchronous Email using Gmail Account

November 19, 2009 Leave a comment

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

Categories: ASP.Net Tags: