Showing posts with label Concepts. Show all posts
Showing posts with label Concepts. Show all posts

Sunday, July 18, 2010

Sample Coding

1.To clear history and disabled back button

Response.Cache.SetCacheability(HttpCacheability.NoCache);

Response.Cache.SetAllowResponseInBrowserHistory(false);
Javascript
<body onload="history.go(1);">
2.how to get previuos page value from another page?

In Button property set PostbackURL - redirect page URL

in redirected page access

   
TextBox txt = (TextBox)Page.PreviousPage.FindControl("TextBox1");
    txt.Text;

3.  To Set the screen based on resolution
function onLoad()

{

window.resizeTo(screen.availWidth,screen.availHeight);

}

call the above function on body tag

ex.. <body onload="javascript:onLoad()">

automatically the browser will be maximized based on your resolution


4. window.opener.document.location.reload(); // Parent window refresh

5. window.document.location.reload(); // current window refresh

6. how to reset Form?
   
<input type="button" value="Reset Form" onClick="this.form.reset()" />
7.  To display message box from coding

ScriptManager.RegisterClientScriptBlock(this, GetType(), "Success", "window.setTimeout(\"alert('Record(s) successfully updated.');\",0);", true);
To display message from server side to invoke the client side script

8. window.close(); // current close command

     if it doesn't works in firefox browser
     please set your firefox browser:

1.input "about:config " to your firefox address bar and enter;
2.make sure your "dom.allow_scripts_to_close_windows" is true
9. how to pass value from2 to form1
public partial class Form1 : Form
{
    public Form1()

{

InitializeComponent();

}



private void button1_Click(object sender, EventArgs e)

{


Form2 frm = new Form2(this);

frm.Show();

}

}



public partial class Form2 : Form

{

Form _frm;

public Form2(Form frm)

{

_frm=frm;

InitializeComponent();

}



private void button1_Click(object sender, EventArgs e)

{

Form1 objMain = (Form1)_frm ;

objMain.textBox1.Text = "Hello";

}

}



10.decoration = none // to display is none , instead of hidden

11. how to set first letter should be capital letters

          string test = "Test StRiNg";
          string formatted = System.Globalization.CultureInfo.CurrentUICulture.TextInfo.ToTitleCase(test);

12 . Read Grid Values using Javascript
               <script type="text/javascript">
function showdata()
{
     var gridViewCtlId = '<%=GridView1.ClientID%>';
     var grid = document.getElementById(gridViewCtlId);
    var gridLength = grid.rows.length;
    for (var i = 1; i < gridLength; i++)
   {
      var cols= grid.rows[i].cells.length
      for(var j=0; j < cols; j++)
     {
       cell=grid.rows[i].cells[j];
       alert(cell.innerText);
     }
    }
}
</script>
13. How to maintain cusor positon
       page directive MaintainScrollPositionOnPostback

14. onfocus select the entire text
       <asp:TextBox ID="TextBox1" runat="server" Text="1" onfocus="this.select();"></asp:TextBox>

15 . Set Transparent of a image
<asp:ImageButton style="filter:alpha(opacity=10)" ID="ImageButton1" runat="server" AlternateText="Search" ImageUrl="~/Images/calendar.gif" />
16.  Add zeroes before number
String.Format("{0:00000}", 15); // "00015"
String.Format("{0:00000}", -15); // "-00015"
Align number to the right or left
string.Format("{0,5}", 15); // " 15"
String.Format("{0,-5}", 15); // "15 "
String.Format("{0,5:000}", 15); // " 015"
String.Format("{0,-5:000}", 15); // "015 "
17. Custom number formatting (e.g. phone number)

String.Format("{0:+### ### ### ###}", 447900123456); // "+447 900 123 456"
String.Format("{0:##-####-####}", 8958712551); // "89-5871-2551"
18. Phone No (###) ###-#### validation control
<asp:RegularExpressionValidator runat="server" ID="PNRegEx" ControlToValidate="PhoneNumberTextBox" Display="None" ValidationExpression="((\(\d{3}\) ?)
(\d{3}-))?\d{3}-\d{4}"

ErrorMessage="<b>Invalid Field</b><br />Please enter a phone number in the format:<br />(###) ###-####" />
19. To find Labels
Control myForm = Page.FindControl("Form1");
foreach (Control ctl in myForm.Controls)
{
    if (ctl.GetType().ToString().Equals("System.Web.UI.WebControls.Label"))
   {
     ((Label)ctl).Text = i.ToString();
       i++;
   }
}

20. Check box checking differently

Label1.Text = string.Format("Check box1 status <b>{0}</b> check box2 status <b>{1}</b>",

(CheckBox1.Checked ? "do" : "do not"), (CheckBox2.Checked ? "do" : "do not"));
21. If onblur , the textbox show display a message and change the background color

var defaultText ="Enter Your Keyword";
function WaterMark(txt, evt)
{
if(txt.value.length == 0 && evt.type == "blur")
{
txt.style.color = "gray"; --------- ERROR
txt.value = defaultText;
}
if(txt.value == defaultText && evt.type == "focus")
{
txt.style.color = "black";
txt.value="";
}
}


22. javascript error "Sys.InvalidOperationException. ScriptLoader.loadscripts cannot be called while the ScriptLoader is already loading scripts".

<script type="text/javascript">
Sys.WebForms.PageRequestManager.getInstance().add_initializeRequest(initRequest);
function initRequest(sender, args)
{
if(Sys.WebForms.PageRequestManager.getInstance().get_isInAsyncPostBack()) args.set_cancel(true);
}
</script>

write the above query in a page
23.  how to access all the controls through javascript

