Search This Blog

Monday, August 30, 2010

Change Color-TextBox Focus

<script type ="text/javascript">
function Change(obj, evt)
{
if(evt.type=="focus")
obj.style.background ="Yellow";
else if(evt.type=="blur")
obj.style.background ="White";
}

</script>
----------------------------------------------------------------------
< asp:TextBox ID="TextBox1" runat="server" onfocus ="Change(this, event)" onblur ="Change(this, event)"> </asp:TextBox >
< asp:TextBox ID="TextBox2" runat="server" onfocus ="Change(this, event)" onblur ="Change(this, event)"> </asp:TextBox>

what is the difference between property and variable

what is the difference between property and variable, why can't we
just use variable in a class implementation.
Actually my question is variable and methods are enough. Property seems to
be reductant ?

First of all, you should never expose a member variable directly. Always
make it private which is a standard OOP principle. Otherwise you weaken
encapsulation by exposing your object's implementation to the outside world.
Imagine if you decide to change how your object works later on for instance,
say, by changing your variable to some other incompatible type. You would
then break all existing clients of your object which would need to be fixed
in order to accomodate your change. A "get" and/or "set" function wrapping
your variable is the usually remedy for this (allowing you to change things
without breaking clients). However, a property is a high-level, built-in
construct designed explicitly for this purpose. It's much cleaner than using
a "get" and/or "set" function IOW. Not only does it instantly convey its
intended purpose to other readers (improving your code's legibility), but
it's also specifically recognized by different tools, controls, etc. For
instance, you can pass an object to the native "PropertyGrid" control and it
will automatically populate the control with all properties in your object.
It can only do this however because it's able to identify a "property"
unlike an arbitrary "get" and/or "set" function. This is how the Windows
forms designer works in Visual Studio for instance. Note BTW that a property
need not deal with member variables at all. It can do anything it wants,
calculating your property on-the-fly if you wish (though it's normally
better to avoid this unless the calculation is extremely simple).
--------------------------------------------------------------------------------------------------
Properties are more maintainable than fields. Some properties do not have the equivalent field - you need to write some code to set/get them.

Simple example: say you have a car object. It has a mileage and a gallons as fields. You can make a property MPG by dividing these fields. Notice that there is no MPG field inside an object - you do it on the fly by using a property. And that property is read-only - you cannot set it. It can only be changed by changing mileage field or gallons field.

From the other hand - the critical code path (large loops, for example) should avoid using a lot of properties or get the properties once before the loop.

Sunday, August 29, 2010

Registration Page.aspx

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

< !DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

< html xmlns="http://www.w3.org/1999/xhtml">
< head runat="server">
< title> Untitled Page< /title>
< script language="javascript" type="text/javascript">
function SetFocusOnPhone(PreviousControl, NextControl)
{
if(document.getElementById(PreviousControl).value.length > =3)
{
document.getElementById(NextControl).focus();
}
}


function Validate(sender,args)
{
var txt1 = document.getElementById("txtPhone1");
var txt2 = document.getElementById("txtPhone2");
var txt3 = document.getElementById("txtPhone3");

if((txt1.value == "") || (txt2.value == "") || (txt3.value == ""))
{
return args.IsValid = false;
}
else{
return args.IsValid = true;
}

}

function Validateddl(sender, args)
{
var str = new String();
str = args.Value;

if (str == "0") {
args.IsValid = false;

}
else {
args.IsValid = true;
}
}
< /script>
< /head>
< body>
< form id="form1" runat="server">

< asp:ScriptManager ID="sptMgrLogin" runat="server" EnablePageMethods="true">
< /asp:ScriptManager>

< table>
< tr>
< td>
 
< /td>
< /tr>
< tr>
< td>
< span class=""> * First Name < /span>
< /td>
< td>
< asp:TextBox ID="txtFirstName" runat="server" MaxLength="25" TabIndex ="1"> < /asp:TextBox>
< asp:RequiredFieldValidator ID="reqFirstName" runat="server" ControlToValidate="txtFirstName"
Display="None" EnableClientScript="true" ErrorMessage="Please enter first name"
ForeColor="#00f6ff" SetFocusOnError="true">
< /asp:RequiredFieldValidator>
< cc1:ValidatorCalloutExtender ID="validfirstname" runat="server" HighlightCssClass="validatorCalloutHighlight"
TargetControlID="reqFirstName">
< /cc1:ValidatorCalloutExtender>
< /td>
< /tr>
< tr>
< td>
< span class=""> * Last name < /span>
< /td>
< td>
< asp:TextBox ID="txtLastName" runat="server" MaxLength="25" TabIndex="2"> < /asp:TextBox>
< asp:RequiredFieldValidator ID="reqlastname" runat="server"
ControlToValidate="txtLastName" Display="None" EnableClientScript="true"
ErrorMessage="Please enter last name" ForeColor="#00f6ff"
SetFocusOnError="true">
< /asp:RequiredFieldValidator>
< cc1:ValidatorCalloutExtender ID="validextendlastname" runat="server"
HighlightCssClass="validatorCalloutHighlight" TargetControlID="reqlastname">
< /cc1:ValidatorCalloutExtender>
< /td>
< /tr>
< tr>
< td>
< span class=""> * School < /span>
< /td>
< td>
< asp:DropDownList ID="ddlSchool" runat="server" Width="90px" TabIndex="3" AutoPostBack="True">
< asp:ListItem Value="0" Text="Select"> < /asp:ListItem>
< asp:ListItem Value="1"> St.Francis< /asp:ListItem>
< asp:ListItem Value="2"> Pauls< /asp:ListItem>
< asp:ListItem Value="3"> St.Joseph< /asp:ListItem>
< /asp:DropDownList>
< asp:RequiredFieldValidator ID="reqSchool" runat="server"
ControlToValidate="ddlSchool" Display="None" EnableClientScript="true"

SetFocusOnError="true">
< /asp:RequiredFieldValidator>
< asp:CustomValidator ID="cvddlSchoolName" ControlToValidate="ddlSchool" ClientValidationFunction="Validateddl"
Display="None" OnServerValidate="ValidateDropdown" runat="server" ErrorMessage="Please select school name"
SetFocusOnError="true"> < /asp:CustomValidator>

< cc1:ValidatorCalloutExtender ID="ValidatorCalloutExtender8" runat="server"
HighlightCssClass="validatorCalloutHighlight" TargetControlID="cvddlSchoolName">
< /cc1:ValidatorCalloutExtender>

< /td>
< /tr>
< tr>
< td>
< span class=""> * User Name < /span>
< /td>
< td>
< asp:TextBox ID="txtUserName" runat="server" MaxLength="15" TabIndex="4"> < /asp:TextBox>
< asp:RequiredFieldValidator ID="reqUser" runat="server"
ControlToValidate="txtUserName" Display="None" EnableClientScript="true"
ErrorMessage="Please enter user name"
SetFocusOnError="true">
< /asp:RequiredFieldValidator>
< cc1:ValidatorCalloutExtender ID="ValidatorCalloutExtender6" runat="server"
HighlightCssClass="validatorCalloutHighlight" TargetControlID="reqUser">
< /cc1:ValidatorCalloutExtender>
< /td>
< /tr>
< tr>
< td>
< span class=""> < /span> * Password
< /td>
< td>
< asp:TextBox ID="txtPassword" runat="server" TextMode="Password" MaxLength="15" TabIndex="5"> < /asp:TextBox>
< asp:RequiredFieldValidator ID="reqPassword" runat="server"
ControlToValidate="txtPassword" EnableClientScript="true"
ErrorMessage="Please enter password" SetFocusOnError="true" Display="None">
< /asp:RequiredFieldValidator>
< cc1:ValidatorCalloutExtender ID="ValidatorCalloutExtender1" runat="server"
HighlightCssClass="validatorCalloutHighlight" TargetControlID="reqPassword">
< /cc1:ValidatorCalloutExtender>
< /td>
< /tr>
< tr>
< td>
< span class=""> < /span> * E-mail
< /td>
< td>
< asp:TextBox ID="txtEmail" runat="server" MaxLength="50" TabIndex="6"> < /asp:TextBox>
< asp:RequiredFieldValidator ID="reqEmail" runat="server"
ControlToValidate="txtEmail" Display="None" EnableClientScript="true"
ErrorMessage="Please enter e-mail" ForeColor="#00f6ff" SetFocusOnError="true">
< /asp:RequiredFieldValidator>
< asp:RegularExpressionValidator ID="regEmail" runat="server"
ControlToValidate="txtEmail" Display="None" EnableClientScript="true"
ErrorMessage="Please enter valid e-mail" ForeColor="#00f6ff"
ValidationExpression="\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*"> < /asp:RegularExpressionValidator>
< cc1:ValidatorCalloutExtender ID="ValidatorCalloutExtender3" runat="server"
HighlightCssClass="validatorCalloutHighlight" TargetControlID="reqEmail">
< /cc1:ValidatorCalloutExtender>
< cc1:ValidatorCalloutExtender ID="ValidatorCalloutExtender7" runat="server"
HighlightCssClass="validatorCalloutHighlight" TargetControlID="regEmail">
< /cc1:ValidatorCalloutExtender>
< /td>
< /tr>
< tr>
< td>
< span class=""> < /span> * Phone Number
< /td>
< td >
(< asp:TextBox ID="txtPhone1" runat="server" MaxLength="3" Width="30PX"
onkeyup="SetFocusOnPhone('txtPhone1','txtPhone2')" TabIndex="7">
< /asp:TextBox> )
< span style="padding-left: 5px;"> -< /span>
< asp:TextBox ID="txtPhone2" runat="server" MaxLength="3"
onkeyup="SetFocusOnPhone('txtPhone2','txtPhone3')" Width="30PX" TabIndex="8" > < /asp:TextBox>
< span style="padding-left: 5px;"> -< /span>
< asp:TextBox ID="txtPhone3" runat="server" MaxLength="4"
Width="30PX" TabIndex="9" > < /asp:TextBox>
< asp:RequiredFieldValidator ID="reqtxtPhon1" runat="server"
ControlToValidate="txtPhone1" Display="None" EnableClientScript="true"
ErrorMessage="Please enter phone number" SetFocusOnError="true">
< /asp:RequiredFieldValidator>
< asp:RegularExpressionValidator ID="regularExpPhone1" runat="server"
ControlToValidate="txtPhone1" Display="None" EnableClientScript="true"
ErrorMessage="Please enter valid phone format (###)" SetFocusOnError="true"
ValidationExpression="\d{3}"> < /asp:RegularExpressionValidator>
< cc1:FilteredTextBoxExtender ID="FilteredTextBoxExtender12" runat="server"
FilterType="Numbers" TargetControlID="txtPhone1">
< /cc1:FilteredTextBoxExtender>
< cc1:ValidatorCalloutExtender ID="validReqularExprePh" runat="server"
HighlightCssClass="validatorCalloutHighlight"
TargetControlID="regularExpPhone1">
< /cc1:ValidatorCalloutExtender>
< asp:RequiredFieldValidator ID="ReqPhone2" runat="server"
ControlToValidate="txtPhone2" Display="None" EnableClientScript="true"
ErrorMessage="Please enter phone number" ForeColor="#00f6ff"
SetFocusOnError="true"> < /asp:RequiredFieldValidator>
< asp:RegularExpressionValidator ID="reqgularExpPhon2" runat="server"
ControlToValidate="txtPhone2" Display="None" EnableClientScript="true"
ErrorMessage="Please enter valid phone format (###)" ForeColor="#00f6ff"
SetFocusOnError="true" ValidationExpression="\d{3}"> < /asp:RegularExpressionValidator>
< cc1:FilteredTextBoxExtender ID="FilteredTextBoxExtender14" runat="server"
FilterType="Numbers" TargetControlID="txtPhone2">
< /cc1:FilteredTextBoxExtender>
< cc1:ValidatorCalloutExtender ID="validExReguPhone2" runat="server"
HighlightCssClass="validatorCalloutHighlight"
TargetControlID="reqgularExpPhon2">
< /cc1:ValidatorCalloutExtender>
< asp:RequiredFieldValidator ID="reqPhone3" runat="server"
ControlToValidate="txtPhone3" Display="None" EnableClientScript="true"
ErrorMessage="Please enter phone number" ForeColor="#00f6ff"
SetFocusOnError="true"> < /asp:RequiredFieldValidator>
< cc1:ValidatorCalloutExtender ID="ValidatorCalloutExtender4" runat="server"
HighlightCssClass="validatorCalloutHighlight" TargetControlID="reqPhone3">
< /cc1:ValidatorCalloutExtender>
< asp:RegularExpressionValidator ID="regularExpPhon3" runat="server"
ControlToValidate="txtPhone3" Display="None" EnableClientScript="true"
ErrorMessage="Please enter valid phone format (####)" SetFocusOnError="true"
ValidationExpression="\d{4}"> < /asp:RegularExpressionValidator>
< cc1:FilteredTextBoxExtender ID="FilteredTextBoxExtender13" runat="server"
FilterType="Numbers" TargetControlID="txtPhone3">
< /cc1:FilteredTextBoxExtender>
< cc1:ValidatorCalloutExtender ID="ValidatorCalloutExtender5" runat="server"
HighlightCssClass="validatorCalloutHighlight" TargetControlID="regularExpPhon3">
< /cc1:ValidatorCalloutExtender>
< asp:CustomValidator ID="cvPhone" runat="server"
ClientValidationFunction="Validate" ControlToValidate="txtPhone3"
Display="None" EnableClientScript="true"
ErrorMessage="Please enter phone number" OnServerValidate="ValidReqPhone"> < /asp:CustomValidator>
< cc1:ValidatorCalloutExtender ID="valieReqPhone2" runat="server"
HighlightCssClass="validatorCalloutHighlight" TargetControlID="cvPhone">
< /cc1:ValidatorCalloutExtender>
< /td>
< /tr>
< tr>
< td>
< span> < /span> Contact Address
< /td>
< td>
< asp:TextBox ID="txtContactAddress" runat="server" MaxLength="100" TabIndex="10"> < /asp:TextBox>
< /td>
< /tr>
< tr>
< td>
< span class=""> < /span> City
< /td>
< td>
< asp:TextBox ID="txtCity" runat="server" MaxLength="25" TabIndex="11"> < /asp:TextBox>
< /td>
< /tr>
< tr>
< td>
< span class=""> < /span> State
< /td>
< td>
< asp:DropDownList ID="ddlState" runat="server" Width="90px" AutoPostBack="True" TabIndex="12">

< /asp:DropDownList>
< /td>
< /tr>
< tr>
< td>
ZIP< /td>
< td>
< asp:TextBox ID="txtZipCode" runat="server" MaxLength="5" TabIndex="12" > < /asp:TextBox>
< cc1:FilteredTextBoxExtender ID="FilteredTextBoxExtender3" runat="server"
FilterType="Custom" InvalidChars="A-Z, a-z" TargetControlID="txtZipCode"
ValidChars="1,2,3,4,5,6,7,8,9,0">
< /cc1:FilteredTextBoxExtender>
< asp:RegularExpressionValidator ID="regulaExZipCode" runat="server"
ControlToValidate="txtZipCode" Display="None" EnableClientScript="true"
ErrorMessage="Please enter valid ZIP format (#####)" SetFocusOnError="true"
ValidationExpression="\d{5}"> < /asp:RegularExpressionValidator>
< cc1:ValidatorCalloutExtender ID="ValidatorCalloutExtender2" runat="server"
TargetControlID="regulaExZipCode">
< /cc1:ValidatorCalloutExtender>
< /td>
< /tr>
< tr>
< td>
 
< /td>
< /tr>
< tr>
< td>
< asp:ImageButton ID="imbSubmit" runat="server" CausesValidation="True"
ImageUrl="~/images/submitw.gif" onclick="imbSubmit_Click" TabIndex="13"/>
< asp:HiddenField ID="hdnUserId" runat="server" />
< asp:HiddenField ID="hdnOldUserName" runat="server" />
< asp:HiddenField ID="hdnOldEmailId" runat="server" />
< /td>
< /tr>

< /table>
< asp:Label ID="Label4" runat="server" Style="display: none"> < /asp:Label>
< cc1:ModalPopupExtender ID="ModalPopupExtender4" TargetControlID="Label4" CancelControlID="imbOk"
BackgroundCssClass="popupbg" PopupControlID="Div4" runat="server" OnOkScript="OnOK()">
< /cc1:ModalPopupExtender>

< /form>
< /body>
< /html>

-------------------------Server Validate---------------------------------------
protected void ValidateDropdown(object source, ServerValidateEventArgs args)
{
try
{
if (ddlSchool.SelectedValue == "0")
{
args.IsValid = false;
}
else
{
args.IsValid = true;
}
}
catch
{
args.IsValid = false;

}
}
protected void ValidReqPhone(object source, ServerValidateEventArgs args)
{
try
{
if (String.IsNullOrEmpty(txtPhone1.Text) || String.IsNullOrEmpty(txtPhone2.Text) || String.IsNullOrEmpty(txtPhone3.Text))
{
args.IsValid = false;
}
else
{
args.IsValid = true;
}
}
catch
{
args.IsValid = false;

}
}

Mail Sender

using System;
using System.Data;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Text;
using System.Net.Mail;
using System.Collections.Generic;

///
/// Summary description for MailSender
///

public class MailSender
{
public MailSender(string body,string subj)
{

this.Body = body;
this.Subject = subj;
}
public MailSender()
{


}

string _body, _subject;

public string Subject
{
get { return _subject; }
set { _subject = value; }
}

public string Body
{
get { return _body; }
set { _body = value; }
}
public void SendMail(string toAddress)
{

if (toAddress != null && toAddress != string.Empty)
{
MailMessage objmessage = new MailMessage();
objmessage.Priority = MailPriority.High;
objmessage.Subject = Subject;
objmessage.Body = Body;
objmessage.IsBodyHtml = true;
objmessage.From = new MailAddress(Convert.ToString(ConfigurationManager.AppSettings["emailid"]));
objmessage.To.Add(new MailAddress(toAddress));
try
{
SmtpClient objsmtpClient = new SmtpClient();
objsmtpClient.Host = ConfigurationManager.AppSettings["mailserver"].ToString();
objsmtpClient.DeliveryMethod = SmtpDeliveryMethod.PickupDirectoryFromIis;
objsmtpClient.Send(objmessage);
}

catch (SmtpException mailex)
{
throw mailex;
}

}

}
public void SendMail(List addrCollection)
{

if (addrCollection.Count >0)
{
MailMessage objmessage = new MailMessage();
objmessage.Priority = MailPriority.High;
objmessage.Subject = Subject;
objmessage.Body = Body;
objmessage.IsBodyHtml = true;
objmessage.From = new MailAddress(Convert.ToString(ConfigurationManager.AppSettings["emailid"]));


foreach (string item in addrCollection)
{
objmessage.To.Add(new MailAddress(item));
}

try
{
SmtpClient objsmtpClient = new SmtpClient();
objsmtpClient.Host = ConfigurationManager.AppSettings["mailserver"].ToString();
objsmtpClient.DeliveryMethod = SmtpDeliveryMethod.PickupDirectoryFromIis;
objsmtpClient.Send(objmessage);
}

catch (SmtpException mailex)
{
throw mailex;
}

}

}
public void SendMail(string fromAddress,string toAddress)
{

if (toAddress != null && toAddress != string.Empty)
{
MailMessage objmessage = new MailMessage();
objmessage.Priority = MailPriority.High;
objmessage.Subject = Subject;
objmessage.Body = Body;
objmessage.IsBodyHtml = true;
objmessage.From = new MailAddress(fromAddress);
objmessage.To.Add(new MailAddress(toAddress));
try
{
SmtpClient objsmtpClient = new SmtpClient();
objsmtpClient.Host = ConfigurationManager.AppSettings["mailserver"].ToString();
objsmtpClient.DeliveryMethod = SmtpDeliveryMethod.PickupDirectoryFromIis;
objsmtpClient.Send(objmessage);
}

catch (SmtpException mailex)
{
throw mailex;
}

}

}

}

LinQ -SubQuery

var EmpDetails = from comp in ListCompany
select new {
Emp = (from emp in comp.ListEmp
select new {
Company = comp.Name,
emp
})
};
------------------------------------------------------------------
var LessEmp = from Comp in ListCompany
select new {
Comp.Name,
EmpCount = Comp.ListEmp.Count
};
------------------------------------------------------
var EmpInACity = from comp in ListCompany

from emplist in comp.ListEmp
where emplist.Address.City.ToUpper().Contains("BAN")
select new {
CompName = comp.Name,
EmployeeName = emplist.Name
};
--------------------------------------------------------------------
var EmpHighSalEachComp = from comp in ListCompany
from empHigh in comp.ListEmp
where empHigh.salary == comp.ListEmp.Max(
HighEmp => HighEmp.salary)
select new {
CompanyName = comp.Name,
EmpHighName = empHigh.Name,
EmpHighSal = empHigh.salary
};
-----------------------------------------------------------------
var EmpHighSal = from comp in ListCompany
from emp in comp.ListEmp
where emp.salary == ListCompany.Max(
TComp => TComp.ListEmp.Max(HighEmp => HighEmp.salary))
select new {
CompanyName = comp.Name ,
EmployeeName = emp.Name,
EmpSal = emp.salary
};
-------------------------------------------------------------------------
var CompanyCityWise = from comp in ListCompany

from emp in comp.ListEmp
group emp by emp.Address.City into CityWiseEmp
select new {
State = CityWiseEmp.Key,
TotalSalary = CityWiseEmp.Sum(emp => emp.salary)
};
-------------------------------------------------------------------------------
var CityWiseSalary = from comp in ListCompany
select new {
comp.Name,
Emp =(from emp in comp.ListEmp
group emp by emp.Address.City into CityWiseEmp
select new {
State = CityWiseEmp.Key,
TotalSalary = CityWiseEmp.Sum(emp => emp.salary)
})
};

Linq to SharePoint

Linq to SharePoint

SharePoint 2010 has added new Linq extension called Linq-to-SharePoint similar like Linq-to-Sql. In Linq to Sql, when you Visual Studio generate classes based on your database schema, under the hood a tool called SqlMetal is used. Though VS generates classes for you, you can use SqlMetal outside of VS for your own purpose. Linq to SharePoint is new extension which allows to generate DataContext (having classes representing lists) based on your sharepoint lists using SPMetal and you can use the DataContext for manipulating SharePoint list in an object-oriented fashion. So you don’t need to worry about CAML or SharePoint Object Model. The steps to work with Linq-to-SharePoint is easy. Let’s dig it deeper.

1. Generate Linq-to-SharePoint DataContext class: To use Linq to SharePoint you need to use SPMetal to generate Linq-To-SharePoint class. You can find the SPMetal in the location “C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\BIN”. You can run the command from command prompt. For example the following command will generate Linq-to-SharePoint DataContext class for site ‘http://localhost’ and put the code in C:\MyClass.cs file with namespace MyNameSpace.

spmetal /web:http://localhost /code:c:\myclass.cs /namespace:mynamespace

One thing to point here is that there are Visual Studio extension availa to enable developers to generate DataContext from Visual Studio. One such tool is Linq to SharePoint DSL Extension.
2. Add DataContext class to your Visual Studio Project: The file you have generated at step 1 need to add in your Visual Studio Project. To do so you need to add reference to Microsoft.SharePoint.Linq.dll from Visual Studio’s Add Reference windows’ ‘.NET’ tab.
3. Code Using DataContext Class: Now you can use the DataContext class for manipulating SharePoint lists. For example in the following code I have used the DataContext class generated at step 1 to add a new product in the product list.

using (var context = new MyclassDataContext(http://mysite))
{
var item = new ProductItem();
item.AvaialableQuantity = 100;
item.LaunchDate = DateTime.Now;
item.ProductDescription = "this is computer monitor";
item.ProductName = "Monitor";
context.Product.InsertOnSubmit(item);
context.SubmitChanges();
}

4. Suggestion: If you use SPMetal to generate DataContext class then you’ll find that all classes are placed in a single file (in my case MyClass.cs file). This is very difficult to manage and modify. My suggestion will be to modify the file to move classes in individual pages. You can use some Refactoring tools like Resharper.

CAML and Linq side-by-side

You may think CAML is dead now as we can do all operations using Linq to SharePoint. Wait, here few point to notice. Firstly, when you use Linq to SharePoint, under the hood, CAML is used. the Linq to SharePoint convert you expression in CAML. However, you can still use CAML for retriving data from database, then you can use Linq to do operations on returned results. For example, you can use CAML to find products. Then you can run linq query against the result set to perform operations like orderby, group, join etc. As shown in the example below, I have used Linq to SharePoint to query Product list to find items whose name contains monitor and also ordered by available quantity.

using (var context = new MyclassDataContext("http://mysite"))
{
var proudcts = from p in context.Product
where p.ProductName.Contains("monitor")
orderby p.AvaialableQuantity
select p;
}

In the following example, I have used CAML query to perform the same operation I have performed above. In the above example I have used Linq to SharePoint extension fully. But in the following example I have used CAML query first to filter data from database. Then I have run Linq query to order data. The following example doesn’t use Linq to SharePoint. Rather it uses the conventional CAML and C# Linq.

SPList productList = SPContext.Current.Web.Lists["Product"];
SPQuery camlQuery=new SPQuery();
camlQuery.Query = "your CAMl query";

var products = productList.GetItems(camlQuery);
var orderProducts = from p in products.Cast()
where p["ProductName"].ToString().Contains("monitor")
orderby Convert.ToInt32(p["AvaialableQuantity"])
select p;

Saturday, August 28, 2010

Check username with Ajax using PageMethod

Ajax PageMethod

MS AJAX has gone one step further! We can now call methods in the codebehind of the current page from Javascript. Here's how:

Here i am tryin to Check whether the USERNAME Exists in my database.

----- Default.aspx

<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="True" />
<asp:TextBox ID="TxtEventCode" runat="server" CssClass="StyleTextForm"
onblur="usernameChecker(this.value);"></asp:TextBox>
<span id ="spanAvailability"></span>

JavaScript part with the Script tag.

<script type="text/javascript">
var usernameCheckerTimer;
var spanAvailability = $get("spanAvailability");

function usernameChecker(username) {
clearTimeout(usernameCheckerTimer);
if (username == "")
//if (username.length == 0)
spanAvailability.innerHTML = "Code cannot be Blank";
else {
spanAvailability.innerHTML = "checking...";
usernameCheckerTimer = setTimeout("checkUsernameUsage('" + username + "');", 750);
}
}

function checkUsernameUsage(username) {
// initiate the ajax pagemethod call
// upon completion, the OnSucceded callback will be executed
PageMethods.IsUserAvailable(username, OnSucceeded);
}

// Callback function invoked on successful completion of the page method.
function OnSucceeded(result, userContext, methodName) {
if (methodName == "IsUserAvailable") {
if (result == true)
//spanAvailability.innerHTML = "Available";
spanAvailability.innerHTML = "Already Exists";
else
spanAvailability.innerHTML = "Does Not Exist";
}
}
</script>

***** Do not forget to set the EnablePageMethods attribute to true. ******

------- Default.aspx.cs

using System;
using System.Data;
using System.Data.SqlClient;
using System.Web.Services;

namespace CheckUsernameWithAJAX
{
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{

}
using System.Web.Services;

[WebMethod]
public static bool IsUserAvailable(string username)
{
SqlConnection cnn = new SqlConnection("data source=SYSTEMNAME; initial catalog=EVENTMGM; user ID=xxxx; Password=xxxx");
string Sqlstr;
//SqlCommand cmd = new SqlCommand();
//cmd.Connection= cnn;
//cmd.CommandType = CommandType.Text;
Sqlstr="SELECT USERNAME FROM USERLOG WHERE CODE = '" + username + "' ";
SqlDataAdapter da = new SqlDataAdapter(Sqlstr, cnn);
DataSet ds = new DataSet();
da.Fill(ds, "USERLOG");
//cmd.CommandText= Sqlstr;
//cnn.Open();
//int cnt = cmd.ExecuteNonQuery();

//cnn.Close();

if ( ds.Tables["HOTELMAS"].Rows.Count > 0)
return true;
else
return false;

//if (username.ToLower() == "travis")
// return false;
//else
// return true;
}
}
}

IsValidEMail-Check Onblur

Rather than hard-coding your JavaScript into an aspx page, you can store you JavaScript functions in a separate .js file. This allows your furnctions to be used from multiple pages.

For example, you could add a .js file to your project (right-click your project and select Add New Item | JScript File) from the shortcut menu) and place the following function in it:



function isValidEmail(emailAddressControl)

{

var emailPat = /^(\".*\"|[A-Za-z]\w*)@(\[\d{1,3}(\.\d{1,3}){3}]|[A-Za-z]\w*(\.[A-Za-z]\w*)+)$/;

var emailid = emailAddressControl.value;

var matchArray = emailid.match(emailPat);

if (matchArray == null) {

alert("Invalid e-mail address");

emailAddressControl.focus();

return false;

}

return true;

}

In your web form Page_Load, you can add the following code



if (!Page.ClientScript.IsClientScriptIncludeRegistered(typeof(pgOrders), "MyScript"))

{

Page.ClientScript.RegisterClientScriptInclude(typeof(pgOrders), "MyScript", "JScript.js");

}

The call to IsClientScriptIncludeRegistered() checks if the JavaScript file has already been included. The call to RegisterClientScriptInclude() actually registers the script.

From within your .aspx page, you can call this JavaScript function after the user leaves the e-mail field by doing something like this:



<asp:TextBox ID="txtEmail" runat="server" Width="265px" onblur="isValidEmail(this)"></asp:TextBox>




Note: The first parameter of RegisterClientScriptInclude() accepts a type object which it uses to uniquely key the registered script. The MSDN documentation samples for this method use a call to this.GetType() to get the current page type dynamically at runtime--however, this can be a problem if you ever subclass your web page. The call to this.GetType() will return a different class than the class in which this code is actually defined. I's best to specify the actual type of the page itself by doing something like this:



typeof(pgOrders)

In this example, pgOrders is the actual type of the page in which the JavaScript is being included. This works better, because you are statically typing the reference to the page at compile time rather than dynamically determining the type of the page at runtime.

Logout Button - Avoid Back Button

we sometime face problem of back button that after logout then if we click back button then we able access those pages those already visited and that page always require login Session so if click on button go to login page.Here i will give the code even if you click back button after logout you will remain in same page after you click back button.
if you click logout button go to login page and then click back button you will be same login page if you use this code.Use this code onclick of logout button.
logout button
--------------------
Session.clear();//clear session
Session.Abandon();//Abandon session
Response.Cache.SetExpires(DateTime.UtcNow.AddMinutes(-1));
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.Cache.SetNoStore();Response.Redirect("Logout.aspx");

Add Page Load with postback
--------------------------------
Response.Buffer = true;
Response.ExpiresAbsolute = DateTime.Now.AddDays(-1d);
Response.Expires = -1500;
Response.CacheControl = "no-cache";


2.IE-Browser Head Tag
apply head tag
----------------
<meta http-equiv="Page-Enter" content="blendTrans(Duration=1.5)" />

Already Exist-SQL

private Boolean exists()
{
SqlConnection conn = new SqlConnection("your Connectionstring");
SqlCommand cmd = new SqlCommand("Select Count(*) from DSusers where Username = @Username", conn);
SqlDataReader sReader = null;
Int32 numberOfRows = 0;

try
{
conn.Open();
sReader = cmd.ExecuteReader();

while (sReader.Read())
{
if (!(sReader.IsDBNull(0)))
{
numberOfRows = Convert.ToInt32(sReader[0]);
if (numberOfRows > 0)
{
return true;
}
}
}
}
catch (Exception ex)
{

throw ex;
}
finally
{
conn.Close();
}
return false;
}

Validation for numeric value-JavaScript

function IsNumeric(strString)
// check for valid numeric strings
{
var strValidChars = "0123456789.-";
var strChar;
var blnResult = true;

if (strString.length == 0) return false;

// test strString consists of valid characters listed above
for (i = 0; i < strString.length && blnResult == true; i++)
{
strChar = strString.charAt(i);
if (strValidChars.indexOf(strChar) == -1)
{
blnResult = false;
}
}
return blnResult;
}
**********************************
function NumbersOnly(e)
{
var unicode=e.charCode? e.charCode : e.keyCode
if (unicode<48||unicode>57)
return false

}
***************************************
U can use the below javascript:

function valInteger(obj)
{
var i,strVal,blnChange;
blnChange = false
strVal="";

for(i=0;i<(obj.value).length;i++)
{
switch(obj.value.charAt(i))
{
case "0":
case "1":
case "2":
case "3":
case "4":
case "5":
case "6":
case "7":
case "8":
case "9":strVal=strVal+obj.value.charAt(i);
break;
default :blnChange = true;
break;
}
}
if (blnChange)
{
obj.value=strVal;
}
}

Page ,for that textbox'a keyup give like this

onkeyup="return valInteger(this)"

Thursday, August 19, 2010

Add validation to business objects(using abstract)

Add validation to business objects
Recently, I had to implement validation on business objects in an already existing project. The validation should ensure that the different classes in the business object tier would validate them selves based on business rules. One of the rules on the Product class was that the Price property never must be negative and the Name property must be at least one character long.
For some reason I don’t know, none of these validation checks was made and I had to find a simple way to implement the checks without changing the original code too much. I’m a big fan of Rockford Lhotka’s CSLA.NET framework which has a nice way of doing validation, so I used that as an inspiration.
In the spirit of CSLA.NET I wanted the boolean read-only property IsValid, that tells whether or not the object is valid or not. I also wanted a read-only property called ValidationMessage, which tells what rules are broke and how to correct them.
The business objects didn’t have a base class, so I decided to create one and add as much of the validation code there. Here is that abstract class called ValidationBase:
using System;
using System.Text;
using System.Collections.Specialized;

public abstract class ValidationBase
{

private StringDictionary _BrokenRules = new StringDictionary();

///
/// Add or remove a broken rule.
///

/// The name of the property.
/// The description of the error
/// True if the validation rule is broken.
protected void AddRule(string propertyName, string errorMessage, bool isBroken)
{
if (isBroken)
{
_BrokenRules[propertyName] = errorMessage;
}
else
{
if (_BrokenRules.ContainsKey(propertyName))
{
_BrokenRules.Remove(propertyName);
}
}
}

///
/// Reinforces the business rules by adding rules to the
/// broken rules collection.
///

protected abstract void Validate();

///
/// Gets whether the object is valid or not.
///

public bool IsValid
{
get
{
Validate();
return this._BrokenRules.Count == 0;
}
}

/// ///
/// If the object has broken business rules, use this property to get access
/// to the different validation messages.
///

public string ValidationMessage
{
get
{
StringBuilder sb = new StringBuilder();
foreach (string messages in this._BrokenRules.Values)
{
sb.AppendLine(messages);
}

return sb.ToString();
}
}

}
Then I hade to change all the business object so they derived from ValidationBase and implement the Validate() method on each of them. That’s all the work needed in order to start using the IsValid property. Here’s a dummy example of a derived class that uses the validation feature in its Save() method:
using System;

public class Product : ValidationBase
{
#region Poperties

private int _Price;

public int Price
{
get { return _Price; }
set { _Price = value; }
}

private string _Name;

public string Name
{
get { return _Name; }
set { _Name = value; }
}

#endregion

#region Methods

public void Save()
{
// Only save if the object is valid,
// otherwise throw an exception.
if (IsValid)
{
DoSomething();
}
else
{
throw new Exception(ValidationMessage);
}
}

#endregion

#region Validation

///
/// Reinforces the business rules by adding rules to the
/// broken rules collection.
///

protected override void Validate()
{
AddRule("Price", "Price must be greater than or equal to 0", this.Price < 0);
AddRule("Name", "Name must be set", string.IsNullOrEmpty(this.Name));
}

#endregion
}
It became a very simple implementation in the derived classes that didn’t demand any big changes to the original code.

Check Valid Date

protected bool CheckDate(String date)
{
DateTime Temp;
if (DateTime.TryParse(date, out Temp) == true )
return true;
else
return false;
}
-----------------------------------------
protected bool CheckDate(String fromdate, string enddate)
{
DateTime Temp;
DateTime Temp1;
if (DateTime.TryParse(fromdate, out Temp) == true && DateTime.TryParse(enddate, out Temp1) == true)
return true;
else
return false;
}

Set Max Length From -MultiLine TextBox(asp.net)

function checkTextAreaMaxLength(textBox,e, length)
{

var mLen = textBox["MaxLength"];
if(null==mLen)
mLen=length;

var maxLength = parseInt(mLen);
if(!checkSpecialKeys(e))
{
if(textBox.value.length > maxLength-1)
{
if(window.event)//IE
e.returnValue = false;
else//Firefox
e.preventDefault();
}
}
}
function checkSpecialKeys(e)
{
if(e.keyCode !=8 && e.keyCode!=46 && e.keyCode!=37 && e.keyCode!=38 && e.keyCode!=39 && e.keyCode!=40)
return false;
else
return true;
}
maxL=200;
var bName = navigator.appName;
function taLimit(taObj) {
if (taObj.value.length==maxL) return false;
return true;
}

function taCount(taObj,Cnt) {
objCnt=createObject(Cnt);
objVal=taObj.value;
if (objVal.length>maxL) objVal=objVal.substring(0,maxL);
if (objCnt) {
if(bName == "Netscape"){
objCnt.textContent=maxL-objVal.length;}
else{objCnt.innerText=maxL-objVal.length;}
}
return true;
}
function createObject(objId) {
if (document.getElementById) return document.getElementById(objId);
else if (document.layers) return eval("document." + objId);
else if (document.all) return eval("document.all." + objId);
else return eval("document." + objId);
}

----------------------------------example-----------
TextBox ID="txtReason" onKeyPress="return taLimit(this)" onKeyUp="return taCount(this,'myCounter')" ToolTip="Please enter reason" onkeyDown="checkTextAreaMaxLength(this,event,'200');" CssClass="textbox2" runat="server" TextMode="MultiLine"


You have SPAN id=myCounter-200-SPAN characters remaining
for your description.