Thursday, 15 December 2011

Disable Right Click on your browser using JavaScript or Jquery or making onconextmenu false in body tag.

Sometimes you want to disable the right click on your browser to
protect your source code to be viewed by some one.

To do this you can use Javascript or JQuery:

JavaScript Code:  Put this code in between the Script tag as:
<script>

var message="Sorry, Right Click is disabled.";
   //To disable the right click on the page
    function click(e)
    {
        if (document.all)
         {
            if (event.button == 2)
            {
            alert(message);
            return false;
            }
         }
        if (document.layers)
         {
            if (e.which == 3)
            {
            alert(message);
            return false;
            }
         }
    }
    if (document.layers)
    {
        document.captureEvents(Event.MOUSEDOWN);
    }
    document.onmousedown=click;

</script>

JQuery Code:  Put this code in between the Script tag as:
<script>
   $(document).ready(function(){
    $(document).bind("contextmenu",function(e){
return false;
    });
});
</script>

OR
<script type="text/javascript>
document.oncontextmenu=new Function("return false");
</script> 

OR

<html>
<head>
<title>Disable Right Click using jQuery</title>
<script type="text/javascript" src="jquery-1.6.2.js"></script>
<script type="text/javascript">
$(function() {
     $(this).bind("contextmenu", function(e) {
         e.preventDefault();
     });
}); 
</script>
</head>
<body>
Disable Right Click event using jQuery
</body>
</html>

Using OnContextMenu in Body Tag: 
The Simplest one:
<body oncontextmenu="return false;">




 

"The proxy server is refusing connections"

Got to Internet settings/Internet Options in control panel.
Then connections, then LAN. turn OFF any reference to proxies, configuration files or similar.

Now your system will work fine.

Tuesday, 13 December 2011

Passing Values between the Pages in Asp.net

You can pass values from one page to another using Request.Params collection which returns collection of Form elements, Cookies, Server Variables and QueryString.

Home.aspx page:
private void Submit_Click(object sender, System.EventArgs e)
  {     
   System.Collections.Specialized.NameValueCollection myCol = Request.Params; 

   string userName = Request.Params.Get("tbUserName");
   
   Server.Transfer("Registration.aspx"); 
  }

And the Registration.aspx which will receive the values looks something like this:
private void Page_Load(object sender, System.EventArgs e)
  {
     if(Request.Params.Get("txtUserName") != null) 
     {
       string userName = Request.Params.Get("tbUserName"); 
       Response.Write(userName); 
     }
  } 
Note: Use Server.Transfer for redirecting to the next page otherwise the ControlList 
values of the 1st page will be lost.

How to get the Value of a ReadOnly Asp:TextBox in the Code Behind.

The above one you can do it in 2 ways:

1. Create a hidden field and bind the value to it using Jquery and access that in C#.

2. The Second Method is simply adding a Read Only attribute to the Text Box
in the Code behind during !IsPostback in the page Load Event.

 See the Example:--
In the aspx file: 
 <asp:TextBox ID="txtCheckin" runat="server"></asp:TextBox>

