Sunday, December 9, 2012

How to delete/select absolutely all mail/message in a GMAIL label.

Few months ago I have subscribed at www.forums.asp.net site as it is a great place for DOTNET troubleshooting. Every day more than 100 mails are storing in my mail box. Varieties types of questions, suggestions etc are posting at that site. Great....

Last day I was swiping my Gmail. There was many spam, many junked mail. Suddenly I have noticed that in the "ASP.NET Forum" label I have got almost 90,000 mail message and I allocate 1GB of 10GB storage of GMAIL!!!

 I started deleting and after some minutes I realized that it is very time consuming job to delete 90,000 mails. When I select all mails then it only selects 100 mails of current page. After delete 100 mails then select again 100 mails and delete......

At last I have find a solution.

Step 1: First Select all mail of current page.
Step 2: Then select Select all XXX conversations in "LABEL" from the middle-top of mail list. 
Step 3: Then press delete. 


That's all....


Sunday, December 2, 2012

My CHM file does not display its content!!!

After opening a CHM formatted file sometimes we see this message "This Program cannot display the webpage" instead of the content. 


The program cannot display the webpage


This problem is so common. and the solution is also simple.


Just remove the # or & or ? or +  character from the chm file name and/or folder and/or directory name. Because these characters have special meaning.


like:

if my chm file name is "c# book" then replace # character with other or remove # character.
again, if my chm file is in "F:/ASP and C#" directory then also replace # character with other or remove # character.



Happy Reading........



Wednesday, October 31, 2012

AppendLine method of StringBuilder class object doesn't work.

In ASP.NET AppendLine method of a StringBuilder class object does not put a new line if I show the result in asp:label control.

Here is the code snippet that I have tried - 



aspx page:-



<form id="form1" runat="server">
    <div>
        <asp:Label ID="lblResult" runat="server">          </asp:Label>
    </div>
</form>

cs code:-



protected void Page_Load(object sender, EventArgs e)
    {

        StringBuilder output = new StringBuilder();

        string[] str = { "AB", "BC", "CD", "DE" };
        foreach (string s in str)
        {
            output.AppendLine(s);
        }
        lblResult.Text = output.ToString();

    }

Output:-

AB BC CD DE


I have tried Environment.NewLine also. but failed.


At last I have found the solution: <br/> - as HTML respects this tag only. neither \n nor \r\n



So, after correction the code

            output.Append(s + "<br/>");

I have got my desired Output:

AB
BC
CD
DE

Thursday, September 27, 2012

Wednesday, September 19, 2012

Get Inner most exception


Lets consider a simple example.

We have a static void Main() method which is the entry point of our application.
From static void Main() we call a method named AMethod()
And AMethod() intern calling an another method AMethod1().
Now lets say AMethod1() unfortunately raises an exception which is sent to AMethod() and same is propagated to Main() function.





Look at the following line of code.


class Program
{
static void Main(string[] args)
{
try
{
AMethod();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message.ToString());
}
}

private static void AMethod()
{
try
{
AMethod1();
}
catch (Exception ex)
{
throw new Exception("A Method", ex);
}
}

private static void AMethod1()
{
throw new Exception("Exception from A Method 1.");
}
}


Now, what will happen if you run the code? You will see that the output is "A Method"
Which is the exception message of AMethod() – which is not original error message. But as a developer our expected message is "Exception from A Method 1." Of AMethod1() – which is disguised by AMethod().

To avoid this situation the solution is GetBaseException() method which belongs to the Exception class and “returns the System.Exception that is the root cause of one or more subsequent exceptions.” – means the error from the main source which will not be omitted by another method.



class Program
{
static void Main(string[] args)
{
try
{
AMethod();
}
catch (Exception ex)
{
Console.WriteLine(ex.GetBaseException().Message.ToString());
}
}

private static void AMethod()
{
try
{
AMethod1();
}
catch (Exception ex)
{
throw new Exception("A Method", ex);
}
}

private static void AMethod1()
{
throw new Exception("Exception from A Method 1.");
}
}

Monday, June 4, 2012

How to configure a link to open/download documents in a website using ASP.NET and C#?

Sometimes we need to give/configure a link in our website to open and/or download facility of various types of documents like Microsoft documents(word, excel, power-point file), PDF file etc.

Here I will discuss 3 ways to open documents in a website and/or download a document from a website using ASP.NET and C#.

1. open document using iframe.
2. open document using HTTPResponse.
3. open document using Google doc viewer.


