Facebook

Saturday, 28 July 2012

How to Loop From A to Z in T-SQL

             How to Loop From A to Z in T-SQL


Microsoft SQL Server uses Transact-SQL (T-SQL) as its primary query language. T-SQL "WHILE" loops allow for repeating a process while incrementing a value or looking for a specific condition before exiting the loop. Looping through numeric values is a simple process; however, an alphabetic loop requires translating letters into their equivalent ASCII character codes and then using the "CHAR()" function to convert them back to letters. The ASCII codes for the uppercase letters of the alphabet are values 65 through 90.
 The lowercase alphabet is represented by values 97 through 122.




Instructions

    Open SQL Server Management Studio.

  2    Open a new query window.

  3     Declare an integer variable and set its value to 65 as shown:
         DECLARE @intCharCode INT
         SET @intCharCode = 65

  4   Type the following "WHILE" statement to output the ASCII character equivalent of the integer code       represented by the variable. The loop increments the variable by a value of 1 with each iteration until it reaches 90:

        WHILE NOT (@intCharCode > 90)
        BEGIN
        PRINT CHAR(@intCharCode)
        SET @intCharCode = @intCharCode + 1
        END

  Click the execute button to run the query. The output will print the uppercase alphabet in the results pane in alphabetic order.



Asp.net Life Cycle

                       Page Life Cycle Of Asp.Net


                                                     Asp.net Life Cycle
Introduction:-

Understanding Page lifecycle is very crucial in order to develop ASP.NET applications. Most beginners tend to get
confused while dealing with “dynamic controls” and face problems like losing values, state etc on postbacks.
Since HTTP is stateless, the nature of web programming is inherently different from windows application development,
and the Page lifecycle is one of the primary building blocks while learning ASP.NET.

Event Life Cylcle of an ASP.Net Page

Life cycle stages:-
  1. Page request
  2. Start
  3. Page initialization
  4. Load
  5. Validation
  6. Postback event handling
  7. Rendering
  8. Onload
 
Life Cycle Events:-

   1. PreInit
   2. Init
   3. InitComplete
   4. PreLoad
   5. Load
   6. Control events
   7. LoadComplete
   8. PreRender
   9. SaveStateComplete
  10. Render
  11. Unload

 1. PreInit()

In this Page Level event, all controls created during Design Time are initialized with their default values.
Syntax :
protected override void OnPreInit(EventArgs e)
{

    //custom code

    base.OnPreInit(e);
}
Note that PreInit() is the only event where we can set themes programmatically. See the diagram below showing control
hierarchy after the Page_Init() event:


2. OnInit()

In this event, we can read the controls properties (set at design time). We cannot read control values changed by the
user because that changed value will get loaded after LoadPostData() event fires. But we can access control values
 from the forms POST data as:
1    string selectedValue = Request.Form[controlID].ToString();
Syntax:
protected override void OnInit(EventArgs e)
{
    //custom code
    base.OnInit(e);
}

3. PreLoad

Use this event if you need to perform processing on your page or control before the Load event.
After the Page raises this event, it loads View State for itself and all controls, and then processes any postback
data included with the Request instance.
The PreLoad event is raised after all postback data processing and before the Load event.
protected override void OnPreLoad(EventArgs e)
{
    //custom code
    base.OnPreLoad(e);
}                                                                                                                                                                   
4. Load

This method notifies the Server Control that it should perform actions common to each HTTP request for the page
it is associated with, such as setting up a database query. At this stage in the page lifecycle, server controls in the
 hierarchy are created and initialized, view state is restored, and form controls reflect client-side data.
Use the IsPostBack property to determine whether the page is being loaded in response to a client postback, or if it is
being loaded and accessed for the first time.
Control Event Handlers
syntax:
protected void Page_Load(object sender, EventArgs e)
{
    //code here
}

5. Control Event Handlers

These are basically event handelers  (like Button1_Click()) which are defined for controls in the ASPX markup. Another
 source of confusion arises when the developer thinks that an event handler like Button_Click() should fire independently
 (like in windows apps) as soon as he clicks a Button on the web form, forgetting that Page_Load will fire first before any
 event handlers.
syntax:
void GreetingBtn_Click(Object sender, EventArgs e)
{
    //code
}

6.OnLoadComplete

The LoadComplete event occurs after all postback data and view-state data is loaded into the page and all controls on
the page. In order for view state to work for controls that are added dynamically, they must be added in or before the
 pre-render stage of the page life cycle.
syntax:
protected override void OnLoadComplete(EventArgs e)
{
    //custom code
    base.OnLoadComplete(e);
}