In the Code behind(C#):
protected void Page_Load(object sender, EventArgs e)
{ 
   if (!IsPostBack)
   {
      txtCheckin.Attributes.Add("readonly""readonly");
}
}
 
Now you can access the value of the txtCheckin with ReadOnly. 
 
Note: Don't Write ReadOnly="True" in the asp:TextBox Tag.

Binding the Data To a Asp:dropdownlist using ajax in Entity FrameWork and On button click Accessing the Value in Code Behind.

OR

Accessing a HTML Control in C#.


Aspx file:

<table width="95%" border="0" class="planYourStay" cellpadding="0" cellspacing="0">
<tr>
<td width="50%" height="30" valign="top">
<span class="label16">State</span><br />
<asp:DropDownList ID="drpState" runat="server">
<asp:ListItem Value="0">--Select--</asp:ListItem>
</asp:DropDownList>
<asp:RequiredFieldValidator ID="rfvdrpState" runat="server" ControlToValidate="drpState"
 Text="*" CssClass="errormsg" ValidationGroup="step1" InitialValue="0">
</asp:RequiredFieldValidator> 
</td>
<td width="45%" valign="top">
<span class="label16">City</span><br />
<asp:DropDownList ID="drpCity" runat="server">
<asp:ListItem Value="0" runat="server">--Select--</asp:ListItem>
</asp:DropDownList>
<asp:RequiredFieldValidator ID="rfcdrpCity"   runat="server" ControlToValidate="drpCity"
Text="*" CssClass="errormsg" ValidationGroup="step1" InitialValue="0">
</asp:RequiredFieldValidator> 
</td>
</tr>
</table>
 <asp:ImageButton ID="imgbtnStep2" runat="server" ImageUrl="images/step2-but.gif"
OnClick="imgbtnStep2_Click"  ValidationGroup="step1" /> 
 
Jquery File: 
$(document).ready(function () {
          $("#<%=drpState.ClientID %>").change(function () {
              var $cities = $('#<%=drpCity.ClientID %>');
             $.ajax({
                 type: "POST",
                 url: "Default.aspx/GetCities",
                 contentType: "application/json; charset=utf-8",
                 data: '{stateId: ' + $('#<%=drpState.ClientID%>').val() + '}',
                 dataType: "json",
                 success: function (cities) {
                     $.each(JSON.parse(cities.d), function (i, city) {
                         $cities.append('<option value="' + city.CityID + '">' + 
city.Name + '</option>');
                     });
                 },
                 error: function () {
                     alert('Failed to retrieve states.');
                 }
             });
         });
     }); 
C# web service(Ajax Method): 
[System.Web.Services.WebMethod]
       public static string GetCities(string stateId)
        {
            if (Convert.ToInt32(stateId) == 0)
            {
                return null;
            }
           var result = Common.GetCities().Where(res => res.StateID == 
                                       Convert.ToInt32(stateId)).ToArray();
           var City2 = new {CityID=0, Name=string.Empty};
           var cityList = new[] {City2}.ToList();
            foreach (var city in result)
            {
                cityList.Add(new{CityID=city.CityId,Name=city.City1});
            }
            cityList.RemoveAt(0);
            return new JavaScriptSerializer().Serialize(cityList);
        }
 
Image Button click event: 
 protected void imgbtnStep2_Click(object sender, ImageClickEventArgs e)
        {
            string selectedValue = Request.Params.Get(drpCity.UniqueID); 
// OR string selectedValue = Request.Form.Get(drpCity.UniqueID); 
// Request.Form and request.Params are used for accessing the 
// client side controls in Code behind
            TempData tempData = new TempData()
                                    {
                                        City = selectedValue,
                                      State=drpState.SelectedValue,
                                       Week=drpWeekInterval.SelectedValue,
                                       Package=GetPackage(),
                                       CheckInDate = txtCheckin.Text.Trim()
                                    };
            Session["TempData"] = tempData;
            Response.Redirect("~/Registration.aspx");
        }
 
 

Wednesday, 7 December 2011

Fixing the Database Restore When You get error no. 3154 in MS Sql Server 2008 /2008 R2

In Ms SQL Server 2008/ 2008 R2, some times you get an Error no. 3154 that  database  cannot be restored from the .bak file. To Fix it Follow the procedure:--

1. Use the Current Db as Master. i.e. Use master;
2. Now delete your old database which in not restoring, Say [dbo].[Quizzana ]
3. Create a new Database of the Same name after deleting it.
        CREATE DATABASE Quizzana;
4. Now click on the New Query and write the following command:
   Use Master;
     RESTORE DATABASE Quizzana
  
FROM DISK = 'C:\Quizzana.bak'
  
WITH REPLACE

Note: 
1. Here Disk="c:\Quizzana.bak" is the path where the .bak file is present.
2. Use the current database as master while executing the Query otherwise it will show an error that   the database session is in use.