Yasserzaid’s Weblog

April 24, 2009

Change Color of Uploaded Image to Black and White

Filed under: ASP.Net — yasserzaid @ 11:42 pm

Hi

try this example to Change Color of Uploaded Image to Black and White

1- Create new website and add new page and New Folder and Name it Upload and inside this folder add another folder

and name it to Original

2- Open your Web page and add FileUpload and Button and Image control

<%@ Page Language=”C#” AutoEventWireup=”true” CodeFile=”ChangeImageColor.aspx.cs” Inherits=”ChangeImageColor” %>

<!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>Change Color Image to Black and White</title>
</head>
<body>
    <form id=”form1″ runat=”server”>
    <div>
    <p>Please upload your picture:
    <asp:FileUpload id=”PictureUploadControl” Width=”400″ runat=”server” />       
    </p>
        <p>
    <asp:Button runat=”server” id=”AddPictureButton” text=”Upload” onclick=”AddPictureButton_Click” /><br />
        </p>

    <asp:Image ID=”GrayscaledPhoto” runat=”server” /><br />

    </div>
    </form>
</body>
</html>

3- In code behind add this 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;
using System.Drawing;  //Bitmap needed this
using System.Drawing.Imaging; //ImageFormat needed this
using System.IO; // .delete needed this
public partial class ChangeImageColor : System.Web.UI.Page
{
    public static Bitmap Grayscale(Bitmap bitmap)
    {
        //Declare myBitmap as a new Bitmap with the same Width & Height
        Bitmap myBitmap = new Bitmap(bitmap.Width, bitmap.Height);
        for (int i = 0; i < bitmap.Width; i++)
        {
            for (int x = 0; x < bitmap.Height; x++)
            {
                //Get the Pixel
                Color BitmapColor = bitmap.GetPixel(i, x);
                //I want to come back here at some point and understand, then change, the constants
                //Declare grayScale as the Grayscale Pixel
                int grayScale = (int)((BitmapColor.R * 0.3) + (BitmapColor.G * 0.59) + (BitmapColor.B * 0.11));
                //Declare myColor as a Grayscale Color
                Color myColor = Color.FromArgb(grayScale, grayScale, grayScale);
                //Set the Grayscale Pixel
                myBitmap.SetPixel(i, x, myColor);
            }
        }
        return myBitmap;
    }

    protected void AddPictureButton_Click(object sender, EventArgs e)
    {
        if (PictureUploadControl.HasFile)
        {
            PictureUploadControl.SaveAs(Server.MapPath(“~/Upload/Original”) + PictureUploadControl.FileName);
            Bitmap oldBitmap = new Bitmap(Server.MapPath(“~/Upload/Original”) + PictureUploadControl.FileName, false);
            Bitmap newBitmap = Grayscale(new Bitmap(oldBitmap));
            string name = Guid.NewGuid().ToString();
            newBitmap.Save(Server.MapPath(“~/Upload/”) + name + “.jpg”, ImageFormat.Jpeg);
            oldBitmap.Dispose();
            //we will delete the old
           // File.Delete(Server.MapPath(“~/Upload/Original”) + PictureUploadControl.FileName);
            GrayscaledPhoto.ImageUrl = “Upload/” + name + “.jpg”;
        }
    }

    protected void Page_Load(object sender, EventArgs e)
    {

    }
}

Hope this helps

Good Luck

April 22, 2009

Use Required Field Validator for CheckboxList

Filed under: ASP.Net, Javascript — yasserzaid @ 7:20 am

Hi

try this example to use required field validator for checkboxList with Client Side