var elem = document.getElementById('frmMain').elements;
for(var i = 0; i < elem.length; i++)
{
   str += "<b>Type:</b>" + elem[i].type + "  ";
  str += "<b>Name:</b>" + elem[i].name + "  ";
  str += "<b>Value:</b><i>" + elem[i].value + "</i>  ";
   str += "<BR>";
}
24. how to get id of the particular control

   var ctrl1 = document.getElementsByTagName('textarea');
      for (var i = 0; i < ctrl1.length; i++)
     {
       if (ctrl1[i].title == 'Order')
       {
       ctrl1[i].value = ordno;
       }
     }
   }
25. Delete duplicate records in a table



WITH CTE (COl1,Col2, DuplicateCount)

AS

(

SELECT COl1,Col2,

ROW_NUMBER() OVER(PARTITION BY COl1,Col2 ORDER BY Col1) AS DuplicateCount

FROM DuplicateRcordTable

)

DELETE

FROM CTE

WHERE DuplicateCount > 1
26. How to get readonly textbox value in server side

Textbox1.Attributes.Add("readonly", "readonly");

27. Find the broswer version
Dim browserCaps As HttpBrowserCapabilities = Page.Request.Browser

lblbrowser.Text = "Your Browser : " + browserCaps.Browser + " Version : " + browserCaps.MajorVersion.ToString

28. how to change message box font ?

http://msdn.microsoft.com/en-gb/magazine/cc188920.aspx


29. Autocomplete Extender Method using DB



[WebMethod]

public string[] GetCountryInfo(string prefixText)

{

int count = 10;

string sql = "Select * from Country Where Country_Name like @prefixText";

SqlDataAdapter da = new SqlDataAdapter(sql,”Your Connection String Comes Here”));

da.SelectCommand.Parameters.Add("@prefixText", SqlDbType.VarChar, 50).Value = prefixText+ "%";

DataTable dt = new DataTable();

da.Fill(dt);

string[] items = new string[dt.Rows.Count];

int i = 0;

foreach (DataRow dr in dt.Rows)

{

items.SetValue(dr["Country_Name"].ToString(),i);

i++;

}

return items;

}



<cc1:AutoCompleteExtender ID="AutoCompleteExtender1" runat="server" MinimumPrefixLength="1" ServiceMethod="GetCountryInfo" ServicePath="WebService.asmx" TargetControlID="TextBox1"> </cc1:AutoCompleteExtender>



30. Pass Values from one page to another page without State Manangement techniques.

use Cross-page posting, Posts current page information to the target page.

instead of redirect , use button property postbackURL =target page

ex..


<asp:Button ID="Button1" PostBackUrl="~/TargetPage.aspx" runat="server" Text="Submit" />
in TargetPage Onload
if (Page.PreviousPage != null)
{
DropDownList SourceTextBox = (DropDownList )Page.PreviousPage.FindControl("DropDownList1");
if (SourceTextBox != null)
{
Label1.Text = SourceTextBox.SelectedValue;

}

}


31. How to change SA password in SQL Server



LOGIN sa ENABLE

GO

ALTER LOGIN sa WITH PASSWORD = '<password>'

GO



32. for CSS calls in windows application



<Global.System.Configuration.DefaultSettingValue("Font: Name=Arial, Size=9")> Public Property Font() As String

Get

Return CType(strFont, String)

End Get

Set(ByVal value As String)

strFont = value

End Set

End Property



33. Display hand symbol in div or button



<div style="cursor:hand"><u>submit</u></div>





34. Rectangle textbox to ellipse



GraphicsPath gp = new GraphicsPath();

gp.AddEllipse(0, 0, this.cmdbtn.ClientSize.Width,this.cmdbtn.ClientSize.Height);

this.cmdbtn.Region = new Region(gp);



35. save screen of the windows application

int width, height;

width = System.Windows.Forms.SystemInformation.PrimaryMonitorSize.Width;

height = System.Windows.Forms.SystemInformation.PrimaryMonitorSize.Height;



The following code will capture the screen and save it in the desktop as image.bmp;



Bitmap sBit;

Rectangle screenRegiion = Screen.AllScreens[0].Bounds;

sBit = new Bitmap(width, height, PixelFormat.Format32bppArgb);

Graphics sGraph = Graphics.FromImage(sBit);

sGraph.CopyFromScreen(screenRegiion.Left, screenRegiion.Top, 0, 0, screenRegiion.Size);

string savedPath =Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + @"\exmpale.bmp";

sBit.Save(savedPath);



36. To bind the combo box after particulare time interval

//Define a delgate to bind a combobox

delegate void BindComboBox();

//Defien a timer to bind the combobox for regular intervals

System.Timers.Timer bindTimer = new System.Timers.Timer();

//on form load add a event to elapsed.

bindTimer.Elapsed += new ElapsedEventHandler(BindComboBoxEvent);

bindTimer.Interval = 60000;//for every one minute

bindTimer.Start();



public void BindComboBoxEvent(object source, ElapsedEventArgs e)

{

//Create a Object for delagate and pass the bidn data method as argument

BindComboBox bind= new BindComboBox(BindData);

this.BeginInvoke(bind);

}



private void BindData()

