Yasserzaid’s Weblog

October 29, 2009

Increase file Uploaded size

Filed under: ASP.Net — yasserzaid @ 1:37 pm

By Default, we can’t upload files with size more the 4Mb, because it’s already configured in the machine.web file. as follows:
<httpRuntime maxRequestLength =”4096″/>  where 4096 in kb

Although you can overload these settings in the web.config file

add in the <system.web>

<httpRuntime maxRequestLength =”5120″/>

Which allows uploading files up to for example 5120 = 5Mb.

Hope this helps

Good Luck

October 27, 2009

AJAX Update Progress with Upload Image

Filed under: AJAX, ASP.Net — Tags: , — yasserzaid @ 6:38 pm

Hi

try this example to use AJAX Update Progress with Upload Image

1) Open VS 2005 and create new AJAX Website

2) Add new folder called “Upload” which will upload image on it

3)  Add new web page

<%@ Page Language=”C#” AutoEventWireup=”true” CodeFile=”Default.aspx.cs” Inherits=”_Default” %>
<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.1//EN” “http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd”>
<html xmlns=”http://www.w3.org/1999/xhtml”>
<head runat=”server”>
<title>Upload Image</title>
<style type=”text/css”>
.Progress
 {
   background-color:#CF4342;
   color:White;
   width:105px;
 }
 
.Progress img {
   vertical-align:middle;
   margin:2px;
 }

.progressBackgroundFilter {
  position:absolute;
  top:0px;
  bottom:0px;
  left:0px;
  right:0px;
  overflow:hidden;
  padding:0;
  margin:0;
  background-color:#000; 
  filter:alpha(opacity=50);
  opacity:0.5;
  z-index:1000;
}

.processMessage { 
  position:absolute; 
  top:30%; 
  left:43%;
  padding:10px;
  width:14%;
  z-index:1001;
  background-color:#fff;
}
</style>
<script language=”javascript” type=”text/javascript” >
//— to validate extension of fileupload control
function ValidateFile(source, args)    
{

try        
{              
var fileAndPath=document.getElementById(source.controltovalidate).value;       
var lastPathDelimiter=fileAndPath.lastIndexOf(“\\”);       
var fileNameOnly=fileAndPath.substring(lastPathDelimiter+1);              
var file_extDelimiter=fileNameOnly.lastIndexOf(“.”);       
var file_ext=fileNameOnly.substring(file_extDelimiter+1).toLowerCase();       
if(file_ext!=”jpg”)            
{            
args.IsValid = false;            
if(file_ext!=”gif”)              
args.IsValid = false;                 
if(file_ext!=”png”)                 
{                   
args.IsValid = false;                    
return;                 
}               
}       
}
catch(err)       
{         
txt=”There was an error on this page.\n\n”;         
txt+=”Error description: ” + err.description + “\n\n”;         
txt+=”Click OK to continue.\n\n”;         
txt+=document.getElementById(source.controltovalidate).value;         
alert(txt);         
}                   
args.IsValid = true;   
}   

//– to show UpdateProgress if FileUpload has File
function showWait()
{
    var isValid = Page_ClientValidate(“img”);
     if ( isValid == true )
     {
        if(document.getElementById(‘<%=fileUp.ClientID %>’).value != “”)
        {
            $get(‘UpdateProgress1′).style.display = ‘block’;

            return true;
        }
        else
        {
            alert(“SelectImage”);
            return false;
        }

      }  
}
</script>   
</head>
<body>
    <form id=”form1″ runat=”server”>
        <asp:ScriptManager ID=”ScriptManager1″ runat=”server” />
        <div>
            <asp:UpdatePanel ID=”UpdatePanel1″ runat=”server” UpdateMode=”Conditional”>
                <ContentTemplate>
        <asp:FileUpload ID=”fileUp” runat=”server”  />
        <asp:CustomValidator ID=”CustomValidator1″ runat=”server”
            ClientValidationFunction=”ValidateFile” ControlToValidate=”fileUp”
            Display=”Dynamic” ErrorMessage=”Select Image” ValidationGroup=”img” ></asp:CustomValidator>
            <br />
            <asp:Button ID=”btnAddFile” runat=”server” CausesValidation=”False”
                onclick=”btnAddFile_Click”  OnClientClick=”javascript:return showWait();”
                Text=”Add Image” ValidationGroup=”img” />
                </ContentTemplate>
                <Triggers>
                    <asp:PostBackTrigger ControlID=”btnAddFile” />
                </Triggers>
            </asp:UpdatePanel>
        </div>

        <asp:UpdateProgress ID=”UpdateProgress1″ runat=”server” AssociatedUpdatePanelID=”UpdatePanel1″  >
        <ProgressTemplate>
        <div id=”progressBackgroundFilter”></div>
        <div id=”processMessage” align=”center”>
        <asp:Label ID=”Label32″ runat=”server” Text=”Loading …” ></asp:Label><br /><br /><img src=”Images/5.gif” alt=”Loading” />
         </div>

    </ProgressTemplate>
    </asp:UpdateProgress>
    </form>