1. Open document using iframe.


    Inline frame or iframe is a window cut into your webpage that allows you to view another page on your site. It gives you the flexibility to render a specific portion without reloading entire page.


    ok. using this iframe you can view a document file including word, excel, power-point, pdf, text file and many more. One thing you need to remember that you must have document reader, installed at your client PC to open and read the document.


lets see how we can achieve this.

I assume that there is a folder FileStore at your website which holds all the document files.

1. add a new page.

2. at aspx page add an iframe.

        <iframe id="iframShowFiles" runat="server" height="600" width="800" frameborder="0">

        </iframe>

3. at cs page add the following code at page load event-


string fileName = Request.QueryString["FileName"] != null ? Request.QueryString["FileName"].ToString() : string.Empty;

        string surverUrl = Request.Url.AbsoluteUri.Split('/')[0] + "//" + Request.Url.Authority + Request.ApplicationPath.TrimEnd('/') + "/";
        string fileStoreLocation = "FileStore/";
        string downloadFilePath = surverUrl + fileStoreLocation + fileName;

        iframShowFiles.Attributes.Add("src", downloadFilePath);



now at the target aspx page add a link -


<a target="_blank" href="Default.aspx?FileName=Project-Food.xlsx">View file using iframe</a>


now tun the site.




2. Open document using HTTPResponse.


follow the following instruction:


1. In target aspx page add a hyperlink -


<asp:HyperLink ID="hypDownloadMyFile" runat="server" Text="View file using HTTPResponse"

            NavigateUrl=""></asp:HyperLink>

2. at cs page write the following code at page load event -


        string fileName = "Project-Food.xlsx";

     
        #region Download file using HTTpResponse

        hypDownloadMyFile.Attributes.Add("onclick", "javascript:DownloadFile();");

        hypDownloadMyFile.Attributes.Add("onmouseover", "this.style.cursor='pointer';this.style.color='red';");
        hypDownloadMyFile.Attributes.Add("onmouseout", "this.style.color='';");
        if (!Page.IsPostBack)
        {
            bool isDownloadFile = false;
            if (Request.QueryString["DownloadFile"] != null && Request.QueryString["DownloadFile"] == "1")
                isDownloadFile = true;

            if (isDownloadFile)

            {
                DownloadMyFile(fileName);
            }
        }

        #endregion



and this is DownloadMyFile method -



 private void DownloadMyFile(string fileName)

    {
        string fileStoreLocation = "~/FileStore/";
        string physicalPath = Server.MapPath(fileStoreLocation);
        string filePath = physicalPath + fileName;
        if (System.IO.File.Exists(filePath))
        {
            Response.ContentType = "application/octet-stream";
            Response.AppendHeader("Content-Disposition", "attachment; filename=" + fileName);
            Response.WriteFile(filePath);
            Response.End();
        }
    }


now run the site.





3. Open document using Google doc viewer.


   This is very interesting thing. Google introduces this document viewer. You do not need any document reader installed at client pc to open and read the document. The supported file types are:

  • Microsoft Word (.DOC and .DOCX)
  • Microsoft Excel (.XLS and .XLSX)
  • Microsoft PowerPoint (.PPT and .PPTX)
  • Adobe Portable Document Format (.PDF)
  • Apple Pages (.PAGES)
  • Adobe Illustrator (.AI)
  • Adobe Photoshop (.PSD)
  • Tagged Image File Format (.TIFF)
  • Autodesk AutoCad (.DXF)
  • Scalable Vector Graphics (.SVG)
  • PostScript (.EPS, .PS)
  • TrueType (.TTF)
  • XML Paper Specification (.XPS)
  • Archive file types (.ZIP and .RAR)
as per google Technical Documentation - Instructions for building your own URLs

All viewer URLs should use the path http://docs.google.com/viewer .

This path accepts two parameters:
1. url : The URL of the document to view. This should be URL-encoded.
2. embedded : If set to true , the viewer will use an embedded mode interface.

For example, if you wanted to view the PDF at the URL http://research.google.com/archive/bigtable-osdi06.pdf , you would use the URL:


http://docs.google.com/viewer?url=http%3A%2F%2Fresearch.google.com%2Farchive%2Fbigtable-osdi06.pdf


lets use a real life example:


1. Add a hyperlink into your target aspx page -


<asp:HyperLink ID="hypViewFileUsingGoogleDoc" runat="server" Text="View file using Google Doc"

            Target="_blank"></asp:HyperLink>