<script language=”javascript” type=”text/javascript”>
    function ValidateChkList(source, arguments)
    {                                                   
        arguments.IsValid = IsCheckBoxChecked() ? true : false;  

    }

    function IsCheckBoxChecked()
    {   
        var isChecked = false;
        var list =document.getElementById(‘<%= CheckBoxList1.ClientID %>’);
        if(list != null)
        {
         for (var i=0; i<list.rows.length; i++)
         {
          for (var j=0; j<list.rows[i].cells.length; j++)
          {
           var listControl = list.rows[i].cells[j].childNodes[0];                      
           if(listControl.checked)
           {                      
            isChecked = true;
           }
          }
         }
         }
         return isChecked;

    }
    </script>

   <div>
        <asp:CheckBoxList ID=”CheckBoxList1″ runat=”server”>
            <asp:ListItem Text=”C#” ></asp:ListItem>
            <asp:ListItem Text=”VB”></asp:ListItem>
        </asp:CheckBoxList>
        <asp:CustomValidator ID=”CustomValidator1″ ClientValidationFunction=”ValidateChkList”
            runat=”server” >Required.</asp:CustomValidator>
    </div>
    <div>
        <asp:Button ID=”Button2″ runat=”server” Text=”Submit” OnClick=”Button2_Click”  />
    </div>

Hope this helps

Good Luck

April 21, 2009

Create Popup Panel

Filed under: ASP.Net, CSS, Javascript — yasserzaid @ 9:43 pm

Hi

try this example :-

<html>
<head>

<style>

Body
{
 font-family: Arial;
}

.PopupPanel
{
 border: solid 1px black;
 position: absolute;
 left: 50%;
 top: 50%;
 background-color: white;
 z-index: 100;
 height: 200px;
 margin-top: -100px;
 width: 400px;
 margin-left: -200px;
}

.PopupPanelModalArea
{
 left: 0;
 top: 0;
 height: 100%;
 width: 100%;
 position: absolute;
 background-color:silver;
    filter: progid:DXImageTransform.Microsoft.Alpha(opacity=60);
 z-index: 99;
 border: 0;
 -moz-opacity: 0.60;
}

.PopupPanel .TitleBar
{
 margin: 0;
 display: block;
 background-color: #0058ee;
 line-height: 20px;
 color: white;
 font-weight: bold;
 padding: 0 0 0 5px;
}

.PopupPanel .ContentArea
{
 padding: 0 0 0 5px;
}

</style>

<script>
/**********************************
Simply displays or hides the panel
**********************************/
function TogglePopupPanel()
{
 var panelContainer = document.getElementById(“PopupPanel”);
 
 if (panelContainer.style.display == “none”)
 {
  panelContainer.style.display = “”;
  document.getElementById(‘PopupPanelModalArea’).focus();
  document.body.onfocus = function() { document.getElementById(‘PopupPanelModalArea’).focus(); };
 }
 else
 {
  panelContainer.style.display = “none”;
  document.body.onfocus = function() { return true; };
 }
}

</script>

</head>
<body>

This is the Popup Panel test page.  The idea is that you will not be able<br/>
to alter or interact with the contents of the underlying page while the panel is displaying.<br/>

<br/>
<input type=”Button” value=”Display Popup Panel” onclick=”TogglePopupPanel()” /><br/>
<br/>

<select>
 <option value=”0″>– Select –</option>
 <option value=”1″>One</option>
 <option value=”2″>Two</option>
 <option value=”3″>Three</option>
</select>

<input type=”Button” value=”Test Button”/><br/>

<!– ****************************** –>
<!– Start of the PopupPanel HTML   –>
<!– ****************************** –>

<div id=”PopupPanel” style=”display:none”>
 <iframe class=”PopupPanelModalArea” frameborder=”0″ scrolling=”0″ id=”PopupPanelModalArea”></iframe>
 
 <div class=”PopupPanel”>
  
  <p class=”TitleBar”>
   Popup Panel Title Bar
  </p>
  
  <p class=”ContentArea”>
   Even though the underlying page is disabled, you can however use the controls in this area
   <br/>
   <br/>
   <select>
    <option value=”0″>– Select –</option>
    <option value=”1″>One</option>
    <option value=”2″>Two</option>
    <option value=”3″>Three</option>
   </select>
   <br/>
   <br/>
   <input type=”Button” value=”Close Popup Panel” onclick=”TogglePopupPanel()” />
  </p>
 </div>
</div>
<br/>
</body>
</html>

Hope this helps

Good Luck

April 19, 2009

Show and Hide Panel using Javascript

Filed under: Javascript — yasserzaid @ 4:32 pm

