Monday, August 23, 2010

hiii

Saturday, August 21, 2010

<form action="http://www.google.com/cse" id="cse-search-box">
  <div>
    <input type="hidden" name="cx" value="partner-pub-3239228842410427:5ea2x3-35nv" />
    <input type="hidden" name="ie" value="ISO-8859-1" />
    <input type="text" name="q" size="31" />
    <input type="submit" name="sa" value="Search" />
  </div>
</form>
<script type="text/javascript" src="http://www.google.com/cse/brand?form=cse-search-box&amp;lang=en"></script>

Tuesday, August 17, 2010

HTTPException was unhandled by User Code?

HTTPException was unhandled by User Code?

Error executing child request for ~/page.aspx.


Ans: if page.aspx not exists in your current directory or renamed, so check the name.

Microsoft JScript runtime error?

Microsoft JScript runtime error: Sys.WebForms.PageRequestManagerParserErrorException: The message received from the server could not be parsed. Common causes for this error are when the response is modified by calls to Response.Write(), response filters, HttpModules, or server trace is enabled.



Details: Error parsing near '






<!DOCTYPE html P'.

Ans: Server.Transfer or Response.write wont work in Ajax enabled pages.

Thursday, August 12, 2010

Sample LINQ Queries

DBDataContext objeDC =new DBDataContext();


1. How to check whether the UserID exist in the table using LINQ?


UserMst objUserMst =null;
objUserMst= objeDC.UserMsts.SingleOrDefault(Rec => Rec.UserMstID == "sample");
if(objUserMst !=null)
//exists
else
// Not exists

PwdHistory objHistory = new PwdHistory();
objHistory.UserName = "Sample";
objHistory.UserPwd = FormsAuthentication.HashPasswordForStoringInConfigFile("password", "MD5");
objeDC.PwdHistories.InsertOnSubmit(objHistory);
objeDC.SubmitChanges();



FormsAuthentication.HashPasswordForStoringInConfigFile("password", "MD5");
4. use Transaction in LINQ (Roll and Commit)


DBTransaction objDBTrans=null;
objDBTrans = objeDC.Connection.BeginTransaction();
objeDC.Transaction = objDBTrans ;
try
{
       PwdHistory objHistory = new PwdHistory();
       objHistory.UserName = "Sample";
       objHistory.UserPwd = FormsAuthentication.HashPasswordForStoringInConfigFile("password", "MD5");
       objeDC.PwdHistories.InsertOnSubmit(objHistory);
       objeDC.SubmitChanges();
       objDBTrans.Commit();
}
catch(Exception ex)
{
       objDBTrans.RollBack();
}
5. Simple where condition using LINQ

var Result = from objLogin in objeDC.LoginLogs
where objLogin.UserMstID == strLoginId && objLogin.LoginEventID == "02"
select objLogin;


objUserMst = objeDC.UserMsts.SingleOrDefault(Rec => Rec.UserMstID == "sample");
if (objUserMst != null)
{
        objUserMst.eInsInd = true;
        objeDC.SubmitChanges();
}



var Result = from objUserGroup in objeDC.UserGroups
select objUserGroup;
DropdownList1.DataTextField = "Dsc";
DropdownList1.DataValueField = "UserGroupID";
DropdownList1.DataSource = Result;
DropdownList1.DataBind();



var Result = from objNewsMast in objeDC.NewsMasts
orderby objNewsMast.TimeStamp
select objNewsMast;
gvNewsImage.DataSource = Result;
gvNewsImage.DataBind();


var Result = from objMenu in objeDC.Menus
select new
{
          MenuID = objMenu.MenuID.ToString().Contains(".aspx") == true?objMenu.MenuID :
           string.Empty ,
           Dsc = objMenu.Dsc,
};



UserGroups objUserGrp = null;
objUserGrp = objeDC.UserGroups.SingleOrDefault(Rec => Rec.UserGroupID == "stringval");
if (objUserGrp != null)
{
     objeDC.UserGroups.DeleteOnSubmit(objUserGrp);
     objeDC.SubmitChanges();
}
11. Delete multiple records based on condition using LINQ?


objeDC.MenuAccesses.DeleteAllOnSubmit(objeDC.MenuAccesses.Where(Tmpr => Tmpr.MenuID == strMenuID));
objeDC.SubmitChanges();



ex.. Convert Datetime column (MM/dd/YYYY) to dd/MM/yyyy


var objResult = from objTemp in
( from objNewsMast in objeDC.NewsMasts
   select new
   {
       Date = objNewsMast.TimeStamp,
      Title = objNewsMast.Title,
    }).ToList()
select new
{
    Date = objTemp.Date.ToString("dd/MM/yyyy"),
   Title = objTemp.Title,
});

13. convert LINQ Results to DataTable


var ResultProgram = from objProgram in objeDC.Programs
         select objProgram;
         DataTable dtProgram = LINQToDataTable(ResultProgram);