{

//Write code to bind data to combo box }



37. #Region "ShowReport"

Public Function ShowReport(ByVal path As String, ByVal sParamFld As String, ByVal sParamVal As String, ByVal sReportViewer As CrystalDecisions.Web.CrystalReportViewer) As ReportDocument

Dim tmpSortList As New SortedList

Dim ParamLength As Int16 = 0, iLoop As Int16 = 0

Dim ParamFld() As String, ParamFldVal() As String

Try



myReportDocument = New ReportDocument

myReportDocument.Load(path)



myReportDocument.SetDatabaseLogon(user, pwd, Servername, Database)

Dim Logoninfo As New TableLogOnInfo()

Logoninfo.ConnectionInfo.ServerName = Servername

Logoninfo.ConnectionInfo.DatabaseName = Database

Logoninfo.ConnectionInfo.UserID = user

Logoninfo.ConnectionInfo.Password = pwd

'myReportDocument.Database.Tables().Item(0).TestConnectivity()

myReportDocument.Database.Tables().Item(0).ApplyLogOnInfo(Logoninfo)

myReportDocument.VerifyDatabase()





ParamFld = sParamFld.Split("*")

ParamFldVal = sParamVal.Split("*")

If ParamFld.Length <> ParamFldVal.Length Then

Err.Raise(1, , "Parameter Fleid should be equal to Parameter Value")



End If

For iLoop = 0 To UBound(ParamFld)

tmpSortList.Add(ParamFld(iLoop), ParamFldVal(iLoop))

Next

ParamFldDefn = myReportDocument.DataDefinition.ParameterFields

ParamFldDefn.Reset()

Dim tmpCount As Integer = 0

sReportViewer.ReportSource = myReportDocument

'sReportViewer.DataBind()

sReportViewer.EnableParameterPrompt = False

For tmpCount = 0 To tmpSortList.Count - 1

myReportDocument.SetParameterValue(ParamFldDefn(tmpCount).Name, tmpSortList(ParamFldDefn(tmpCount).Name).ToString())

Next

Return myReportDocument

'fnToolbarSetting()





Catch ex As Exception

' lblErr.Text = ex.Message

Return Nothing

End Try

End Function

#End Region



38. convert string



Public Function ConvertoDate(ByVal dateString As String, ByRef result As DateTime) As DateTime

Try

Dim supportedFormats() As String = New String() {"dd/MM/yyyy", "MM/dd/yyyy", "MM/dd/yy", "ddMMMyyyy", "dMMMyyyy"}

result = DateTime.ParseExact(dateString, supportedFormats, System.Globalization.CultureInfo.CurrentCulture, System.Globalization.DateTimeStyles.None)



Return result

Catch ex As Exception

Return Nothing

End Try

End Function



39. redirect to prevoius page



Response.Redirect(Request.UrlReferrer.ToString(),false);



40 . Now entered value from SQL

insert into dupemp(name,salary,deptno) values('1sd',4000,12)

with CTE as(select *,ROW_NUMBER() over(order by (select 0))as row from dupemp)

select * from cte where row=(select max(row) from cte)



method 2

select top 1 column_list FROM

(select ROW_NUMBER() over(order by (select 0)) as rownum,column_list from table_name) t order by rownum desc



 BEGIN DECLARE @Output VARCHAR(8000) SELECT @Output = COALESCE (@Output + ';', '') + CONVERT(varchar(20), PolicyNo)

FROM tblSubmissionList END



42. To password encription



FormsAuthentication.HashPasswordForStoringInConfigFile(objCreateUser.Pwd, "MD5");



43. to use Session in class file

HttpContext.Current.Session["UserName"]



44. How to use ModalPopupExtender for the asking the requirement and process within the same page

(ex.. like javascript prompt , msgbox like that)



1. Create the panel with the required information

ex. forgot password

<asp:Panel ID="pnlForgotPwd" runat="server" BorderWidth="3" BorderStyle="Double" BorderColor="Gray" CssClass="cssImg">

<asp:Panel ID="handlePwd" runat="server" Style="cursor: move; background-color: #F5F5F5;

border: solid 1px Gray; color: Black;">

<div>

<b style="color: #B5AA6D"> Forgot your password.</b>

</div>

</asp:Panel>

<asp:UpdatePanel ID="upForgotPwd" runat="server">

<ContentTemplate>

<table align="center" style="margin-left: 10px; margin-right: 10px;">

<tr>

<td align="right" style="height: 30px;">

Login ID :

</td>

<td align="right" valign="middle">

<asp:TextBox ID="txtLoginID" runat="server" Width="170px" ValidationGroup="ForgotPwd"></asp:TextBox>

</td>

<td>

<asp:RequiredFieldValidator ID="rfvLoginID" runat="server" ControlToValidate="txtLoginID"

Font-Size="Small" ValidationGroup="ForgotPwd">*</asp:RequiredFieldValidator>

</td>

<td>

<asp:UpdateProgress ID="udProgressPwd" runat="server" AssociatedUpdatePanelID="upForgotPwdBtn"

DisplayAfter="50" DynamicLayout="true">

<ProgressTemplate>

<div style="margin-left: 15px;">

<asp:Image ID="imgProPwd" runat="server" Height="15px" ImageUrl="~/images/Processing2.gif" /></div>

</ProgressTemplate>

</asp:UpdateProgress>

</td>

</tr>

<tr>

<td colspan="4">

<hr />

</td>

</tr>

<tr align="center">

<td align="center" colspan="2" valign="bottom">

<asp:UpdatePanel ID="upForgotPwdBtn" runat="server">

<ContentTemplate>

<asp:ImageButton ID="btnForgotPassword" ImageUrl="~/images/submit1.png" runat="server"

ValidationGroup="ForgotPwd" OnClick="btnForgotPassword_Click" />

<asp:ImageButton ID="btnCancelPwd" ImageUrl="~/images/cancel.png" runat="server"

CausesValidation="false" OnClick="btnCancelPwd_Click" />

</ContentTemplate>

</asp:UpdatePanel>

</td>

</tr>

</table>

</ContentTemplate>

</asp:UpdatePanel>

</asp:Panel>



2. when the modelextender will arise

<asp:LinkButton ID="btnForgotPwd" runat="server" ForeColor="#B5AA6D" Text="Forgot Password" />



3. Assign ModalPopupExtender



<cc1:ModalPopupExtender ID="btnForgotPwd_ModalPopupExtender" BackgroundCssClass="BGCSS"

runat="server" DynamicServicePath="" Enabled="True" TargetControlID="btnForgotPwd"

PopupControlID="pnlForgotPwd" PopupDragHandleControlID="handleForgotPwd" CancelControlID="btnCancel">

</cc1:ModalPopupExtender>



TargetControlID - to invoke the modalpopupextender

PopupControlID - panel Control id

PopupDragHandleeControlId = which part to drag

CancelControlId - to canel the modalpopupextender



4. Cancel button event

pnlForgotPwd.Style.Add("display", "none");

btnForgotPwd_ModalPopupExtender.Hide();

txtLoginID.Text = "";

upMain.Update();



5. How to show error while popupwindow

a) create one more panel with required control to display error message