7. PreRender

This event is again recursively fired for each child controls in the Page. If we want to make any changes to control
values, this is the last event we have to peform the same.
protected override void OnPreRender(EventArgs e)
{
    //custom code
    base.OnPreRender(e);
}

8.SaveStateComplete

Before this event occurs, ViewState has been saved for the page and for all controls. Any changes to the page or controls
 at this point will be ignored.
Use this event perform tasks that require view state to be saved, but that do not make any changes to controls.
protected override void OnSaveStateComplete(EventArgs e)
{
    //custome code
    base.OnSaveStateComplete(e);
}

9.Render

This is not an event; instead, at this stage of processing, the Page object calls this method on each control. All ASP.NET
web server controls have a Render method that writes out the control’s markup that is sent to the browser.
Syntax:
protected override void Render(HtmlTextWriter writer)
{
    //custom code
    base.Render(writer);
}

10.Unload

This event occurs for each control and then for the page. In controls, use this event to do final cleanup for specific
controls, such as closing control-specific database connections.
protected override void OnUnload(EventArgs e)
{
    //custom code
    base.OnUnload(e);
}

Friday, 27 July 2012

Password Encryption Decryption model in Class file

--------------------------------------------------------------------------------------------------------
                                        First You Add This Code in Class File
  ------------------------------------------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace ModelName.Models
{
   public class Encryptiondecryption
   {
       public string Decode(string sData)
       {

           System.Text.UTF8Encoding encoder = new System.Text.UTF8Encoding();

           System.Text.Decoder utf8Decode = encoder.GetDecoder();

           byte[] todecode_byte = Convert.FromBase64String(sData);

           int charCount = utf8Decode.GetCharCount(todecode_byte, 0, todecode_byte.Length);

           char[] decoded_char = new char[charCount];

           utf8Decode.GetChars(todecode_byte, 0, todecode_byte.Length, decoded_char, 0);

           string result = new String(decoded_char);

           return result;

       }
       public string Encode(string sData)
       {
           try
           {
               byte[] encData_byte = new byte[sData.Length];

               encData_byte = System.Text.Encoding.UTF8.GetBytes(sData);

               string encodedData = Convert.ToBase64String(encData_byte);

               return encodedData;

           }
           catch (Exception ex)
           {
               throw new Exception("Error in base64Encode" + ex.Message);
           }
       }
   }
}

 -----------------------------------------------------------------------------------------------------------
                                        Then go to the  Admin Controlller Apply This Code
                                     Firstly Set The TextBox Name and Etc another Names
 -----------------------------------------------------------------------------------------------------------

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Models Name;
namespace Controller Name
{
   public class AdminController : Controller
   {
       //
       // GET: /Admin/

       public ActionResult Index()
       {
           return View();
       }
      
       public ActionResult Login()
       {
               return View();

       }
       [HttpPost]
       public ActionResult Http_login(string username, string password)
       {
        
    
           YourEntityName ObjEntity = new YourEntityName();
           var Admindata = (from p in ObjEntity.tbl_User where p.username == username select p).SingleOrDefault();
                      if (Admindata!= null)
           {
               Encryptiondecryption Obj_Encryptiondecryption = new Encryptiondecryption();
               string decdrypt_password = Obj_Encryptiondecryption.Decode(Admindata.password);
               if (decdrypt_password == password)
               {
                   Session["User"] = Admindata.username;

                 return RedirectToAction("Index", "ShareYourStory");
               }
               else
               {                  
                   ModelState.AddModelError("Msgpsd", "Wrong Password!");
                    return View("Login");
               }
           }
           else
           {
               
               ModelState.AddModelError("Msgusr", "Wrong Usename!");  
                 return View("Login");
           }
       }

       // Change Password of admin
       public ActionResult Change_Password()
       {
           if (Session["User"] == null)
           {
               return RedirectToAction("Login", "Admin");
           }
           else
           {

               if (TempData["success"] == null)
               {
                   TempData["success"] = "";
                   return View();
               }
               else
               {
                   return View();
               }
               
           }
       }

       // Change Password of admin Http_Post

