Showing posts with label How To Do. Show all posts
Showing posts with label How To Do. Show all posts

Wednesday, September 19, 2012

How to crop and compress an bitmap file and load it as a Meta File

    Bitmap croppedImage = bitmap.Clone(new Rectangle(0, top, bitmap.Width, limit - top), bitmap.PixelFormat);
    System.Drawing.Image cha = image;
    Graphics g = null;                                    
    ImageCodecInfo imageCodecInfo = null;
    System.Drawing.Imaging.Encoder encoder;
    EncoderParameter encoderParameter;
    EncoderParameters encoderParameters;
    ImageCodecInfo[] encoders;
    encoders = ImageCodecInfo.GetImageEncoders();
    for (int j = 0; j < encoders.Length; ++j)
        if (encoders[j].MimeType == "image/tiff")
            imageCodecInfo = encoders[j];
    encoder = System.Drawing.Imaging.Encoder.Compression;
    encoderParameters = new EncoderParameters(1);
    encoderParameter = new EncoderParameter(encoder, (long)EncoderValue.CompressionLZW);
    encoderParameters.Param[0] = encoderParameter;
    string path = this.TempFileName("tif");
    croppedImage.Save(path, imageCodecInfo, encoderParameters);
    System.Drawing.Image m = Metafile.FromFile(path);

Wednesday, December 14, 2011

How to retain the password in a postback

<%@ Page Language="C#" %>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>Test Page</title>
    <script runat="server">
        public string Password
        {
            get { return ViewState["Password"as string; }
            set { this.ViewState["Password"] = value; }
        }
        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);
            if (this.IsPostBack)
            {
                if (!string.IsNullOrEmpty(this.txtPassword.Text))
                    this.Password = this.txtPassword.Text;
                this.txtPassword.Attributes.Add("value"this.Password ?? string.Empty);
            }
        }
    </script>
</head>
<body>
    <form  id="aspNetForm" runat="server">
        UserName: <asp:TextBox runat="server" ID="txtName" />
        Password: <asp:TextBox runat="server" ID="txtPassword" TextMode="Password" />
        <hr />
        <asp:Button runat="server" ID="btnSave" Text="Save" />
    </form>
</body>
</html>

Friday, August 19, 2011

How to upload a external image link url and save on the disk

 We can get the use of HttpWebRequest and HttpWebResponse to send the request and get the response. Then response.GetResponseStream() will give us a stream of the image where we can use that stream to create a Image object like Image image = Image.FromStream(stream)

Markup:
<%@ Page Language="C#" CodeBehind="Test.aspx.cs" Inherits="ActiveTest.Test" %>
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:TextBox runat="server" ID="txtUpload" 
            Text="http://www.web-sphere.co.uk/web/websphere/blog/bloggerheader.jpg" />
        <asp:Button runat="server" ID="btnUpload" OnClick="Upload" Text="Upload" />
    </div> 
    </form>
</body>
</html>
Code:
namespace ActiveTest
{
    public partial class Test : Page
    {
        protected void Upload(object sender, EventArgs e)
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(this.txtUpload.Text);
            HttpWebResponse response = request.GetResponse() as HttpWebResponse;
            Stream stream = response.GetResponseStream();         
            ///
            /// use response content type to findout the image type, 
            /// here I just use jpg to simplify the story.
            /// 
            System.Drawing.Image image = System.Drawing.Image.FromStream(stream);
            image.Save(this.Server.MapPath(string.Format("~/Uploads/{0}.jpg",Guid.NewGuid())));
        }
    }
}

Tuesday, November 16, 2010

How to output web page as MS word document

public partial class Test : Page
{
    protected override void Render(HtmlTextWriter writer)
    {
        Response.Clear();
        Response.Buffer = true;
        Response.ContentType = "application/msword";
        StringBuilder sb = new StringBuilder();
        StringWriter stringWriter = new StringWriter(sb);
        HtmlTextWriter htmlTextWriter = new HtmlTextWriter(stringWriter);
        base.Render(htmlTextWriter);
        Response.Write(sb.ToString());
        Response.End();            
    }
}