<div id="MsgBox" runat="server">

</div>



<asp:Panel ID="pnlOuterMsgBox" runat="server" CssClass="outerPopup" Style="display: none;">

<asp:Panel ID="pnlInnerMsgBox" BackColor="#F0F0F0" CssClass="cssImg" runat="server"

Width="350px">

<br />

<asp:Image ID="imgMsgBox" runat="server" /><asp:Label ID="lblMsgBox" runat="server"></asp:Label>

<br />

<br />

<asp:ImageButton ID="btnOK" runat="server" ImageUrl="~/images/ok.png" />

<br />

</asp:Panel>

</asp:Panel>



b) create one more modalpopextender



<cc1:ModalPopupExtender ID="mpeMsgBox" runat="server" TargetControlID="MsgBox" PopupControlID="pnlOuterMsgBox"

CancelControlID="btnCancel" OkControlID="btnOK" BackgroundCssClass="BGCSS" />



<asp:Button ID="btnCancel" runat="server" Text="Cancel" Enabled="false" />



success and not success



if (objUser.CheckUserExists(txtLoginID.Text))

{

lblMsgBox.ForeColor = System.Drawing.Color.Green;

imgMsgBox.ImageUrl = "~/images/id_ok.png";

lblMsgBox.Text = " Password successfully send to your HP Number.";

txtLoginID.Text = "";

mpeMsgBox.Show();

pnlForgotPwd.Style.Add("display", "none");

btnForgotPwd_ModalPopupExtender.Hide();

upMain.Update();

}

else

{

lblMsgBox.ForeColor = System.Drawing.Color.Red;

imgMsgBox.ImageUrl = "~/images/id_occ.png";

lblMsgBox.Text = " Incorrect Login ID.";

mpeMsgBox.Show();

pnlForgotPwd.Visible = true;

btnForgotPwd_ModalPopupExtender.Show();

upMain.Update();

}



45. to focus popupwindow



function openPopup(purl)

{

wndAttr = "width=520,height=630,left=100,top=100";

var w = window.open(purl, 'popup_test', wndAttr);

w.focus();

}



46. retrieve page records

command.ExecutePageReader(CommandBehavior.Default, 1, 10);



47. REfresh every 2 seconds