       [HttpPost]
       public ActionResult Http_ChangePassword( string txt_cnf_new_password, string txt_old_password)
       {
           EntityName obj_YourEntities = new EntityNameEntities();
         string  username = Session["user"].ToString();
           var admindata = (from data in obj_YourEntities.tbl_User where data.username ==username  select data).SingleOrDefault();
           if (admindata != null)
           {
               Encryptiondecryption Objencryptcls = new Encryptiondecryption();
            string   encrypt_old_password=Objencryptcls.Decode(admindata.password);
            if (encrypt_old_password == txt_old_password)
               {
                    YourEntityName obj_YourEntities1 = newYourEntityName();
                   tbl_User objUser = new tbl_User();
                   //Encryptiondecryption Objencryptcls = new Encryptiondecryption();
                   string encrypt_pass = Objencryptcls.Encode(txt_cnf_new_password);
                   objUser.password = encrypt_pass;
                   objUser.username = username;
                   objUser.userid = 1;
                   obj_YourEntities1.tbl_User.Attach(objUser);
                   obj_YourEntities1.ObjectStateManager.ChangeObjectState(objUser, System.Data.EntityState.Modified);
                   obj_YourEntities1.SaveChanges();
                   TempData["success"] = "Password changed successfully";
                     
                    return View("Change_Password");
               }
               else
               {
                   ModelState.AddModelError("Msgpsd", "Wrong Password!");
                   return View("Change_Password");
                   
               }
           }
           else
           {
               ModelState.AddModelError("Msgusr", "Wrong Usename!");  
              return View("Change_Password");
           }
       }
       // action for logoff admin
       [HttpPost]
       public ActionResult logoff()
       {
           Session["User"] = null;
           return RedirectToAction("Login", "Admin");
       }
   }

}

Save Controller

[HttpPost]
           public ActionResult EmailSubcribe_Action(string txt_emailsubscribe)
           {
               EntityName obj_EmailSubscribe = new EntityName();
               if (txt_emailsubscribe != null)
               {
                   tbl_EmailSubscriber objsubscribe = new tbl_EmailSubscriber();
                   objsubscribe.Email_Subscribe = txt_emailsubscribe;
                   EntityName obj = new EntityName();
                   obj.tbl_EmailSubscriber.AddObject(objsubscribe);
                   obj.SaveChanges();
                   return RedirectToAction("Index", "Home");
               }
               else
               {
                   return RedirectToAction("Index", "Home");
               }

Mvc 3 Grid View With Check Box and delete button



    @model ModelName.EmailModel

@{
   var grid = new WebGrid(source: Model.getemail, rowsPerPage: 10, canPage: true, canSort: true);
}


@using (Html.BeginForm())
{
<div class="inner_div">
@grid.GetHtml(tableStyle: "grid", alternatingRowStyle: "alter_row", columns: grid.Columns(grid.Column("Email_Subscribe", "User Subscribe Email ID"), grid.Column(header:"Select All",format: @<text><input name="chkID" type="checkbox" value="@item.Email_Subscribe" /></text>), grid.Column(format: (item) => Html.ActionLink("Delete", "DeleteEmail", new { Email_ID = item.Email_ID }))))<br />
</div>    
@Html.EditorFor(model => model.message)<br />
<input type="submit" value="Send" />    <br /><br />
}
@using (Html.BeginForm("Email_FileUpload", "EmailSubscriber", FormMethod.Post, new { enctype = "multipart/form-data" }))
   {
   <input type="file" name="file" />
   <input type="submit" value="OK" />
   }
<script type="text/javascript">
   $(function () {
       addCheck();
   });
   function addCheck() {
       var $chk = $('<input/>').attr({ type: 'CheckBox', name: 'chkAll', id: 'chkAll', title: "Select All" });
       $('th:last').append($chk);
       $('#chkAll').click(function () {
           $(':checkbox').attr('checked', $(this).is(':checked') ? 'checked' : '');
       });
   }
</script>

JavaScript Images Not Copy


<body ondragstart="return false" onselectstart="return false">   



 <script type = "text/javascript">
   var message = "Function Disabled!";
   function clickIE4() {
       if (event.button == 2) {
            return false;
       }
   }
   function clickNS4(e) {
       if (document.layers
          || document.getElementById && !document.all) {
           if (e.which == 2 || e.which == 3) {
                return false;
           }
       }
   }
   if (document.layers) {
       document.captureEvents(Event.MOUSEDOWN);
       document.onmousedown = clickNS4;
   }
   else if (document.all && !document.getElementById) {
       document.onmousedown = clickIE4;
   }
   document.oncontextmenu = new Function("return false")
       </script>

Script On Button Click

protected void btnScript_Click(object sender, EventArgs e)
       {
           if (txtdata.Text != "")
           {
               const string script = "alert('You have e')";
               ClientScript.RegisterClientScriptBlock(GetType(), "alert", script, true);
           }
           else
           {
               const string script = "alert('Please enter some data')";
               ClientScript.RegisterClientScriptBlock(GetType(), "alert", script, true);
           }
       }