Friday, November 12, 2010

How to keep track of selected file during a postback.

When you select a file and then do a postback, you will lose your selected file. This is because there is no ViewState for posted file in asp.net FileUpload control. This example is to demonstrate an idea of how to save the file in any-postback and if there is a selected file, then we save the file and show the fileName in a hyperlink to download or view,
Example:
<%@ Page Language="C#" %>
<html>
<head id="Head1" runat="server">
    <script runat="server">
        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);
            if (this.fuFile.HasFile)
            {                
                string filePath = Server.MapPath(string.Format("~/Uploads/{0}"this.fuFile.FileName));
                if (!System.IO.File.Exists(filePath))
                {
                    this.fuFile.SaveAs(filePath);
                    this.linkSelectedFile.NavigateUrl 
                        this.ResolveUrl(string.Format("~/Uploads/{0}", this.fuFile.FileName));
                    this.linkSelectedFile.Text = this.fuFile.FileName;
                }
            }
        }
    </script>
</head>
<body>
    <form id="form1" runat="server">
        Select a File: <asp:FileUpload runat="server" ID="fuFile" />
        <asp:HyperLink runat="server" ID="linkSelectedFile" />
        <hr />
        <asp:DropDownList runat="server" ID="ddlItems" AutoPostBack="true">
            <asp:ListItem>Item One</asp:ListItem>
            <asp:ListItem>Item Two</asp:ListItem>
        </asp:DropDownList>
    </form>
</body>
</html>

Tuesday, November 02, 2010

How to disable past days in asp.net calender control

<%@ Page Language="C#" %>
<html>   
<head id="Head1" runat="server">  
    <script runat="server">
        protected void DisablePastDays(object sender, DayRenderEventArgs e)
        {
            if (e.Day.Date < DateTime.Now)
            {
                e.Cell.Enabled = false;
                e.Day.IsSelectable = false;
                e.Cell.BackColor = System.Drawing.Color.Gray;
            }
        } 
    </script>
</head>
<body>
    <form id="form1" runat="server">
        <asp:Calendar runat="server" ID="calDate" OnDayRender="DisablePastDays" />
    </form>
</body>
</html>

How to add detail textbox opon the check of a check box

Demo:
Example:
Markup:
<%@ Page Language="C#" %>
<html>   
<head id="Head1" runat="server">  
</head>
<body>
    <form id="form1" runat="server">
        <asp:FreeCheckBox runat="server" 
            ID="freeCheckBox" 
            DetailPlaceHolderId="phDetails" 
            Text="Are you disabled?" 
            DetailLabel="Please please provide details" />
        <asp:PlaceHolder runat="server" ID="phDetails" />
        <hr />
        <asp:Button runat="server" ID="btnSave" Text="Save" />
    </form>
