Thursday, September 09, 2010

How to print fit to page

Microsoft Internet Explorer
1. Select File and then Page Setup
2. Tick on Fit to page check box
Mozilla Firefox
1. Select File and then Page Setup
2. Tick on Fit to page check box

How to print background colors in common web browsers

Microsoft Internet Explorer:
Method 1:
1. Open Tools

2. Select Advanced and under print options, tick on print background colors and images
Method 2:
1. Select File then Page Setup
2. Then tick print background colors and images
Mozialla FireFox:
1. Select File and then Page Setup
2. Tick print background colors and images check box

How to convert Html page to a Image using WebBrowser

  1. Part 1 - In windows Forms - Naturally single threaded apartment - read more
  2. Part 2 - In Asp.net Web Forms - Multi apartment thread but can run as a STA or Asp compact mode - read more
  3. Part 3 - How to take a snapshot of the working (asp.net form) page using WebBrowser - read more

How to convert Html page to a Image using WebBrowser in Asp.net

Thumbnail Image:
public class Thumbnail
{
    public string Url { getset; }
    public Bitmap ThumbnailImage { getset; }
    public int Width { getset; }
    public int Height { getset; }
    public int BrowserWidth { getset; }
    public int BrowserHeight { getset; }
 
    public Thumbnail(string Url, int BrowserWidth, int BrowserHeight, int ThumbnailWidth, int ThumbnailHeight)
    {
        this.Url = Url;
        this.BrowserWidth = BrowserWidth;
        this.BrowserHeight = BrowserHeight;
        this.Height = ThumbnailHeight;
        this.Width = ThumbnailWidth;
    }
    public Bitmap GenerateThumbnail()
    {
        Thread thread = new Thread(new ThreadStart(GenerateThumbnailInteral));
        thread.SetApartmentState(ApartmentState.STA);
        thread.Start();
        thread.Join();
        return ThumbnailImage;
    }
    private void GenerateThumbnailInteral()
    {
        WebBrowser webBrowser = new WebBrowser();
        webBrowser.ScrollBarsEnabled = false;
        webBrowser.Navigate(this.Url);
        webBrowser.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(WebBrowser_DocumentCompleted);
        while (webBrowser.ReadyState != WebBrowserReadyState.Complete) Application.DoEvents();
        webBrowser.Dispose();
    }
    private void WebBrowser_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
    {
        WebBrowser webBrowser = (WebBrowser)sender;
        webBrowser.ClientSize = new Size(this.BrowserWidth, this.BrowserHeight);
        webBrowser.ScrollBarsEnabled = false;
        this.ThumbnailImage = new Bitmap(webBrowser.Bounds.Width, webBrowser.Bounds.Height);
        webBrowser.BringToFront();
        webBrowser.DrawToBitmap(ThumbnailImage, webBrowser.Bounds);
        this.ThumbnailImage = (Bitmap)ThumbnailImage.GetThumbnailImage(Width, Height, nullIntPtr.Zero);
    }
}
Test Page:
<%@ Page Language="C#" %>
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <script runat="server">
        protected void CreateThumbnailImage(object sender, EventArgs e)
        {
            string url = string.Format("http://{0}", txtWebsiteAddress.Text);
            int width = Int32.Parse(txtWidth.Text);
            int height = Int32.Parse(txtHeight.Text);
            Thumbnail thumbnail = new Thumbnail(url, 800, 600, width, height);
            Bitmap image = thumbnail.GenerateThumbnail();
            image.Save(Server.MapPath("~") + "/Thumbnail.bmp");
            imgThumbnailImage.ImageUrl = "~/Thumbnail.bmp";
            imgThumbnailImage.Visible = true;
        }     
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:TextBox ID="txtWebsiteAddress" runat="server" Text="www.google.com" /> 
        <asp:Button ID="btnCreateThumbnailImage" runat="server" Text="Create Thumbnail Image" OnClick="CreateThumbnailImage" /></td>
        <asp:TextBox ID="txtWidth" runat="server" Text="200" />
        <asp:TextBox ID="txtHeight" runat="server" Text="200" />
        <asp:Image ID="imgThumbnailImage" runat="server" Visible="false" />
    </div>
    </form>