Hi

try this example:-

<%@ 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>Toggle Panel</title>

    <script language=”javascript” type=”text/javascript”>
        function toggle(ID)
        { 
            var ctrlID = document.getElementById(ID);                        
            if (ctrlID.style.display == ‘none’)
            {
                ctrlID.style.display = ‘block’;
                document.getElementById(‘<%= lbTogglePanel.ClientID %>’).innerHTML=”Hide Panel”;
            }
            else
            {
                ctrlID.style.display = ‘none’;
                document.getElementById(‘<%= lbTogglePanel.ClientID %>’).innerHTML=”Show Panel”;
            }       
        }
    </script>

</head>
<body>
    <form id=”form1″ runat=”server”>
        <table cellpadding=”2″ cellspacing=”2″ border=”0″ width=”50%”>
            <tr id=”clickEvent” runat=”server”>
                <td style=”background-color: Gray; font-family: Verdana; cursor:hand; font-size: small;”>
                    <asp:Label ID=”lbTogglePanel” runat=”server” Text=”Hide Panel” Font-Underline=”true” Font-Bold=”true”></asp:Label>
                </td>
            </tr>
            <tr id=”togglePanel” runat=”server” style=”display: block; font-family: Verdana;
                font-size: small;”>
                <td>
                    <asp:Panel ID=”pnlToggle” runat=”server”>
                        <asp:Label ID=”lbl1″ runat=”server” Text=”Content 1″>
                        </asp:Label>
                        <br />
                        <asp:Label ID=”Label1″ runat=”server” Text=”Content 2″>
                        </asp:Label>
                        <br />
                        <asp:Label ID=”Label2″ runat=”server” Text=”Content 3″>
                        </asp:Label>
                    </asp:Panel>
                </td>
            </tr>
        </table>
    </form>
</body>
</html>

Hope this helps

Good Luck

April 15, 2009

Disabling mouse Right click Function (on image)

Filed under: ASP.Net — yasserzaid @ 12:31 pm

Hi

try this example :

<asp:Image ID=”Image1″ runat=”server” ImageUrl=”~/images/square.gif” oncontextmenu=”return false;” />

Hope this helps

Good Luck

April 14, 2009

Bind Table to Dynamic Data from Database

Filed under: ASP.Net — yasserzaid @ 8:47 pm

Hi

try this example to Bind Asp Table to Data from Database and make each row of this table clicable for update to

another Page

in this example i will use Northwind Database

.ASPX

<%@ Page Language=”C#” AutoEventWireup=”true” CodeFile=”Default2.aspx.cs” Inherits=”Default2″ %>

<!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>make an asp:Table row highlight and become clickable</title>
<script type=”text/javascript”>
function highlight(tableRow, active)
{
if (active)
{
tableRow.style.backgroundColor = ‘#cfc’;
}
else
{
tableRow.style.backgroundColor = ‘#fff’;
}
}

function link(Url)
{
document.location.href = Url;
}
</script>
   
</head>
<body>
    <form id=”form1″ runat=”server”>
    <div>
        <asp:Table ID=”Table1″ runat=”server”>
        </asp:Table>
    </div>
    </form>
</body>
</html>

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

public partial class Default2 : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        string connstr = ConfigurationManager.ConnectionStrings["NorthwindConnectionString"].ConnectionString;
       
        string query = “SELECT [CustomerID], [CompanyName], [ContactName], [Address], [City]“;
        query += ” FROM [Customers]“;
        SqlConnection conn = new SqlConnection(connstr);
        SqlDataAdapter da = new SqlDataAdapter(query, conn);
        DataSet ds = new DataSet();
        da.Fill(ds, “Employees”);
        foreach (DataRow dr in ds.Tables[0].Rows)
        {
            TableRow trow = new TableRow();
            foreach (DataColumn dc in ds.Tables[0].Columns)
            {
                TableCell tcell = new TableCell();
                tcell.Controls.Add(new LiteralControl(dr[dc.ColumnName].ToString()));
                trow.Cells.Add(tcell);

                trow.Attributes["onmouseover"] = “highlight(this, true);”;
                trow.Attributes["onmouseout"] = “highlight(this, false);”;
                trow.Attributes["onclick"] = “link(‘Edit.aspx?id=” + dr[0].ToString() + “‘);”;
                HttpResponse myHttpResponse = Response;
                HtmlTextWriter myHtmlTextWriter = new HtmlTextWriter(myHttpResponse.Output);
                trow.Attributes.AddAttributes(myHtmlTextWriter);
                Table1.Rows.Add(trow);
            }
        }
        conn.Close();
    }
}