</body>
</html>
Control:
public class FreeCheckBox : CheckBox
{
    private TextBox txtDetail;
    private Panel pnlDetail;
    private string script = @"
    function ShowHideDetailPanel(detailPanel, source) {            
        var panel = document.getElementById(detailPanel);
        if (panel == undefined) return;
        if (source.checked == true)
            panel.style.display = ""block"";
        else
            panel.style.display = ""none"";
    }
";
    public string DetailLabel { getset; }
    public string Details { getset; }
    public string DetailPlaceHolderId { getset; }
    public bool IsMultiline { getset; }
    public FreeCheckBox()
    {
        this.DetailPlaceHolderId = string.Empty;
        this.IsMultiline = false;
    }
    protected override void OnInit(EventArgs e)
    {
        base.OnInit(e);
        this.CreateControlHeirarchy();
    }
    public void CreateControlHeirarchy()
    {
        this.pnlDetail = new Panel() { ID = string.Concat(this.ID, "_DetailPanel"), CssClass = "DetailPanel" };
        this.txtDetail = new TextBox() { ID = string.Concat(this.ID, "_TextBox"), 
                                            CssClass = "DetailTextBox", TextMode = TextBoxMode.MultiLine };
        if (this.IsMultiline) this.txtDetail.TextMode = TextBoxMode.MultiLine;
        this.pnlDetail.Controls.Add(new Label() { Text = this.DetailLabel, CssClass = "DetailLabel" });
        this.pnlDetail.Controls.Add(this.txtDetail);
        PlaceHolder phDetail = this.Page.FindControl(this.DetailPlaceHolderId) as PlaceHolder;
        Control parent = this.Parent;
        while (phDetail == null)
        {
            phDetail = parent.FindControl(this.DetailPlaceHolderId) as PlaceHolder;
            if (phDetail == null) parent = parent.Parent;
            if (parent == nullbreak;
        }
        if (phDetail != null) phDetail.Controls.Add(pnlDetail);
        this.Attributes.Add("onclick", 
                string.Format("javascript:ShowHideDetailPanel('{0}', this)", pnlDetail.ClientID));
    }
    protected override void OnLoad(EventArgs e)
    {
        base.OnLoad(e);
        if (this.Checked)
            this.pnlDetail.Attributes.Add("style""display:block;");
        else
            this.pnlDetail.Attributes.Add("style""display:none;");
    }
    protected override bool LoadPostData(string postDataKey, NameValueCollection postCollection)
    {
        bool value = base.LoadPostData(postDataKey, postCollection);
        if (this.Checked)
            this.Details = this.txtDetail.Text;
        return value;
    }
    protected override void OnPreRender(EventArgs e)
    {
        base.OnPreRender(e);
        this.Page.ClientScript.RegisterClientScriptBlock(
                this.GetType(), this.GetType().Name, this.script, true);
    }
}

How to download images

Demo:
Code:
<%@ Page Language="C#" %>
<html>   
<head id="Head1" runat="server">  
    <script runat="server">
        public void DownloadPicture(object sender, EventArgs e)
        {
            ImageButton button = sender as ImageButton;
            if (button != null)
            {
                string fileName = button.CommandArgument;
                this.Response.AddHeader("content-disposition", 
                    string.Format("attachment;filename={0}", Path.GetFileName(fileName)));
                this.Response.ContentType = "image/jpg";
                this.Response.WriteFile(this.Server.MapPath("~/Images/" + fileName));
            }
        }
    </script>
</head>
<body>
    <form id="form1" runat="server">
        <asp:ImageButton runat="server" ID="btnPic1" Text="Pic 1" CommandArgument="Image1.jpg" 
            OnClick="DownloadPicture" Width="100" Height="75" ImageUrl="~/Images/Image1.jpg" />
        <asp:ImageButton runat="server" ID="btnPic2" Text="Pic 2" CommandArgument="Image2.jpg" 
            OnClick="DownloadPicture" Width="100" Height="75" ImageUrl="~/Images/Image2.jpg" />
        <asp:ImageButton runat="server" ID="btnPic3" Text="Pic 3" CommandArgument="Image3.jpg" 
            OnClick="DownloadPicture" Width="100" Height="75" ImageUrl="~/Images/Image3.jpg" />
        <asp:ImageButton runat="server" ID="btnPic4" Text="Pic 4" CommandArgument="Image4.jpg" 
            OnClick="DownloadPicture" Width="100" Height="75" ImageUrl="~/Images/Image4.jpg"/>
        <asp:ImageButton runat="server" ID="btnPic5" Text="Pic 5" CommandArgument="Image5.jpg" 
            OnClick="DownloadPicture" Width="100" Height="75" ImageUrl="~/Images/Image5.jpg"/>
    </form>
</body>
</html>

Monday, November 01, 2010

How to implement a custom default button for a page

<%@ Page Language="C#" %>
<html>   
<head id="Head1" runat="server">
    <script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>
    <script language="javascript">
        $(document).ready(function () {
            $(".TextBox").bind("keyup"function (evt) {
                evt = (evt) ? evt : window.event
                var charCode = (evt.which) ? evt.which : evt.keyCode
                if (charCode == 13)
                    __doPostBack('<%= btnDefault.UniqueID %>''');
                return true;
            });
            $(".TextBox").bind("keypress"function (evt) {
                evt = (evt) ? evt : window.event
                var charCode = (evt.which) ? evt.which : evt.keyCode
                if (charCode == 13)
                    return false;
                return true;
            });
        });
    </script>      
    <script runat="server">
        protected void Default(object sender, EventArgs e)
        {
            Response.Write(string.Format("Default button clicked at {0}",DateTime.Now.ToString("hh:mm:ss")));
        }
    </script>
</head>
<body>
    <form id="form1" runat="server">
        <asp:TextBox runat="server" ID="TextBox1" CssClass="TextBox" onkeypress="return false" />
        <asp:TextBox runat="server" ID="TextBox2" CssClass="TextBox" onkeypress="return false" />
        <asp:TextBox runat="server" ID="TextBox3" CssClass="TextBox" onkeypress="return false" />
        <asp:TextBox runat="server" ID="TextBox4" CssClass="TextBox" onkeypress="return false" />
        <asp:TextBox runat="server" ID="TextBox5" CssClass="TextBox" onkeypress="return false" />        
        <hr />
        <asp:Button runat="server" ID="btnDefault" Text="Default" OnClick="Default" UseSubmitBehavior="false" />
        <asp:Button runat="server" ID="Button1" Text="Other" />
        <asp:Button runat="server" ID="Button2" Text="Other" />
        <asp:Button runat="server" ID="Button3" Text="Other" />
        <asp:Button runat="server" ID="Button4" Text="Other" />
        <asp:Button runat="server" ID="Button5" Text="Other" />
    </form>
</body>
</html>

How to add select other/details textbox next to selection