</body>
</html>

How to remove external links from a asp.net web page

<%@ Page Language="C#" %>
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <script runat="server">
        public string RootUrl
        {
            get
            {
                Uri requestUri = Context.Request.Url;
                HttpRequest request = Context.Request;
                string rootUrl = string.Format("{0}{1}{2}{3}{4}",
                    requestUri.Scheme,
                    Uri.SchemeDelimiter,
                    requestUri.Host,
                    requestUri.IsDefaultPort ? string.Empty : string.Format(":{0}", requestUri.Port),
                    request.ApplicationPath);
                return rootUrl.EndsWith("/") ? rootUrl : string.Format("{0}/", rootUrl);
            }
        }
        protected override void Render(HtmlTextWriter writer)
        {
            StringBuilder sb = new StringBuilder();
            HtmlTextWriter htw = new HtmlTextWriter(new StringWriter(sb));
            base.Render(htw);
            string html = sb.ToString();
 
            string tag = "a";
 
            List<string> tags = new List<string>();
            int limit = 0, lb = 0, ub = 0;
            string startTag = string.Format("<{0}", tag);
            string endTag = string.Format(">", tag);
            string lHtml = html.ToLower();
            do
            {
                lb = lHtml.IndexOf(startTag, limit);
                if (lb > 0)
                {
                    limit = ub = lHtml.IndexOf(endTag, lb) + endTag.Length;
                    tags.Add(html.Substring(lb, ub - lb));
                }
                else limit = lb;
            }
            while (limit > 0);
            foreach (string a in tags)
            {
                string link = a.ToLower();
                link = link.Replace("'""\"");
                lb = link.IndexOf("href");
                lb = link.IndexOf("\"", lb);
                ub = link.IndexOf("\"", lb + 1);
                string href = link.Substring(lb + 1, ub - (lb + 1));
                if (href.StartsWith("http://") && !href.StartsWith(this.RootUrl.ToLower()))
                {
                    link = link.Replace(href, string.Format("{0}StopUrl.aspx"this.RootUrl));
                    html = html.Replace(a, link);
                }
            }
            writer.Write(html);
        }
     
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <a href="About.aspx">About</a>
        <a href="Default.aspx">Home</a>
        <a href="http://www.yahoo.com">Yhaoo</a>
        <a href="http://localhost/ActiveTest/Test.aspx">Test Page</a>
    </div>
    </form>
</body>
</html>

Tuesday, September 07, 2010

LoadViewState(...) method does not fire in a postback

Unless you have some values in the ViewState the LoadViewState(...) method will not get fired in a postback.
Example:
<%@ Page Language="C#" %>
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <script runat="server">
        public string Value
        {
            get { return (string)ViewState["Value"]; }
            set { ViewState["Value"] = value; }
        }
        protected override void LoadViewState(object savedState)
        {
            Response.Write("Load View State <br />");
            base.LoadViewState(savedState);
        }
        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);
            Response.Write("Page Load <br />");
        }
        protected void Save(object sender, EventArgs e)
        {
            Response.Write("My Save Method - I didnt add anyting to View state <br />");
        }
        protected override object SaveViewState()
        {
            Response.Write("Save View State <br />");
            return base.SaveViewState();
        }
        protected void Add(object sender, EventArgs e)
        {
            Response.Write(string.Format("My Add Method - I add some value to view state <strong>{0}</strong> <br />",
                string.IsNullOrEmpty(this.Value) ? "Next time page will load view sate" : string.Empty));
            this.Value = DateTime.Now.ToShortTimeString();
        }
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <div id="ProductList">
            <asp:Button runat="server" ID="btnSave" OnClick="Save" Text="Save" />
            <asp:Button runat="server" ID="btnAdd" OnClick="Add" Text="Add" />
        </div>
    </div>
    </form>