and create another page called Edit.aspx and get the CustomerID from QueryString

and in web.config add this line

<connectionStrings>
  <add name=”NorthwindConnectionString” connectionString=”Data Source=.;Initial Catalog=Northwind;Integrated Security=True” providerName=”System.Data.SqlClient”/>
 </connectionStrings>

Hope this helps

Good Luck

April 13, 2009

Get User Name Under Windows Authentication

Filed under: ASP.Net — yasserzaid @ 8:32 am

Getting the authenticated user’s name when using Windows Authentication with ASP.NET is very simple.  I just keep having to go back to Google or dig out an old project to remember it, so here it is:

string username = User.Identity.Name.ToString();

Be sure to add the Security reference:

using System.Web.Security;

Hope this helps

Good Luck

April 12, 2009

Send Email using Gmail Account

Filed under: ASP.Net — yasserzaid @ 5:32 pm

Hi

try this example to Send Email using Gmail Account

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 Send_Email : System.Web.UI.Page
{
    private bool SendMail(string from, string body, string subject)
    {
        try
        {
            string mailServerName = “smtp.gmail.com”;
            MailMessage message = new MailMessage(from, “username@gmail.com“, subject, body);
            message.IsBodyHtml = true;
            SmtpClient smtp = new SmtpClient();
            smtp.Host = mailServerName;
            smtp.Host = “smtp.gmail.com”;
            smtp.EnableSsl = true;
            smtp.UseDefaultCredentials = true;
            System.Net.NetworkCredential NetworkCred = new System.Net.NetworkCredential();
            NetworkCred.UserName = “username@gmail.com“;
            NetworkCred.Password = “xxxx”;
            smtp.UseDefaultCredentials = true;
            smtp.Credentials = NetworkCred;
            smtp.Port = 587;
            smtp.Send(message);
        }
        catch (Exception ex)
        {
            ClientScript.RegisterStartupScript(Type.GetType(“System.String”), “messagebox”, “<script type=\”text/javascript\”>alert(‘An Error Accured try

again.’);</script>”);
        }
        return true;
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        txt_Email.Attributes.Add(“onpaste”, “return false;”);
        txt_Message.Attributes.Add(“onpaste”, “return false;”);
    }

    protected void btn_Send_Click(object sender, EventArgs e)
    {
        bool x = SendMail(txt_Email.Text, txt_Message.Text, txt_Subject.Text);
        if (x == true)
        {
            ClientScript.RegisterStartupScript(Type.GetType(“System.String”), “messagebox”, “<script type=\”text/javascript\”>alert(‘Message

Sent’);</script>”);
            Response.Redirect(Request.Url.ToString(), false);
        }
        else
        {
            ClientScript.RegisterStartupScript(Type.GetType(“System.String”), “messagebox”, “<script type=\”text/javascript\”>alert(‘Try again’);</script>”);
        }
    }
}

and in web.config file add this :-

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

AJAX ModalPopup with FileUpload

Filed under: AJAX — yasserzaid @ 5:11 pm

Hi

try this example :-

<%@ Page Language=”C#” %>

<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN” “http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd“>

<script runat=”server”>

    protected void ButtonOk_Click(object sender, EventArgs e)
    {
        if (FileUpload1.HasFile)
        {
            if (FileUpload1.PostedFile.ContentLength < 4096)
            {
                FileUpload1.SaveAs(Server.MapPath(“”) + FileUpload1.FileName);
            }
        }
    }
</script>