<body onload="doTimer();"> <form id="form1" runat="server" > <div> <asp:ScriptManager ID="ScriptManager1" runat="server"> </asp:ScriptManager> <asp:UpdatePanel ID="UpdatePanel1" runat="server"> <ContentTemplate> <asp:GridView ID="GridView1" runat="server"> </asp:GridView> </ContentTemplate> </asp:UpdatePanel> </div> </form> <script type="text/javascript"> var t; var timer_is_on = 0; function timedCount() { __doPostBack("UpdatePanel1", ""); t = setTimeout("timedCount()", 2000);//2 second } function doTimer() { if (!timer_is_on) { timer_is_on = 1; timedCount();} }</script> </body>





48.. Gridview Chkbox in ASp Update panel



function CheckAllElements(checkallbox) {



if (checkallbox.checked == true) {

for (i = 0; i < document.forms[0].elements.length; i++) {

//.match("world")

if (document.forms[0].elements[i].id.match("chkDetails") != null)

{

if (document.forms[0].elements[i].type == 'checkbox') {

document.forms[0].elements[i].checked = true;

}

}

}

}

else {

for (i = 0; i < document.forms[0].elements.length; i++) {

if (document.forms[0].elements[i].id.match("chkDetails") != null) {

if (document.forms[0].elements[i].type == 'checkbox') {

document.forms[0].elements[i].checked = false;

}

}

}

}

//document.Form1.submit();

}



49. convert linq to datatable



public DataTable LINQToDataTable<T>(IEnumerable<T> varlist)

{

DataTable dtReturn = new DataTable();

// column names

PropertyInfo[] oProps = null;

if (varlist == null) return dtReturn;

foreach (T rec in varlist)

{

// Use reflection to get property names, to create table, Only first time, others

//will follow

if (oProps == null)

{

oProps = ((Type)rec.GetType()).GetProperties();

foreach (PropertyInfo pi in oProps)

{

Type colType = pi.PropertyType;

if ((colType.IsGenericType) && (colType.GetGenericTypeDefinition() == typeof(Nullable<>)))

colType = colType.GetGenericArguments()[0];

dtReturn.Columns.Add(new DataColumn(pi.Name, colType));

}

}



DataRow dr = dtReturn.NewRow();

foreach (PropertyInfo pi in oProps)

{

dr[pi.Name] = pi.GetValue(rec, null) == null ? DBNull.Value : pi.GetValue

(rec, null);

}

dtReturn.Rows.Add(dr);

}

return dtReturn;

}



LINQToDataTable(ResultMenuAcc); // var ResultMenuAcc result



50. to enter key active login id

txtPassword.Attributes.Add("onKeyPress", "javascript:if (event.keyCode == 13) __doPostBack('" + btnLogin.UniqueID + "','')");



52. Split only number from string exx. adsfad1234



you can use regular expression to split the value



ex.



string val ="SCV 5000";

Regex r = new Regex("^[0-9]$");

string[] tmpval = r.Split(val);



tmpval[1] = have numberic values

tmpval[0] = character values

Regex not work try below one "^\d+$"



53. SCrolling text from bottom to up with scroll bar



<marquee direction=up height=150 scrollAmount=2.8 scrollDelay=70 onMouseDown="this.stop()" onMouseOver="this.stop()" onMouseMove="this.stop()" onMouseOut="this.start()"> hello <br /> hello1 </marquee>



54. Remove duplicates in a string

function removeDuplicates(field) {

var temp = field.value;

var array = temp.split(" ");

array.sort();

temp = array.join(" ");



55. Without prompting close button message



function CloseWindow()

{

window.open('','_self','');

window.close();

}



56.. Refresh page



<asp:Timer ID="Timer1" OnTick="Timer1_Tick" runat="server" Interval="10000" />



<asp:UpdatePanel ID="StockPricePanel" runat="server" UpdateMode="Conditional">

<Triggers>

<asp:AsyncPostBackTrigger ControlID="Timer1" />

</Triggers>

<ContentTemplate>

Stock price is <asp:Label id="StockPrice" runat="server"></asp:Label><BR />

as of <asp:Label id="TimeOfPrice" runat="server"></asp:Label>

</ContentTemplate>

</asp:UpdatePanel>



protected void Timer1_Tick(object sender, EventArgs e)

{



}



57. to populate the file and folder in tree



public void PopulateTree(string dir, TreeNode node) {

// get the information of the directory

DirectoryInfo directory = new DirectoryInfo(dir);

// loop through each subdirectory

foreach(DirectoryInfo d in directory.GetDirectories()) {

// create a new node

TreeNode t = new TreeNode(d.Name);

// populate the new node recursively

PopulateTree(d.FullName, t);

node.Nodes.Add(t); // add the node to the "master" node

}

// lastly, loop through each file in the directory, and add these as nodes

foreach(FileInfo f in directory.GetFiles()) {

// create a new node

TreeNode t = new TreeNode(f.Name);

// add it to the "master"

node.Nodes.Add(t);

}

}



58. Common on Text box CSS



input[type=text] {

width: 300px;

background-color: cyan;

}





59.custom MessageBox



private void MessageBox(string Message)

{ Guid Key = Guid.NewGuid();

string K = Key.ToString().Replace("-", "");

ScriptManager.RegisterClientScriptBlock(this, GetType(), k, "alert('" + Message + "');", true); }

Sunday, December 20, 2009

BusinessLayer and Presentation Layer - C#

Business Layer
using System;
using System.Data;
using System.Data.SqlClient;
using AcPro.DataLayer;

namespace AcPro.BusinessLayer
{
    ///
    /// Summary description for loging.
    ///

    public class login
    {
        public login()
        {
           
        }
        private string P_orgname;
        public string orgname
        {
            set
            {
                P_orgname=value;
            }
            get
            {
                return P_orgname;
            }
        }
        private string P_username;
        public string username
        {
            set
            {
                P_username=value;
            }
            get
            {
                return P_username;
            }
        }
        private string P_pwd;
        public string pwd
        {
            set
            {
                P_pwd=value;
             }
            get
            {
                return P_pwd;
            }
        }
        public DataSet Executesp()
        {
            string strsql="loginsuccess";
            SqlParameter[] prms;
            prms=new SqlParameter[3];
            prms[0]=new SqlParameter("@orgname",orgname);
            prms[1]=new SqlParameter("@username",username);
            prms[2]=new SqlParameter("@pwd",pwd);
            DataSet ds=DataAccess.ExecuteSql(strsql,prms);
            return ds;
        }
    }
}


Presentation Layer -C#


           Login is  Business Layer File Name
            login ln=new login();
            ln.orgname=Ddl_OrgName.SelectedItem.Text.Trim();
            Session["OrgName"]=Ddl_OrgName.SelectedItem.Text.Trim(); // For Display purpose -Muhil
            ln.username=txt_UserName.Text.Trim();
            Session["UserName"]=txt_UserName.Text.Trim(); //For Display purpose -Muhil
            ln.pwd=txt_Password.Text.Trim();
            DataSet ds=ln.Executesp();

Javascript Stuff

How to Clear Controls in Web-Page using JavaScript?
    function clearFormTextElements(Form)
    {  
        if( typeof( Form ) == "object" )
        {
            for(var i = 0; i <  Form.elements.length; i ++ )
            {
                if( Form.elements[i].type == "text" )
                    Form.elements[i].value = "" ;
                else
                Form.elements[i].selectedIndex=-1;
            }
        }
    }

Analog Clock

fCol='white';
sCol='FF00FF';
mCol='red';
hCol='green';
Ybase=50;
Xbase=50;
H='...';
H=H.split('');
M='... ';
M=M.split('');
S='....';
S=S.split('');
NS4=(document.layers);
NS6=(document.getElementById&&!document.all);
IE4=(document.all);
Ypos=0;
Xpos=0;
dots=12;
Split=360/dots;


document.write('div Style="position:absolute;top:0px;left:0px">

for (i=1; i less than dots+1; i++){
document.write('div id="ieDigits" style="position:absolute;top:0px;left:0px;width:30px;height:30px;font-family:Arial;font-size:10px;color:'+fCol+';text-align:center;padding-top:10px">'+i+'
');
}
document.write('/div>')
document.write('div style="position:absolute;top:0px;left:0px">
');
for (i=0; i less than M.length; i++){
document.write('div id=y style="position:absolute;width:2px;height:2px;font-size:2px;background:'+mCol+'">
');
}
document.write('/div>')
document.write('div style="position:absolute;top:0px;left:0px">
');
for (i=0; i less than H.length; i++){
document.write('div id=z style="position:absolute;width:2px;height:2px;font-size:2px;background:'+hCol+'">
');
}
document.write('/div>')
document.write('div style="position:absolute;top:0px;left:0px">
');
for (i=0; i less than S.length; i++){
document.write('div id=x style="position:absolute;width:2px;height:2px;font-size:2px;background:'+sCol+'">
');
}
document.write('/div>')



function clock(){
time = new Date ();
secs = time.getSeconds();
sec = -1.57 + Math.PI * secs/30;
mins = time.getMinutes();
min = -1.57 + Math.PI * mins/30;
hr = time.getHours();
hrs = -1.57 + Math.PI * hr/6 + Math.PI*parseInt(time.getMinutes())/360;
if (IE4){
Ypos=document.body.scrollTop+window.document.body.clientHeight-Ybase-20;
Xpos=document.body.scrollLeft+window.document.body.clientWidth-Xbase-20;
for (i=0; i < dots; ++i){
 ieDigits[i].style.pixelTop=Ypos-15+Ybase*Math.sin(-1.045 +i *Split*Math.PI/180)
 ieDigits[i].style.pixelLeft=Xpos-15+Xbase*Math.cos(-1.045 +i *Split*Math.PI/180)
 }
for (i=0; i < S.length; i++){
 x[i].style.pixelTop =Ypos+i*Ybase/4.1*Math.sin(sec);
 x[i].style.pixelLeft=Xpos+i*Xbase/4.1*Math.cos(sec);
 }
for (i=0; i < M.length; i++){
 y[i].style.pixelTop =Ypos+i*Ybase/4.1*Math.sin(min);
 y[i].style.pixelLeft=Xpos+i*Xbase/4.1*Math.cos(min);
 }
for (i=0; i < H.length; i++){
 z[i].style.pixelTop =Ypos+i*Ybase/4.1*Math.sin(hrs);
 z[i].style.pixelLeft=Xpos+i*Xbase/4.1*Math.cos(hrs);
 }
}
setTimeout('clock()',100);
}
clock();

How to Select all checkbox in CheckboxList ?

function selectall()
{

 for (var i=1; i <   document.forms(0).length; i++)
 { 
if(document.forms(0).elements[i].id )
     {
    if(document.forms(0).elements[i].id.indexOf("CheckBoxList1")!=-1)
      {
     document.forms(0).elements[i].checked=true;
      }
    }
 }
}


How to DeSelect all checkbox in CheckboxList using Javascript?

function deselectall()
{
 
 for (var i=1; i <   document.forms(0).length; i++)
 { 
if(document.forms(0).elements[i].id )
     {
    if(document.forms(0).elements[i].id.indexOf("CheckBoxList1")!=-1)
      {
     document.forms(0).elements[i].checked=false;
      }
    }
 }
}



Amount Field Validation

function fnCurrency(pCtlTextBox)
{
    var pNumKeyCode = window.event.keyCode;
    var pStrValue = pCtlTextBox.value;
    var pNumLength = pStrValue.length - 1;
    var pNumDeciPosi = pStrValue.indexOf(".");
    if (pNumLength < 0 && pNumKeyCode == 46)
    {    alert("Period Not allowed In First Position.");
        window.event.keyCode = 0;           
    }
    else if (pNumDeciPosi > 0 && pNumDeciPosi+2 == pNumLength)
    {   
        alert("After Period Only Two Numbers are Allowed.");
        window.event.keyCode = 0;
    }
    else if(pNumKeyCode > 47 && pNumKeyCode < 58)
    {
        window.event.keyCode = pNumKeyCode;
    }
    else if(pNumKeyCode == 46 && pNumDeciPosi < 0)
    {   
        window.event.keyCode = pNumKeyCode;
    }
    else
    {   
        alert("Only numeric values allowed.");
        window.event.keyCode = 0;
    }
}

How to Know No. Of users Logged In?

STEP 1 

Add below lines in  Global.asax File

Sub Application_Start(ByVal sender As Object, ByVal e As EventArgs)
Application.Add("UserCount", 0)
End Sub



Sub Session_Start(ByVal sender As Object, ByVal e As EventArgs)

Dim UserCount As Integer
UserCount = Convert.ToInt32(Application.Get("UserCount").ToString())
UserCount = UserCount + 1
Application.Set("UserCount", UserCount)
End Sub

Sub Session_End(ByVal sender As Object, ByVal e As EventArgs)
Dim UserCount As Integer
UserCount = Convert.ToInt32(Application.Get("UserCount").ToString())
UserCount = UserCount - 1
Application.Set("UserCount", UserCount)
End Sub

Step: 2 
Add a Web.Config File

  < sessionState mode="InProc"/ >        

Step: 3
Code Behind


   TextBox1.Text = Application.Get("UserCount").ToString()


Monday, December 14, 2009

How to convert the string to DateTime ?

Common Function:

Public Function ConvertoDate(ByVal dateString As String,
 ByRef result As DateTime) As DateTime   
Try             
     Dim supportedFormats() As String = New String() 
{"dd/MM/yyyy", "MM/dd/yyyy", "MM/dd/yy", 
"ddMMMyyyy", "dMMMyyyy"}             
     result = DateTime.ParseExact(dateString, 
supportedFormats, System.Globalization.CultureInfo.
CurrentCulture, System.Globalization.DateTimeStyles.None)  
     Return result    
Catch ex As Exception   
    Return Nothing      
End Try    
End Function 
We should enter the Date below format. Then only it 
will convert into DateTime.

Dim supportedFormats() As String = New String() {"dd/MM/yyyy", 
"MM/dd/yyyy", "MM/dd/yy", "ddMMMyyyy", "dMMMyyyy"}


Calling the function

ConvertoDate(frmDate, TfrmDate)
frmDate - String
TfrmDate - DateTime object

Where does the Session Variables gets Stored?

Session variables are stored in a SessionStateItemCollection object that is exposed through the HttpContext.Session property.

In an ASP.NET page, the current session variables are exposed through the Session property of the page object.

Sessions are identified by a unique identifier that can be read by using the SessionID property. When session state is enabled for an ASP.NET application, each request for a page in the application is examined for a SessionID value sent from the browser. If no SessionID value is supplied, ASP.NET starts a new session and the SessionID value for that session is sent to the browser with the response.

By default, SessionID values are stored in a cookie. However, you can also configure the application to store SessionID values in the URL for a "cookieless" session.


By default, the SessionID value is stored in a non-expiring session cookie in the browser. However, you can specify that session identifiers should not be stored in a cookie by setting the cookieless attribute to true in the sessionState section of the Web.config file.






Different Session-State Modes

ASP.NET session state supports several different storage options for session data.

  1.       InProc mode, which stores session state in memory on the Web server. This is the default.
  2.       StateServer mode, which stores session state in a separate process called the ASP.NET state service. This ensures that session state is preserved if the Web application is restarted and also makes session state available to multiple Web servers in a Web farm.
  3.       SQLServer mode stores session state in a SQL Server database. This ensures that session state is preserved if the Web application is restarted and also makes session state available to multiple Web servers in a Web farm.
  4.      Custom mode, which enables you to specify a custom storage provider.
  5.      Off mode, which disables session state.

 In-Process Mode

In-process mode is the default session state mode and is specified using the InProc SessionStateMode enumeration value. In-process mode stores session state values and variables in memory on the local Web server. It is the only mode that supports the Session_OnEnd event

StateServer mode

StateServer mode stores session state in a process, referred to as the ASP.NET state service, that is separate from the ASP.NET worker process or IIS application pool. Using this mode ensures that session state is preserved if the Web application is restarted and also makes session state available to multiple Web servers in a Web farm.

To use StateServer mode, you must first be sure the ASP.NET state service is running on the server used for the session store. The ASP.NET state service is installed as a service when ASP.NET and the .NET Framework are installed. The ASP.Net state service is installed at the following location:

systemroot\Microsoft.NET\Framework\versionNumber\aspnet_state.exe

SQL Server Mode

SQLServer mode stores session state in a SQL Server database. Using this mode ensures that session state is preserved if the Web application is restarted and also makes session state available to multiple Web servers in a Web farm.

To use SQLServer mode, you must first be sure the ASP.NET session state database is installed on SQL Server. You can install the ASP.NET session state database using the Aspnet_regsql.exe tool

Example





Custom Mode

Custom mode specifies that you want to store session state data using a custom session state store provider. When you configure your ASP.NET application with a Mode of Custom, you must specify the type of the session state store provider using the providers sub-element of the sessionState configuration element. 


You specify the provider type using an add sub-element and include both a type attribute that specifies the provider's type name and a name attribute that specifies the provider instance name. 

The name of the provider instance is then supplied to the customProvider attribute of the sessionState element to configure ASP.NET session state to use that provider instance for storing and retrieving session data.

Examples



State Management Advantages and Disadvantages

ASP.Net State Management
State management is the process by which you maintain state and page information over multiple requests for the same or different pages.

client-side state management
  1.       View state
  2.       Control state
  3.       Hidden fields
  4.       Cookies
  5.       Query strings
View state
Web Forms pages provide the ViewState property as a built-in structure for automatically retaining values between multiple requests for the same page. View state is maintained as a hidden field in the page

Advantages of using view state:

  1.        The view state is contained in a structure within the page code.
  2.       View state does not require any custom programming to use. It is on by default to maintain state data on controls.
  3.        The values in view state are hashed, compressed, and encoded for Unicode implementations, which provides more security than using hidden fields.
Disadvantages of using view state:
  1.        Because the view state is stored in the page itself, storing large values can cause the page to slow down when users display it and when they post it. This is especially relevant for mobile devices, where bandwidth is often a limitation.
  2.        Mobile devices might not have the memory capacity to store a large amount of view-state data.
  3.        The view state is stored in one or more hidden fields on the page. Although view state stores data in a hashed format, it can still be tampered with. The information in the hidden field can be seen if the page output source is viewed directly, creating a potential security issue


Control State
The ASP.NET page framework provides the ControlState property as way to store custom control data between server trips

Advantages of using control state are:

  1.     By default, control state is stored in hidden fields on the page.
  2.     Because control state cannot be turned off like view state, control state is a more reliable method for managing the state of controls.
  3.     Custom adapters can be written to control how and where control-state data is stored.
Disadvantage of using control state are:
      Some programming is required   While the ASP.NET page framework provides a foundation for control state, control state is a custom state-persistence mechanism. To fully utilize control state, you must write code to save and load control state.

Hidden Fields

You can store page-specific information in a hidden field on your page as a way of maintaining the state of your page.If you use hidden fields, it is best to store only small amounts of frequently changed data on the client.

Advantages of using hidden fields are:
  1.       The hidden field is stored and read from the page.
  2.       Almost all browsers and client devices support forms with hidden fields.
  3.      Hidden fields are standard HTML controls that require no complex programming logic.

Disadvantages of using hidden fields are:
  1.      The hidden field can be tampered with. The information in the hidden field can be seen if the page output source is viewed directly, creating a potential security issue. You can manually encrypt and decrypt the contents of a hidden field, but doing so requires extra coding and overhead. If security is a concern, consider using a server-based state mechanism so that no sensitive information is sent to the client.
  2. The hidden field does not support rich data types. Hidden fields offer a single string value field in which to place information. To store multiple values, you must implement delimited strings and the code to parse those strings. You can manually serialize and de-serialize rich data types to and from hidden fields, respectively. However, it requires extra code to do so. If you need to store rich data types on the client, consider using view state instead. View state has serialization built-in, and it stores data in hidden fields.
  3.   Because hidden fields are stored in the page itself, storing large values can cause the page to slow down when users display it and when they post it.
  4.   If the amount of data in a hidden field becomes very large, some proxies and firewalls will prevent access to the page that contains them. Because the maximum amount can vary with different firewall and proxy implementations, large hidden fields can be sporadically problematic

Cookies

Cookies are useful for storing small amounts of frequently changed information on the client. The information is sent with the request to the server

Advantages of using cookies are:

  1.       The cookie can expire when the browser session ends, or it can exist indefinitely on the client computer, subject to the expiration rules on the client.
  2.      The cookie is stored on the client and read by the server after a post.
  3.       The cookie is a lightweight, text-based structure with simple key-value pairs.
  4.      Although the durability of the cookie on a client computer is subject to cookie expiration processes on the client and user intervention, cookies are generally the most durable form of data persistence on the client.

Disadvantages of using cookies are:
  1.         Most browsers place a 4096-byte limit on the size of a cookie, although support for 8192-byte cookies is becoming more common in newer browser and client-device versions.
  2.        Some users disable their browser or client device's ability to receive cookies, thereby limiting this functionality.
  3.        Users can manipulate cookies on their computer, which can potentially cause a security risk or cause the application that is dependent on the cookie to fail. Also, although cookies are only accessible by the domain that sent them to the client, hackers have historically found ways to access cookies from other domains on a user's computer. You can manually encrypt and decrypt cookies, but it requires extra coding and can affect application performance because of the time that is required for encryption and decryption

Query Strings

A query string is information that is appended to the end of a page URL.

You can use a query string to submit data back to your page or to another page through the URL. Query strings provide a simple but limited way of maintaining some state information. For example, query strings are an easy way to pass information from one page to another, such as passing a product number to another page where it will be processed.

Advantages of using query strings are:
  1.        The query string is contained in the HTTP request for a specific URL.
  2.     Almost all browsers and client devices support using query strings to pass values.
  3.       ASP.NET provides full support for the query-string method, including methods of reading query strings using the Params property of the HttpRequest object.
Disadvantages of using query strings are:
  1.       The information in the query string is directly visible to the user via the browser's user interface. A user can bookmark the URL or send the URL to other users, thereby passing the information in the query string along with it. If you are concerned about any sensitive data in the query string, consider using hidden fields in a form that uses POST instead of using query strings
  2.     Some browsers and client devices impose a 2083-character limit on the length of URLs.

Server-Side State Management Options

Server-side options for storing page information typically have higher security than client-side options, but they can use more Web server resources, which can lead to scalability issues when the size of the information store is large.

server-side state management options that ASP.NET supports:

  1.       Application state
  2.       Session state
  3.       Profile properties
  4.       Database support

Application State

ASP.NET provides application state via the HttpApplicationState class as a method of storing global application-specific information that is visible to the entire application. Application-state variables are, in effect, global variables for an ASP.NET application

Advantages of using application state are:

  1.        Application state is easy to use, familiar to ASP developers, and consistent with other .NET Framework classes.
  2.         Because application state is accessible to all pages in an application, storing information in application state can mean keeping only a single copy of the information.

Disadvantages of using application state are:

  1.       The scope of application state can also be a disadvantage. Variables stored in application state are global only to the particular process the application is running in, and each application process can have different values. Therefore, you cannot rely on application state to store unique values or update global counters in Web-garden and Web-farm server configurations.
  2.       Because global data that is stored in application state is volatile, it will be lost if the Web server process containing it is destroyed, such as from a server crash, upgrade, or shutdown.
  3.        Application state requires server memory, which can affect the performance of the server as well as the scalability of the application.

Session State

ASP.NET provides a session state, which is available as the HttpSessionState class, as a method of storing session-specific information that is visible only within the session. ASP.NET session state identifies requests from the same browser during a limited time window as a session, and provides the ability to persist variable values for the duration of that session.


Advantages of using session state are:
  1.      The session-state facility is easy to use, familiar to ASP developers, and consistent with other .NET Framework classes.
  2.        Session management events can be raised and used by your application.
  3.        Data placed in session-state variables can be preserved through Internet Information Services (IIS) restarts and worker-process restarts without losing session data because the data is stored in another process space. Additionally, session-state data can be persisted across multiple processes, such as in a Web farm or a Web garden.
  4.        Session state can be used in both multi-computer and multi-process configurations, therefore optimizing scalability scenarios.
  5.       Session state works with browsers that do not support HTTP cookies, although session state is most commonly used with cookies to provide user identification facilities to a Web application. Using session state without cookies, however, requires that the session identifier be placed in the query string, which is subject to the security issues stated in the query string section of this topic.
  6. You can customize and extend session state by writing your own session-state provider. Session state data can then be stored in a custom data format in a variety of data storage mechanisms, such as a database, an XML file, or even to a Web service.

Disadvantage of using session state are:
      Performance considerations   Session-state variables stay in memory until they are either removed or replaced, and therefore can degrade server performance. Session-state variables that contain blocks of information, such as large datasets, can adversely affect Web-server performance as server load increases.


Profile Properties

ASP.NET provides a feature called profile properties, which allows you to store user-specific data. It is similar to session state, except that unlike session state, the profile data is not lost when a user's session expires. The profile properties feature uses an ASP.NET profile, which is stored in a persistent format and associated with an individual user.

The ASP.NET profile allows you to easily manage user information without requiring you to create and maintain your own database. In addition, the profile makes the user information available using a strongly typed API that you can access from anywhere in your application. You can store objects of any type in the profile.

The ASP.NET profile feature provides a generic storage system that allows you to define and maintain almost any kind of data while still making the data available in a type-safe manner

Advantages of using profile properties are:
  1.       Data placed in profile properties is preserved through IIS restarts and worker-process restarts without losing data because the data is stored in an external mechanism. Additionally, profile properties can be persisted across multiple processes, such as in a Web farm or a Web garden.
  2.      Profile properties can be used in both multi-computer and multi-process configurations, therefore optimizing scalability scenarios.
  3.      In order to use profile properties, you must configure a profile provider. ASP.NET includes a SqlProfileProvider class that allows you to store profile data in a SQL database, but you can also create your own profile provider class that stores profile data in a custom format and to a custom storage mechanism, such as an XML file, or even to a Web service.

Disadvantages of using profile properties are:
  1.       Profile properties are generally slower than using session state because instead of storing data in memory, the data is persisted to a data store.
  2.       Unlike session state, the profile properties feature requires a considerable amount of configuration to use. To use profile properties, you must not only configure a profile provider, but you must pre-configure all of the profile properties that you want to store.
  3.       Profile properties require a certain amount of maintenance. Because profile data is persisted to non-volatile storage, you must make sure that your application calls the appropriate cleanup mechanisms, which are provided by the profile provider, when data becomes stale.