</body>
</html>

Saturday, September 04, 2010

How to find browser window close or refresh using java script

Tested and works in IE, Mozilla FireFox, Safari
<%@ Page Language="C#" %>
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title>ClientScriptManager Example</title>
    <script type="text/javascript">
        window.onbeforeunload = function (evt) {
            var message = 'Are you sure you want to leave?';
            if (typeof evt == 'undefined') {
                evt = window.event;
            }
            if (evt) {
                evt.returnValue = message;
            }
            return message;
        } 
    </script>
</head>
<body>
    <form id="Form1" runat="server">
    <div>
 
    </div>
    </form>
</body>
</html>

How to use ICallbackEventHandler and execute a server method from java script in Asp.net

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>ClientScriptManager Example</title>
    <script type="text/javascript">
        var value1 = 0;
        var value2 = 0;
        function ReceiveServerData2(arg, context) {
            Message2.innerText = arg;
            value2 = arg;
        }
        function ProcessCallBackError(arg, context) {
            Message2.innerText = 'An error has occurred.';
        }
    </script>
</head>
<body>
    <form id="Form1" runat="server">
    <div>
        Callback 1 result: <span id="Message1">0</span>
        <br />
        Callback 2 result: <span id="Message2">0</span>
        <br />
        <br />
        <input type="button" value="ClientCallBack1" onclick="CallTheServer1(value1, alert('Increment value'))" />
        <input type="button" value="ClientCallBack2" onclick="CallTheServer2(value2, alert('Increment value'))" />
        <br />
        <br />
        <asp:Label ID="lblMessage" runat="server"></asp:Label>
    </div>
    </form>
</body>
</html>
Code Behind:
namespace ActiveTest
{
    public partial class Test : PageICallbackEventHandler
    {
        #region Attributes
 
        public int callBackCount = 0;
        private string script = @"
            function ReceiveServerData1(arg, context)
            {
                Message1.innerText = arg;
                value1 = arg;
            }
        ";
 
        #endregion
 
        #region ICallbackEventHandler Members
 
        public void RaiseCallbackEvent(String eventArgument)
        {
            callBackCount = Convert.ToInt32(eventArgument) + 1;
        }
        public string GetCallbackResult()
        {
            return callBackCount.ToString();
        }
 
        #endregion
 