<html xmlns=”http://www.w3.org/1999/xhtml“>
<head runat=”server”>
    <title></title>
    <style type=”text/css”>
        .modalBackground
        {
            position: absolute;
            z-index: 100;
            top: 0px;
            left: 0px;
            background-color: #000;
            filter: alpha(opacity=60);
            -moz-opacity: 0.6;
            opacity: 0.6;
        }
    </style>

</head>
<body>
    <form id=”form1″ runat=”server”>
    <div>
        <asp:ScriptManager ID=”ScriptManager1″ runat=”server” />
        <asp:Panel ID=”Panel1″ runat=”server” Height=”97px” Width=”259px”
            BackColor=”Red”>
            <asp:FileUpload ID=”FileUpload1″ runat=”server” />
            <br />
            <asp:Button ID=”ButtonOk” runat=”server” Text=”OK” />
            <asp:Button ID=”ButtonCancel” runat=”server” Text=”Cancel” />
        </asp:Panel>
        <asp:Button ID=”Button1″ runat=”server” Text=”Button” />
        <ajaxToolkit:ModalPopupExtender ID=”Button1_ModalPopupExtender” runat=”server” DynamicServicePath=”"
            Enabled=”True” TargetControlID=”Button1″ PopupControlID=”Panel1″ BackgroundCssClass=”modalBackground”
            CancelControlID=”ButtonCancel” BehaviorID=”Button1_ModalPopupExtender”>
        </ajaxToolkit:ModalPopupExtender>
    </div>
    </form>
</body>
</html>

Good Luck

Get Different between two Dates

Filed under: ASP.Net — yasserzaid @ 5:08 pm

Hi

try this example to get difference between two dates in format MM/dd/yyyy hh:mm:ss

       DateTime date1 = Convert.ToDateTime(txtFromDate.Text); //– example : 02/01/2008 01:30:30
       DateTime date2 = Convert.ToDateTime(txtToDate.Text);   //– example : 03/03/2009 03:00:00

        int oldMonth = date2.Month;
        while (oldMonth == date2.Month)
        {
            date1 = date1.AddDays(-1);
            date2 = date2.AddDays(-1);
        }

        int years = 0, months = 0, days = 0, hours = 0, minutes = 0, seconds = 0, milliseconds = 0;

        // getting number of years
        while (date2.CompareTo(date1) >= 0)
        {
            years++;
            date2 = date2.AddYears(-1);
        }
        date2 = date2.AddYears(1);
        years–;

        // getting number of months and days
        oldMonth = date2.Month;
        while (date2.CompareTo(date1) >= 0)
        {
            days++;
            date2 = date2.AddDays(-1);
            if ((date2.CompareTo(date1) >= 0) && (oldMonth != date2.Month))
            {
                months++;
                days = 0;
                oldMonth = date2.Month;
            }
        }
        date2 = date2.AddDays(1);
        days–;

        TimeSpan difference = date2.Subtract(date1);

        Response.Write(” Difference: ” +
            years.ToString() + ” years” +
            “, ” + months.ToString() + ” months” +
            “, ” + days.ToString() + ” days” +
            “, ” + difference.Hours.ToString() + ” hours” +
            “, ” + difference.Minutes.ToString() + ” minutes” +
            “, ” + difference.Seconds.ToString() + ” seconds” +
            “, ” + difference.Milliseconds.ToString() + ” milliseconds”);

//——–or try this ———-

 DateTime frdt = Convert.ToDateTime(txtFromDate.Text); //– example : 2/1/2009 01:30:30
        DateTime todt = Convert.ToDateTime(txtToDate.Text);   //– example : 2/2/2009 22:00:00
        TimeSpan span = todt.Subtract(frdt);
        Response.Write(“Time Difference (seconds): ” + span.Seconds);
        Response.Write(“<br/>”);
        Response.Write(“Time Difference (minutes): ” + span.Minutes);
        Response.Write(“<br/>”);
        Response.Write(“Time Difference (hours): ” + span.Hours);
        Response.Write(“<br/>”);
        Response.Write(“Time Difference (days): ” + span.Days);
        Response.Write(“<br/>”);

Hope this helps

Good Luck

Older Posts »

Blog at WordPress.com.