  1. How to add select other textbox next to DropDownList? 
  2. How to add detials textbox next to checkbox when check of a checkbox?

How to remember the TreeView selection during postbacks

Markup:
<asp:TreeView runat="server" ID="trvItems" EnableClientScript="false" />
<asp:Button runat="server" ID="btnSave" Text="Save" />
 Code:
public partial class Test : Page
{
    protected List<string> SelectedNodes
    {
        get { return (List<string>)(ViewState["TREENODECOLLECTION"] ?? (ViewState["TREENODECOLLECTION"] = new List<string>())); }
        set { ViewState["TREENODECOLLECTION"] = value; }
    }
    protected override void OnLoad(EventArgs e)
    {
        base.OnLoad(e);
        this.trvItems.TreeNodeExpanded += new TreeNodeEventHandler(TreeNodeExpanded);
        this.trvItems.TreeNodeCollapsed += new TreeNodeEventHandler(TreeNodeCollapsed);
        this.trvItems.SelectedNodeChanged += new EventHandler(SelectedNodeChanged);
        if (!this.IsPostBack)
        {
            this.InitalizeTreeView();
            this.trvItems.DataBind();
            this.trvItems.CollapseAll();
            this.SelectedNodes = new List<string>();
        }
        else
            this.SetExapandNodes(this.trvItems.Nodes);
            
    }
    protected void InitalizeTreeView()
    {
 
    }
    protected void SelectedNodeChanged(object sender, EventArgs e)
    {
            
    }
    protected void TreeNodeCollapsed(object sender, TreeNodeEventArgs e)
    {
        this.SelectedNodes.Remove(e.Node.Value);
        this.SetExapandNodes(this.trvItems.Nodes);
    }
    protected void TreeNodeExpanded(object sender, TreeNodeEventArgs e)
    {
        this.SelectedNodes.Add(e.Node.Value);
        this.SetExapandNodes(this.trvItems.Nodes);
    }
    protected void SetExapandNodes(TreeNodeCollection nodes)
    {
        foreach(TreeNode n in nodes)
        {
            if(this.SelectedNodes.Exists(x=>x.Equals(n.Value)))
                n.Expand();
            if(n.ChildNodes.Count>0)
                this.SetExapandNodes(n.ChildNodes);
        }
    }
}

Thursday, October 28, 2010

How to change a theme dynamically

We need to assign a theme in the page preInit event to legimately change the theme dynamically.
protected override void OnInit(EventArgs e)
{
    this.Theme = "Blue";
    base.OnInit(e);
}
However there are couple of challanges if you let users to chose the theme. First one is by the pre-init phase, there are not values loaded for page controls has LoadViewState has not yet been executed.
Solution 1: You can use Request.Form[...] collection.
protected override void OnInit(EventArgs e)
{
    string theme = this.Request.Form[ddlTheme.UniqueID];
    if (!string.IsNullOrEmpty(theme))
        this.Theme = theme;
    else
        this.Theme = "Default";
    base.OnInit(e);
}
Solution 2: You can use a Session variable but we have to re-execute the page to see the session variable.
protected override void OnInit(EventArgs e)
{
    string theme = Session["theme"as string;
    if (!string.IsNullOrEmpty(theme))
        this.Theme = theme;
    else
        this.Theme = "Default";
    base.OnInit(e);
}
protected void ddlTheme_SelectedIndexChanged(object sender, EventArgs e)
{
    Session["Theme"] = this.ddlTheme.SelectedValue;
    Server.Transfer("Page.aspx");
}

Sunday, October 17, 2010

How to show budy cursor while processing a request


Please note this example deos not work in Mozilla Firefox.

Demo:

<%@ Page Language="C#" %>
<html>
<head id="Head1" runat="server">
    <script runat="server">
        public void Save(object sender, EventArgs e)
        {
            System.Threading.Thread.Sleep(5000);
            this.lblLastUpdate.Text = DateTime.Now.ToString("hh:mm:ss");
        }
    </script> 
</head>
<body>
    <form id="form1" runat="server">
        <asp:ScriptManager runat="server" ID="pageScriptManager">
        </asp:ScriptManager>
        <script language="javascript" type="text/jscript">
            Sys.WebForms.PageRequestManager.getInstance().add_endRequest(function () {
                document.body.style.cursor = "auto";
            });
            Sys.WebForms.PageRequestManager.getInstance().add_beginRequest(function () {
                document.body.style.cursor = "wait";
            });
        </script>
        <asp:UpdatePanel runat="server" ID="upnlInsertContent">
            <ContentTemplate>                
                <asp:Button runat="server" ID="btnSave" OnClick="Save" Text="Save" />
                <asp:Label runat="server" ID="lblLastUpdate" />
            </ContentTemplate>
        </asp:UpdatePanel>    
    </form>
</body>
</html>

Saturday, October 16, 2010

How to find outer html content of a specified html tag in html document

string html = @"
    <html xmlns=""http://www.w3.org/1999/xhtml"" >
    <head>
     <title></title>                   
        <script language=""javascript"">
        </script>
     <style type=""text/css"">
     </style>
    </head>
    <body>
     <form target=""_blank"" id=""searchForm"">
      <a href=""Test.aspx"">Back</a>
            <table>
                <tr>
                    <td>Hello</td>
                </tr>
            </table>
            <p>some paragraph</p>
            <table>
                <tr>
                    <td>Hello</td>
                </tr>
            </table>
     </form>
    </body>
    </html>
";
protected override void OnLoad(EventArgs e)
{
    base.OnLoad(e);
    List<string> tables = this.GetTags(html, "table"true);
}
protected List<string> GetTags(string html, string tag, bool outerHtml)
{
    List<string> tables = new List<string>();
    int limit = 0, lb = 0, ub = 0, length = 0;
    length = html.Length;
    string startTag = string.Format("<{0}", tag);
    string endTag = string.Format("</{0}", tag);
    string lHtml = html.ToLower();
    do
    {
        int s = html.ToLower().IndexOf(startTag, limit);
        if (s > 0)
        {
            lb = outerHtml ? s : lHtml.IndexOf(">", s) + 1;
            limit = ub = outerHtml 
                ? lHtml.IndexOf(endTag, lb) + endTag.Length + 1 
                : lHtml.IndexOf(endTag, lb) - 1;
            tables.Add(html.Substring(lb, ub - lb));
        }
        else limit = s;
    }
    while (limit > 0);
    return tables;
}

Azure Storage Account Types

Defferent Types of Blobs Block blobs store text and binary data. Block blobs are made up of blocks of data that can be managed individually...