14. LINQ to DataTable
public DataTable LINQToDataTable<T>(IEnumerable<T> varlist)
{
      DataTable dtReturn = new DataTable();
       PropertyInfo[] oProps = null;
       if (varlist == null) return dtReturn;
          foreach (T rec in varlist)
         {
          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;
}



 
12. Format the retrieve column using LINQ)
10. Delete a record using LINQ?
9. Check the column value having specified characters using LINQ?
8. Bind into gridview using LINQ?
7. Bind into DropdownList using LINQ?
6. Update Single value to particular record using LINQ
3. Encrpted Password
2. insert Values into table using LINQ?

'Button1_Click' and no extension method 'Button1_Click' accepting a first argument of type 'ASP.feedback_aspx'

'ASP.feedback_aspx' does not contain a definition for 'Button1_Click' and no extension method 'Button1_Click' accepting a first argument of type 'ASP.feedback_aspx' could be found (are you missing a using directive or an assembly reference?)

Ans: After Delete the button and buttonl_Click event , it will thrown the above error while building because you didn't properly saved the file.

Save that file and rebuild the solution.

Wednesday, August 11, 2010

Partitioning Operators

Partitioning Operators are

1. Take
2. Skip
3. TakeWhile
4. SkipWhile

Example SQL Table is UserMsts

Fields  : UserMstID, Name, EMail, CreateBy, CreateDate , Address

1. Take Simple Query

var Result = from objUserMst in UserMsts

select objUserMst;
foreach (var n in Result.Take(8))
Console.WriteLine (n.UserMstID + n.Name );
This Query uses Take to get only the first 8 records.

2. Skip

var Result = from objUserMst in UserMsts
         select objUserMst;
foreach (var n in Result.Skip(3))
Console.WriteLine ("UserId="+n.UserMstID + "; Name = "+ n.Name );
This Query uses to SKIP first three record and retrieve rest of the records.

3. Retrieve records from 10 - 20 for the following results

                Records
UserId=
UserId=admin
UserId=AZIZUL
UserId=D00281-000
UserId=D00304-000
UserId=D00611-000
UserId=D01619-000
UserId=D01745-000
UserId=D02669-000
UserId=D02670-0001
UserId=D02673-000
UserId=D02684-000
UserId=D02940-000
UserId=D03002-000
UserId=D03252-000
UserId=D06124-000
UserId=D09533-000
UserId=D09999-001
UserId=D10051-001
UserId=D10059-000
UserId=D11719-000
UserId=D12345-000
UserId=D99999-000
UserId=d99999-999
UserId=DAVID
UserId=Jason
UserId=mradmin
UserId=SOW
UserId=tech_it
UserId=TEST
UserId=test1
UserId=testing
UserId=Testing1
Query:
                   var Result = from objUserMst in UserMsts

select objUserMst;
foreach (var n in Result.Skip(10).Take(10))
Console.WriteLine ("UserId="+n.UserMstID );
Results:


UserId=D02673-000

UserId=D02684-000
UserId=D02940-000
UserId=D03002-000
UserId=D03252-000
UserId=D06124-000
UserId=D09533-000
UserId=D09999-001
UserId=D10051-001
UserId=D10059-000
4. TakeWhile

int[] numArray = { 1235, 4456, 1234, 3232, 1900, 80000, 6234, 7123, 2343,0 };

var FindNumbers = numArray.TakeWhile(n => n < 3232);
foreach (var objFindNumbers in FindNumbers)
{
Console.WriteLine(objFindNumbers);
}
         The above query  TakeWhile to return elements starting from the beginning of the array whether the given(3232)  number is hit and retrieved less than 3232 numbers from the array


Output:

1235

Generate Password using C#

public string GeneratePassword()

{
Random rndNumber = null;
        char[] chars = null;
try

{

int passwordLength = 8;

string allowedChars = "abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ123456789";
chars = new char[passwordLength];

rndNumber = new Random();

for (int i = 0; i < passwordLength; i++)

{



chars[i] = allowedChars[rndNumber.Next(0, allowedChars.Length)];

}

}

catch

{

throw;

}

return new string(chars);

}

Monday, July 26, 2010

Gifts

DotNetFunda:

DotNetfunda

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); }

Dot-Net Programming Tips: Dyamically set User Name , Password for crystal report.

Dot-Net Programming Tips: Dyamically set User Name , Password for crystal report.

Dyamically set User Name , Password for crystal report.

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).ApplyLogOnInfo(Logoninfo)
myReportDocument.VerifyDatabase()

Monday, February 22, 2010

Several Ways Redirect to Another Page

Hyperlinks

Performs new request on the target page.
Does not pass current page information to the target page.
Requires user initiation.
Redirects to any page, not just pages in the same Web application.
Enables you to share information between pages using query string or session
state.

Cross-page posting
Posts current page information to the target page.
Makes post information available in the target page.
Requires user initiation.
Redirects to any page, not just pages in the same Web application.
Enables the target page to read public properties of the source page if the pages are in the same Web application.
To pass current page information to the target page (as in multi-page forms).
When navigation should be under user control.

