Monday, 26 March 2012

Return user in same position on page after postback event in asp.net ?


When Web pages are posted back to the server, the user is returned to the top of the page. On long Web pages, this means that the user has to scroll the page back to the last position on the page.
When the MaintainScrollPositionOnPostback() property is set to true, the user is instead returned to the last position on the page.

<%@ Page Language="C#" AutoEventWireup="true" MaintainScrollPositionOnPostback="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

Note:
In ASP.NET version 2.0, the SmartNavigation property is deprecated. Use the SetFocus method and the MaintainScrollPositionOnPostback() property instead. i.e in the code behind use the set focus property of the control after the post back.

How to lock Your private folder without using any software.


  • First select Your folder which you want to lock. Suppose paint is my private folder and it stored into E:\ drive.
  • In the same drive ( e.g. E:\) you need to create two bat file. Create a new text file there & Open it in note pad. Type in:

    Quote:
    ren paint paint.{21EC2020-3AEA-1069-A2DD-08002B30309D}
    Save it in as lock.bat
  • Again open another text file and type
    Quote:
    ren paint.{21EC2020-3AEA-1069-A2DD-08002B30309D} paint
    Now save this as a unlock.bat .

Now you can see 2 batch files lock and unlock.Double click on Press lock.bat and the folder paint's icon will change to control panel and you cannot view its contents.

Double click on unlock.bat and you will get back your original folder.

Creating A WaterMark TextBox

Some times it requires a watermark  or a faded text to be placed in the text-box with default text on it.
We can design such using JQuery.you can use even a simple HTML controls to for this one. Here is the Code below:

·         
  WaterMark TextBox:
var swap = [];
              $(".waterMark").each(function (i) {

                swap[i] = $(this).val();

                $(this).focus(function () {
                    if ($(this).val() == swap[i])
                        $(this).val("").removeClass("waterMark");

                })
                .blur(function () {
if ($.trim($(this).val()) == "")
                        $(this).val(swap[i]).addClass("waterMark");
                })


            });
Mark Up:
<asp:textbox cssClass="waterMark" id="tbName" text="Your Name goes here..." runat="server"/>

Enjoy.........!

Wednesday, 21 March 2012

How to Access the Windows Registry from C#?

Sometimes it may require to develop a application which can able to retrive the information from the Registry.
This can be done using the Registry class and RegisteryKey class. Here is a small Application to get a bit knowledge about it.


By using the Registry and RegistryKey classes in Microsoft.Win32, one can easily access the registry.
The following is a sample that reads a key and displays its value:
using System;
using Microsoft.Win32;
class regTest
{
public static void Main(String[] args)
{
RegistryKey regKey;
Object value;
regKey = Registry.LocalMachine;
regKey =
regKey.OpenSubKey("HARDWAREDESCRIPTIONSystemCentralProcessor ");
value = regKey.GetValue("VendorIdentifier");
Console.WriteLine("The central processor of this machine is: {0}.", value);
}
}

Tuesday, 20 March 2012

ITextSharp Showing Image in the PDF using Http.Context.Current.Server.Mapath showing Error.

You will find that the application in which you had used ITextSharp is working fine in local machine,  but when you put it into the production Environment it might be showing that the Image path cannot be found or unable to access the Image path in the current context. This is due to the restriction by your Server, So in order to make it work properly just do it as given below: 


 string imagePath = HttpContext.Current.Server.MapPath("~/Styles/Images/etv-logo.png");
        iTextSharp.text.Image headerImage =
            iTextSharp.text.Image.GetInstance(new FileStream(imagePath, FileMode.OpenOrCreate));
 
Hopes it will help you, Enjoy.... 

How to set master page file at run time

When you are developing a web site using Master and Content page model, you have noticed that after creating your Master page in the web application when you use Wizard to add Content page, it asks you to pick the master page that you would like to associate with this page. And if you choose the option of not selecting a master page, then wizard gives you a standard web form. Then you will have to manually delete markup for body, header etc. to convet it to a content page.
If you do pick the option of selecting a master page, then your content page's declaration at the top looks like the following snippet.

<%@ Page Title="" Language="C#" 
MasterPageFile="~/Themes/Default/ByteBlocks.master" 
AutoEventWireup="true" 
CodeFile="Default.aspx.cs" 
Inherits="_Default" %>

Notice use of MasterPageFile attribute that specifies what master page this content page is associated with. What if you want to switch your master page at run time based on some configuration settings or some use choice. Does this mean you will have to find a way to modify your ASPX file to do. No there is a easier solution to it.
For example in my project I added a drop down in master page to change the theme on the fly. And then PreInit event handler of the page, I set MasterPageFile property of the page object. This is the same attribute that was set at top of the page when we added content page using wizard.

protected override void OnPreInit(EventArgs e)
{
if (Session["theme"] != null)
{
MasterPageFile = 
string.Format("~/Themes/{0}/ByteBlocks.master", Session["theme"]);
}
base.OnPreInit(e);
}

It is very important that you set MasterPageFile property in or before PreInit step of life of ASPX page. Otherwise applicaiton will throw run time exception.
System.InvalidOperationException: The 'MasterPageFile' property can only be set in or before the 'Page_PreInit' event.

Creating PDF Using ITextSharp showing System.Security.Permissions.EnvironmentPermission, mscorlib, Version = 1.0.50000.0, Culture = neutral, publicKeyToken = [number] failed error.


Sometimes when you are using ITextSharp for creating PDF's might throw the error in the production environment that System.Security.Permissions.EnvironmentPermission, mscorlib, Version = 1.0.50000.0, Culture = neutral, publicKeyToken = [number] failed error. This is because the ITextSharp doesn't work on minimum security level, so in order to work just download the ITextSharp all source code(Here is the Link: ITextSharp )
Now extract it and open it in your Visual Studio 20008/2010.
Open Assemplyinfo.cs and Add this line: [assembly: AllowPartiallyTrustedCallers()]
Save it and Build the Solution, Go to the \itextsharp-src-core-5.2.0\bin\Debug folder and copy the itextharp.dll and the Xml file to your production Environment.

Enjoy....

Friday, 16 March 2012

Sorting a List of Objects on a particular field.

   public static List<Participant> SortedObjects(IEnumerable<Participant> myList) {
     SortedList<string,Participant> sortedList = new SortedListstringParticipant>();
     foreach (Participant participant in myList) {
         sortedList.Add(participant.RegistrationNo, participant);
     }
     return new List<Participant>(sortedList.Values);
  }

Monday, 12 March 2012

FIND Nth Maximum value and Nth minimum Value from a colum in a table in MS-Sql Server.

 FIND Nth Maximum value 
SELECT id, amount
FROM(SELECT id, amount, Row_Number() OVER(ORDER BY amount DESC) AS highest
FROM @tmp
) as x
WHERE highest = 3

-- FIND Nth Minimum value 
SELECT id, amount
FROM(SELECT id, amount, Row_Number() OVER(ORDER BY amount ASC) AS lowest
FROM @tmp


) as x
WHERE lowest = 3

Create a Drop Shadow around Form

public partial class MyCustomForm : Form
{
private static Int32 CS_DROPSHADOW = 0x00020000;

protected override CreateParams CreateParams
{
get
{
CreateParams parameters = base.CreateParams;
parameters.ClassStyle |= CS_DROPSHADOW;

return parameters;
}
}
}