</body>
</html>

4) In code behind in Button Click Event:-

protected void btnAddFile_Click(object sender, EventArgs e)
    {
        System.Threading.Thread.Sleep(1000);
        //string filename = System.IO.Path.GetFileName(fileUp.FileName);
        //fileUp.SaveAs(Server.MapPath(“~/Upload/”) + filename);
        string File = Guid.NewGuid().ToString() + Path.GetExtension(fileUp.FileName);
        fileUp.SaveAs(Server.MapPath(“~/Upload/”) + File);
    }

Hope this helps

Good Luck

 

Bind DropdownList from XML file

Filed under: ASP.Net, XML — yasserzaid @ 4:50 pm

Hi

try this example to Bind DropdownList from xml file on server

1) Open VS 2005 and create new website

2) Add new xml file “XMLFile.xml”

<?xml version=”1.0″ encoding=”utf-8″ ?>
<Countries>
  <Country>
    <ID>1</ID>
    <Name>Nepal</Name>
  </Country>
  <Country>
    <ID>2</ID>
    <Name>India</Name>
    <Country>
      <ID>3</ID>
      <Name>China</Name>
    </Country>
    <Country>
      <ID>4</ID>
      <Name>Bhutan</Name>
    </Country>
    <Country>
      <ID>5</ID>
      <Name>USA</Name>
    </Country>
  </Country>
</Countries>

3) Add new Web page and inside it add DropdownList control

4) In Code behind add the following code:

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;

public partial class _Default : System.Web.UI.Page
{
    public void Bind()
    {
        DataSet ds = new DataSet(); 
        ds.ReadXml(Server.MapPath(“~/XMLFile.xml”)); 
 
        //get the dataview of table “Country”, which is default table name 
        DataView dv = ds.Tables[0].DefaultView; 

        //Now sort the DataView vy column name “Name” 
        dv.Sort = “Name”; 
        //now define datatext field and datavalue field of dropdownlist 
        DropDownList1.DataTextField = “Name”;
        DropDownList1.DataValueField = “ID”; 
 
        //now bind the dropdownlist to the dataview 
        DropDownList1.DataSource = dv;
        DropDownList1.DataBind(); 
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            Bind();
        }
    }
}

Hope this helps

Good Luck

Convert database tables into XML and Schema

Filed under: XML — yasserzaid @ 4:08 pm

Hi

try this example :-

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.Data.SqlClient;

public partial class xml : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        string strConnect = ConfigurationManager.ConnectionStrings["Northwind"].ConnectionString;
        string strSelect = “SELECT * FROM Employees”;
        DataSet objDataSet = new DataSet();
        SqlConnection objConnect = new SqlConnection(strConnect);
        SqlDataAdapter objDataAdapter = new SqlDataAdapter(strSelect, objConnect);
        objDataAdapter.Fill(objDataSet, “Employees”);
        string strVirtualPath = Request.ApplicationPath + “/Employees.xml”;
        string strVSchemaPath = Request.ApplicationPath + “/Employees.xsd”;
        objDataSet.WriteXml(Request.MapPath(strVirtualPath));
        objDataSet.WriteXmlSchema(Request.MapPath(strVSchemaPath));
    }
}