        protected void Page_Load(object sender, EventArgs e)
        {
            StringBuilder sb = new StringBuilder();
            sb.Append("No page postbacks have occurred.");
            if (Page.IsPostBack)
            {
                sb.Append("A page postback has occurred.");
            }
            this.lblMessage.Text = sb.ToString();
            ClientScriptManager cs = Page.ClientScript;
 
            String cbReference1 = cs.GetCallbackEventReference(this"arg""ReceiveServerData1"this.script);
            String cbReference2 = cs.GetCallbackEventReference("'" + Page.UniqueID + "'""arg",
                                                            "ReceiveServerData2""""ProcessCallBackError"false);
            String callbackScript1 = "function CallTheServer1(arg, context) {" + cbReference1 + "; }";
            String callbackScript2 = "function CallTheServer2(arg, context) {" + cbReference2 + "; }";
            cs.RegisterClientScriptBlock(this.GetType(), "CallTheServer1", callbackScript1, true);
            cs.RegisterClientScriptBlock(this.GetType(), "CallTheServer2", callbackScript2, true);
        }
    }
}
 

Reference - MSDN

Friday, September 03, 2010

Ambiguous namespaces in while having classes App_Code directory.

If you dont need read the rest of this article and relax the rest of the day,
Solution:
Rename the App_Code folder to AppCode

Cause:
For the demonstration, I use custom type define as page base to provide common features to all pages. This base type been configured from the web.config. However this is not specific to page base type, this can happen to any type which referred at runtime from the web.config, like custom configuration classes.

Description: An error occurred during the processing of a configuration file required to service this request. Please review the specific error details below and modify your configuration file appropriately.

Parser Error Message:
The type WebNamespace.PageBase' is ambiguous: it could come from assembly 'C:\Windows\Microsoft.NET\Framework\v4.0.30319\Temporary ASP.NET Files\webnapplication\8235a0d2\f00609ba\App_Code.atbdii2e.DLL' or from assembly 'C:\Projects\WebSite\bin\WebNamespace.DLL'. Please specify the assembly explicitly in the type name.

Source Error:

Line 34:                           <error statusCode="500" redirect="error.html"/>
Line 35:                  </customErrors>
Line 36:                  <pages pageBaseType="WebNamespace.PageBase" ...>
Line 37:                           <controls>
Line 38:                                    <add tagPrefix="ajax" .../>

Why this happen?
When you have pages which does not contain specific code behind file in the solution but some scripts with run-at server in the mark-up, visual studio and asp.net create temporary DLL file in the asp.net temporary files folder (located at c:/Windows/Microsoft.NET/Framework/Asp.net-Version/Temporary Asp.net Files/ApplicationName). In such a occasion, when you add a class file to App_Code directory, which has its own name space within asp.net web application’s assembly this class get created in both temporary and fixed assembly. Then from the configuration, it any of these classes being referred you get a run-time error stating ambiguous type. This is because while asp.net creates temporary assembly for temporary classes which does not have specific file to inherit, asp.net automatically merges all the class files which are located at App_Code directory regardless of what they are, causing same class to be in two different assemblies.
Then you may wonder why I can’t specify assembly along with the type name like this.
<pages pageBaseType="WebApplication.PageBase, WebAssemblyName"...
But still no luck, .net can’t distinguish the type in conflicting assemblies.
Conclusion:
It is better to not to use App_Code folder for your custom classes which get referred at run-time.

How to find html tags and content inside rendered html in code behind

Finding html tags and tag content in the code behind is something you may find useful  when providing custom render time tweaks your asp.net website. By the render time you can control many more features like root URL and broken links etc. Following are two useful scripts that you may find useful when tweaking rendered html of asp.net pages.

Please consider this example:
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <script language="javascript">
        function SayHello() {
            alert("Hello");
        }
    </script>
</head>
<body>
    <form id="form1" runat="server">
        <p>This is sample paragraph and this is my image 
            <img src="Images/Picture.jpg" alt="Picture" /></p>       
    </form>
</body>
</html>

Find tag:
Example: image tag <img>
<img src="Images/Picture.jpg" alt="Picture" />
Please refer this article for more information

Find tag content:
Example: script tag content <script>
function SayHello() {
    alert("Hello");
}
Please refer this article for more information

How to find html tags inside rendered html in code behind - Asp.net

This script grabs all the tags specified by a tag name. Like if you need to find all the image tags inside rendered html in code behind, you may achive your goal using following script. If you are looking to find the content of a given html element please refer this article.
protected override void Render(HtmlTextWriter writer)
{
    StringBuilder sb = new StringBuilder();
    HtmlTextWriter htw = new HtmlTextWriter(new StringWriter(sb));
    base.Render(htw);
    string html = sb.ToString();
 
    string tag = "img";
 
    List<string> tags = new List<string>();
    int limit = 0, lb = 0, ub = 0;
    string startTag = string.Format("<{0}", tag);
    string endTag = string.Format(">", tag);
    string lHtml = html.ToLower();
    do
    {
        lb = lHtml.IndexOf(startTag, limit);
        if (lb > 0)
        {
            limit = ub = lHtml.IndexOf(endTag, lb) + endTag.Length;
            tags.Add(html.Substring(lb, ub - lb));
        }
        else limit = lb;
    }
    while (limit > 0);
    ///
    /// all the image tags are in tags list.
    ///
    writer.Write(html);
}

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...