2. add the following code at cs page at page load event -


 #region Download file using Google Doc

   
        hypViewFileUsingGoogleDoc.Attributes.Add("onmouseover", "this.style.cursor='pointer';this.style.color='red';");
        hypViewFileUsingGoogleDoc.Attributes.Add("onmouseout", "this.style.color='';");
        string surverUrl = Request.Url.AbsoluteUri.Split('/')[0] + "//" + Request.Url.Authority + Request.ApplicationPath.TrimEnd('/') + "/";
        string fileStoreLocation = "FileStore/";
        string downloadFilePath = surverUrl + fileStoreLocation + fileName;
        hypViewFileUsingGoogleDoc.NavigateUrl = "http://docs.google.com/viewer?url=" + downloadFilePath;

        #endregion


now run the site.


If you found a screen like this -





Do not worry about this. Google cannot format and display the document from private file storage that are behind a firewall or on a local site that is accessed with a 'localhost' address.


Click on red font 'here' text. the document will download.


You can discover many more from the Google doc viewer.




That's all for now. Happy programming.. :)



Saturday, June 2, 2012

Create expandable post with a link "Read More" in your blogger post?

When we write a post, generally the google blogger shows the full-length blog at home page. The result is, the blog home page grows as long as the total length of all displayed blog. By using 'After the jump' feature we can show only the blog summary.

I have found it very useful guide from google blogger guide.

Here is the link: Create expandable post

Friday, June 1, 2012

How to remove Home link at the bottom of blogger main page?


F

ollow the steps to remove the Home link at the bottom of your blogger main page.


Step 1: From Dashboard > Template > Edit HTML.


Click "Proceed" button.

Step 2: at code editor check "Expand Widget Templates".

Step 3: Then copy the code and paste in a notepad.
Then Find and Remove <a class='home-link' expr:href='data:blog.homepageUrl'><data:homeMsg/></a>





your can also comment the line so that reuse later.





Thats all. now replace the existing blogger code with new modified code. Save the template and see preview. Happy blogging. :-)






Thursday, May 31, 2012

What is the query processing order at SQL Server?

Does SQL Server execute the query from top to bottom, starting with the SELECT clause and working its way down? You might think that, but that is not how a query is processed in SQL Server at all. SQL Server logically processes a query in the following order:


(8) SELECT
(9) TOP
(1) FROM
(3) JOIN
(2) ON
(4) WHERE
(5) GROUP BY
(6) WITH
(7) HAVING
(10) ORDER BY

:-)




I collect this information from book Wrox Professional LINQ

How to write an extension method?

Introduction:-

In C# 1.0 - the methods were belonging to a class. That means the methods were defined within the body of the class. C# v2.0 introducing partial classes - the methods making up a class could be defined in more than one place. At compile time they are all collected together. Extension methods are new to C# v3. Extension methods are a powerful new language feature that ensures the code abstraction and increase the code re usability.


How to define extension method?


as per msdn

1. Define a static class with appropriate access modifier.
2. Implement the extension method as a static method with at least same visibility of the containing class.
3. The first parameter of the method specifies the type that the method operates on. It must be preceded with the 'this' modifier.


How to call the extension method?


as per msdn

1. In the calling code, add a using directive to specify the namespace that contains the extension method class.
2. Call the method as if they were instance methods on the type. You do not need to specify the first parameter because it represents the type on which the operator is being applied, and the compiler already knows the type of your object. You only have to provide arguments for parameters 2 through n.


So, extension methods are defined as static methods but are called by using instance method syntax. There first parameter specifies which type the method operates on, and the parameter is preceded by the this modifier. Extension methods are only in scope when you explicitly import the namespace into your source code with using directive.



Example


At first create a new website at Visual Studio 2010.





at New Web Site popup screen

1. Select Visual C# from left side - in which language you want to write code
2. Select ASP.NET Empty Web Site - we will add pages later
3. Then select file location. I rename the website name Website1 to ExamineExtensionMethod.
Then Click Ok.




After clicking Ok the file structure in Solution Explorer tab will be shown like below.





Then add a Class file named MyExtensions and a Web Form





At MyExtensions class remove all code and write the following code-


using System;


namespace CustomExtension

{


public static class MyExtensions
{


public static int WordCount(this string str)
{
return str.Split(new char[] { ' ', '-', '_', ',' }, StringSplitOptions.RemoveEmptyEntries).Length;
}


}

}


Here the important things are namespace, public static class and public static method declaration.





Then at aspx file add a label control.





Then code behind page file

1. add the namespace first
2. then calculate word count of a string.





Thats all.


You need to remember 2 things if you implement extension methods-

1. If you have an extension method and the class(in which your extension method is using) itself implements a method with same name and signature, your extension method will never call.
2. Extension methods are brought into scope at the namespace level.




I would like to name one - Jonathan Worthington from whom I encouraged to write this blog for beginners.