Hope this helps

Good Luck

October 24, 2009

Use LINQ to XML to create XML document from Database

Filed under: Linq — Tags: — yasserzaid @ 3:44 pm

Hi

try this example to Use LINQ to XML to create XML document from database :-

1) Open VS 2008

2) Create new website

3) Add the following code in code behind :-

using System;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Data.SqlClient;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            using (SqlConnection conn = new SqlConnection(“Data Source=localhost;Initial Catalog=Northwind;Integrated Security=True”))
            {
                conn.Open();
                SqlCommand comm = new SqlCommand(“select CategoryID, CategoryName, Description from Categories”, conn);
                IDataReader reader = comm.ExecuteReader();
                DataTable dt = new DataTable();
                dt.Load(reader);
                var xmlDoc = new XDocument(
                    new XElement(“rootElement”,
                        new XElement(“categories”,
                            from cat in dt.AsEnumerable()
                            select new XElement(“category”,
                                       new XAttribute(“CategoryID”, cat["CategoryID"]),
                                       new XAttribute(“CategoryName”, cat["CategoryName"]),
                                       new XAttribute(“Description”, cat["Description"])
                                )
                       )
                    )
                );
                Response.Clear();
                Response.ContentType = “text/xml”;
                xmlDoc.Save(Response.Output, SaveOptions.None);
                Response.End();
                reader.Close();
                comm.Dispose();
            }
        }
    }
}

Hope this helps

Good Luck

October 23, 2009

Displaying two Column Fields in DropDownList Control using Linq

Filed under: ASP.Net, Linq — Tags: — yasserzaid @ 1:53 pm

Hi

try this example :-

1) create new website using VS 2008

2) In this example i use Northwind database

3) Add new Data Context Class called “Northwind.dbml” and add Employee table in it 

4) Add new web page and add DropdownList control and in code behind add the following code

protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            Bind();
        }
    }

    private void Bind()
    {
        NorthwindDataContext db = new NorthwindDataContext();
        var emp = from em in db.Employees
                  select new { EmployeeID = em.EmployeeID, FullName = em.FirstName + ” ” + em.LastName };
        DropDownList1.DataSource = emp;
        DropDownList1.DataTextField = “FullName”;
        DropDownList1.DataValueField = “EmployeeID”;
        DropDownList1.DataBind();
    }

Hope this helps

you can also check this link to Displaying two Column Fields in DropDownList Control from Here

Good Luck

October 16, 2009

JQuery to Refresh the page for every 5 minutes

Filed under: Jquery — yasserzaid @ 1:04 pm

Hi

try this example to Refresh the page for every 5 minutes using JQuery :-

<%@ Page Language=”C#” AutoEventWireup=”true” CodeFile=”Default.aspx.cs” Inherits=”_Default” %>
<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN” “http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”>
<html xmlns=”http://www.w3.org/1999/xhtml” >
<head runat=”server”>
    <title>Untitled Page</title>
    <script language=”javascript” type=”text/javascript” src=”jquery-latest.js”></script>   
    <script language=”javascript” type=”text/javascript”>
        $(document).ready(function() {
            setInterval(“location.reload(true)”, 300000);
        });   
    </script>
</head>
<body>
    <form id=”form1″ runat=”server”>
    <div>
      I’ll refresh every 5 minutes!
    </div>
    </form>
</body>
</html>

Hope this helps

Good Luck

October 14, 2009

Disable and Restrict Copy Cut and Paste from on a Textbox

Filed under: ASP.Net, Javascript — yasserzaid @ 4:08 pm

Hi

try this example to Disable and Restrict Copy Cut and Paste from on a textbox using Javascript