Browser redirect
Performs a new HTTP GET request on the target page.
Passes the query string (if any) to the target page. In Internet Explorer, the size of the query string is limited to 2,048 characters.
Provides programmatic and dynamic control over the target URL and query string.
Enables you to redirect to any page, not just pages in the same Web application.
Enables you to share information between source and target pages using session state.
For conditional navigation, when you want to control the target URL and control when navigation takes place. For example, use this option if the application must determine which page to navigate to based on data provided by the user.

Server transfer
Transfers control to a new page that renders in place of the source page.
Redirects only to target pages that are in the same Web application as the source page.
Enables you to read values and public properties from source page.
Does not update browser information with information about the target page. Pressing the refresh or back buttons in the browser can result in unexpected behavior.
For conditional navigation, when you want to control when navigation takes place and you want access to the context of the source page.
Best used in situations where the URL is hidden from the user.

Wednesday, February 10, 2010

Detect Javascript is enabled in ASPX programmatically

if (Session["Flag"] == null)
{
Session["Flag"] = "Checked";
string path = Request.Url + "?temp=1";
Page.ClientScript.RegisterStartupScript(this.GetType(), "redirect",
"window.location.href='" + path + "';", true);
}
if (Request.QueryString["temp"] == null)
Response.Write("JavaScript is not enabled.");
else
Response.Write("JavaScript is enabled.");

Monday, February 1, 2010

Could not find the visual SourceSafe internet web service connection information. SourceSafe web service cannot be accessed.

Could not find the visual SourceSafe internet web service connection information. SourceSafe web service cannot be accessed.


Solution:

Visual Studio -> Tools -> options -> Choose Source Control and Plug-in Selection.

Switch Back to Microsoft Visual SourceSafe instead of Microsoft Visual SourceSafe(Interenet);

Saturday, January 16, 2010

Multi Language Support


Use Global Resources for your page text and controls based on the user’s language. 


Basics
  1. A Resource file(.resx) stores values.
  2. Manually indicate that controls should use resources for their property value
  3. At run-time, the controls property values are derived from the resource file.

Steps

  1. In Solution Explorer, right click the root of your web site , Click Add ASP.NET Folder and then click App_GlobalResources..
             




  1. Right-Click the App_GlobalResources folder, and then click Add New Item
  2. Choose Resource templates , Name box , type MultiLanguage.resx and click Add.
  3. Open the MultiLanguage.resx file
  4. First row under the Name column type Login  and Value Column type Login
       6 . Create for resource file for Chinese and Malay language in the name of  MultiLanguage.zh-SG.resx  and MultiLanguage.ms-MY.resx
       7. Enter the all the corresponding values.







Now you have created three values for the resource. At runtime, ASP.Net will read the value based on what language user selected.

     8. Add Label Control to the page


1.    Default.aspx and switch to design mode, drag label control into the page
2.    Right-Click the Label control , click properties and then click the ellipsis(..)button in the expression box.The Expressions dialog box appears
3. In the Bindable Properties list, click Text.
4. In the Expression Type Lost, Select Resources.
5. Expression Properties, Set ClassKey to MultiLanguage and ResourceKey to Username , click Ok.
6. Assign for all Control.




Chinese Link Button Event



Session["Language"] = "zh-SG";
Response.Redirect("Default.aspx");



Malay Link Button Event



  Session["Language"] = "ms-MY";
  Response.Redirect("Default.aspx");



Add the below function in every page



protected override void InitializeCulture()
    {
String str = (String)Session["Language"];
        if (str != null)
        {
            String selectedLanguage = str;
            UICulture = selectedLanguage;
            Culture = selectedLanguage;

            Thread.CurrentThread.CurrentCulture =
                CultureInfo.CreateSpecificCulture(selectedLanguage);
            Thread.CurrentThread.CurrentUICulture = new
                CultureInfo(selectedLanguage);
        }
        else
        {
            base.InitializeCulture();
        }

}




Write the InitializeCulture function in separate file and call that file.

MultiLanguage.cs

using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Globalization;
using System.Threading;

///
/// Summary description for MultiLanguage
///
public class MultiLanguage : System.Web.UI.Page
{
      public MultiLanguage()
      {
            //
            // TODO: Add constructor logic here
            //
      }
  
    
    public void fnSupportMultiLanguage()
    {
        String str = (String)Session["Language"];
        if (str != null)
        {
            String selectedLanguage = str;
            UICulture = selectedLanguage;
            Culture = selectedLanguage;

            Thread.CurrentThread.CurrentCulture =
                CultureInfo.CreateSpecificCulture(selectedLanguage);
            Thread.CurrentThread.CurrentUICulture = new
                CultureInfo(selectedLanguage);
        }
        else
        {
            base.InitializeCulture();
        }
     
    }
   
}

In Aspx Page

protected override void InitializeCulture()
    {

        MultiLanguage ml = new MultiLanguage();
        ml.fnSupportMultiLanguage();
    }