You will need two javascript functions for this:

    function noCopyMouse(e) {
        var isRight = (e.button) ? (e.button == 2) : (e.which == 3);
       
        if(isRight) {
            alert(‘You are prompted to type this twice for a reason!’);
            return false;
        }
        return true;
    }

    function noCopyKey(e) {
        var forbiddenKeys = new Array(‘c’,'x’,'v’);
        var keyCode = (e.keyCode) ? e.keyCode : e.which;
        var isCtrl;

        if(window.event)
            isCtrl = e.ctrlKey
        else
            isCtrl = (window.Event) ? ((e.modifiers & Event.CTRL_MASK) == Event.CTRL_MASK) : false;
   
        if(isCtrl) {
            for(i = 0; i < forbiddenKeys.length; i++) {
                if(forbiddenKeys[i] == String.fromCharCode(keyCode).toLowerCase()) {
                    alert(‘You are prompted to type this twice for a reason!’);
                    return false;
                }
            }
        }
        return true;
    } 
 
And a wee bit of code-behind to handle the two events for the textbox(es):

Textbox1.Attributes.Add(“onmousedown”, “return noCopyMouse(event);”)
 Textbox1.Attributes.Add(“onkeydown”, “return noCopyKey(event);”)

 Hope this helps

Good Luck

October 12, 2009

Allow Users to Change Their Email Address using Membership

Filed under: ASP.Net — Tags: — yasserzaid @ 5:55 pm

Hi

try this example to Allow Users to Change Their Email Address using Membership :-

in code behind :-

protected void Page_Load(object sender, EventArgs e)
{
    //add theses lines
    if (!IsPostBack)
   {
      MembershipUser user = Membership.GetUser();
       if (user != null)
      {
         txtEmail.Text = user.Email;
      }
   }
}
Then, we need to add the method that fires when the Change Email button is clicked.

//add this methodprotected void btnEmail_Click(object sender, EventArgs e)
{
   if (IsValid)
   {
      MembershipUser user = Membership.GetUser();
       if (user != null && txtEmail.Text != user.Email)
       {
         user.Email = txtEmail.Text;
          try
         {
            Membership.UpdateUser(user);
            lblEmailChangeSuccess.Text = “Your email address was successfully changed.”;
         }
         catch (ProviderException)
         {
            lblEmailChangeFail.Text = “A user with that email address already exists. Your address was not changed.”;
         }
      }
   }
}

Hope this helps

Good Luck

October 5, 2009

Highlight Row on MouseOver in Repeater Control

Filed under: ASP.Net — yasserzaid @ 9:59 pm

Hi

try this example to Highlight Row on MouseOver in Repeater or DataList Control

<%@ Page Language=”vb” Src=”HighlightRepeater.aspx.vb” Inherits=”HighlightRepeater”%>
 <!DOCTYPE HTML PUBLIC “-//W3C//DTD HTML 4.0 Transitional//EN”>
 <html>
 <head>
 <title>Highlight Repeater Row</title>
 </head>
 <body>
 <table width=”50%”>
   <tr>
     <td bgcolor=”black” align=”center”><font color=”white”><b>Customer Data</b></font></td>
   </tr>
 </table>
 <form id=”Form1″ method=”post” runat=”server”>
  <asp:Repeater ID=”Repeater1″ Runat=”server”>
   <HeaderTemplate>
     <table width=”50%” cellspacing=”0″ cellpadding=”0″>
       <tr>
         <td bgcolor=”black” align=”left”><font color=”white”><b>Customer ID</b></font></td>
         <td bgcolor=”black” align=”left”><font color=”white”><b>Company Name</b></font></td>
         <td bgcolor=”black” align=”left”><font color=”white”><b>Contact Name</b></font></td>
       </tr>
   </HeaderTemplate>
   <ItemTemplate>
       <a href=”ShowCust.aspx?id=<%# Container.DataItem(“CustomerID”) %>”>
       <tr style=”cursor:hand” onmouseover=”style.backgroundColor=’LightBlue’” onmouseout=”style.backgroundColor=””>
         <td align=”left”><%# Container.DataItem(“CustomerID”) %></td>
         <td align=”left”><%# Container.DataItem(“CompanyName”) %></td>
         <td align=”left”><%# Container.DataItem(“ContactName”) %></td>
       </tr>
       </a>
   </ItemTemplate>
   <FooterTemplate>
     </table>
   </FooterTemplate>
 </asp:Repeater>
 </form>
 </body>
 </html>

Hope this helps

Good Luck

Older Posts »

Blog at WordPress.com.