Monday 31 December 2012

MVC Validation



 var currentAddress = bingRepository.ToDatabaseAddress(model.CurrentAddress, LocationTypes.Current, out errorString);

//If currentAddress is null and error message value was found, set error in errorstring.then add below lines

                if (!string.IsNullOrEmpty(errorString))
                {
                    string wrongAddressErrorString = errorString;
                    ModelStateDictionary modelState = new ModelStateDictionary();
                    modelState.AddModelError(string.Empty, string.IsNullOrWhiteSpace(wrongAddressErrorString) ? "Not  update error" : wrongAddressErrorString);
                    return false;
                }



Back button


This code will not work if javascript is disabled,but most of the browsers supports javascript.

1. Write this script
  <script language="javascript" type="text/javascript">
    function Back()
    {
        history.go(-1);
        return false;
    }

  </script>


2. Now in Button click

//<input type="submit" name="btnEdit" value="Back" onclick="return Back();" id="btnEdit" class="buttonstyle" />///

how to change gridview cell color

Here is the code for that 
       

  <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
        DataKeyNames="ID" DataSourceID="AccessDataSource1"
        ondatabound="GridView1_DataBound" onrowdatabound="GridView1_RowDataBound">
        <Columns>
            <asp:BoundField DataField="ID" HeaderText="ID" InsertVisible="False"
                ReadOnly="True" SortExpression="ID" />
            <asp:BoundField DataField="Title" HeaderText="Title" SortExpression="Title" />
            <asp:BoundField DataField="Location" HeaderText="Location"
                SortExpression="Location" />
            <asp:BoundField DataField="ParentID" HeaderText="ParentID"
                SortExpression="ParentID" />
            <asp:BoundField DataField="Content" HeaderText="Content"
                SortExpression="Content" />
            <asp:BoundField DataField="ShortContent" HeaderText="ShortContent"
                SortExpression="ShortContent" />
            <asp:TemplateField HeaderText="Status" ControlStyle-Width="75px" >
                <ItemTemplate>
                    <asp:Label ID="Label1" runat="server" Text='<%# Eval("ParentID") %>'></asp:Label>
                </ItemTemplate>
            </asp:TemplateField>
        </Columns>
    </asp:GridView>
    <asp:AccessDataSource ID="AccessDataSource1" runat="server"
        DataFile="App_Data/Database1.accdb" SelectCommand="SELECT CMSMenus.ID, CMSMenus.Title, CMSMenus.Location, CMSMenus.ParentID, CMSMenus.Content, CMSMenus.ShortContent
FROM CMSMenus;
">
    </asp:AccessDataSource>


For Code behind here is the code behind I coloured the cells depends on column ParentID value you can choose your own

  protected void GridView1_DataBound(object sender, EventArgs e)
    {
        for (int i =0 ; i <= GridView1.Rows.Count -1 ;i++)
        {
            Label lblparent = (Label)GridView1.Rows[i].FindControl("Label1");

            if (lblparent.Text == "1")
            {
                GridView1.Rows[i].Cells[6].BackColor = Color.Yellow;
                lblparent.ForeColor = Color.Black;
            }
            else
            {
                GridView1.Rows[i].Cells[6].BackColor = Color.Green;
                lblparent.ForeColor = Color.Yellow;
            }
                
        }
    }

Sunday 30 December 2012

Session


Sessions can be used to store even complex data for the user just like cookies. Actually, sessions will use cookies to store the data, unless you explicitly tell it not to. Sessions can be used easily in ASP.NET with the Session object. We will re-use the cookie example, and use sessions instead. Keep in mind though, that sessions will expire after a certain amount of minutes, as configured in the web.config file. Markup code:
<%@ Page Language="C#" AutoEventWireup="true"  CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!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>Sessions</title>
</head>
<body runat="server" id="BodyTag">
    <form id="form1" runat="server">
    <asp:DropDownList runat="server" id="ColorSelector" autopostback="true" onselectedindexchanged="ColorSelector_IndexChanged">
        <asp:ListItem value="White" selected="True">Select color...</asp:ListItem>
        <asp:ListItem value="Red">Red</asp:ListItem>
        <asp:ListItem value="Green">Green</asp:ListItem>
        <asp:ListItem value="Blue">Blue</asp:ListItem>
    </asp:DropDownList>
    </form>
</body>
</html>
And here is the CodeBehind:
using System;
using System.Data;
using System.Web;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if(Session["BackgroundColor"] != null)
        {
            ColorSelector.SelectedValue = Session["BackgroundColor"].ToString();
            BodyTag.Style["background-color"] = ColorSelector.SelectedValue;
        }
    }

    protected void ColorSelector_IndexChanged(object sender, EventArgs e)
    {
        BodyTag.Style["background-color"] = ColorSelector.SelectedValue;
        Session["BackgroundColor"] = ColorSelector.SelectedValue;
    }
}
As you can see, the example doesn't need a lot of changes to use sessions instead of cookies. Please notice that session values are tied to an instance of your browser. If you close down the browser, the saved value(s) will usually be "lost".

The if block is missing a closing "}" character. Make sure you have a matching "}" character for all the "{" characters within this block, and that none of the "}" characters are being interpreted as markup.


Many time some people ask this question in asp.net forums.
for
Error: The if block is missing a closing "}" character.  Make sure you have a matching "}" character for all the "{" characters within this block, and that none of the "}" characters are being interpreted as markup.

@model IEnumerable<GuestbookApp.Models.Guestbook>
@{
    ViewBag.Title = "Guestbook";
}

<h2>Guestbook</h2>
@Html.ActionLink("Sign Guestbook", "Sign")
<hr />
@if (ViewBag.Result != null)
{
    if (ViewBag.Result == "success")
    {
        <div style="border: 1px #138b0e solid; background-color: #deffe0">
    }
    else
    {
        <div style="border: 1px #ff6a00 solid; background-color: #fcc7c7">
    }
        @ViewBag.Msg
    </div>
}
<table border="0" cellpadding="4" cellspacing="2">

...Where did I go wrong? that's the right if-else statement right? or is there I miss in Razor rules? Please help.. thanks..


How to solve??


Solving code
add this @: in front of div(or any)  open and close tag in used if conditions.

for above code issu was solved by,watch below

 if (ViewBag.Result == "success")
    {
        @:<div style="border: 1px #138b0e solid; background-color: #deffe0">
    }
    else
    {
       @:<div style="border: 1px #ff6a00 solid; background-color: #fcc7c7">
    }
        @ViewBag.Msg
    @:</div>

and all of you must refer this

Image Viewer in C#


DescriptionThis program allows you to open and view image files including JPEG, GIF, WMF and other images. Program also provides options to stretch and shrink them, rotate at different angles through all axes and save them in different formats.This example uses menus, radio buttons, group boxes, open and save dialog boxes, picture box and status bar controls.Compiling Code with Visual Studio .NETTo compile and execute code with VS.NET, create a Windows application and copy and paste this code in Form1.cs class. Replace all code from Form1.cs accept namespace includes.
using System;using System.Windows.Forms;
using System.Drawing;
using System.Text;
using System.Drawing.Imaging;
using System.IO;
public class win:Form 
{
Stream stm;
Panel pnlTop;
StatusBar stbBtm;
Label lblPicMode;
MainMenu mnuMain;PictureBox pbxImg;
bool blnPicLoaded;
ComboBox cmbPicMode;
OpenFileDialog dlgFile;
Button btnTransform,btnOrg;
GroupBox gpbRotate,gpbFlip;
MenuItem mnuFile, mnuOpen, mnuSave, mnuExit, mnuSep;
String strImgName,strRot,strFlip,strRotFlip,strStatus;
RadioButton bnRotNone,rbnRotX,rbnRotY,rbnRotXY,rbnFlipNone,rbnFlip90,rbnFlip180,rbnFlip270,rbnTemp;
public win()
{
try{
this.Text="Images";
pnlTop=new Panel();
this.Size=new Size(770,570);
this.Controls.Add(pnlTop);
this.Menu=fncBuildMenus();
setControls();
strRot=rbnRotNone.Name;
strFlip=rbnFlipNone.Name;
pnlTop.Location = new Point(0,0);
pnlTop.Size = new Size(750,500);
}
catch (Exception e)
{
Console.WriteLine("error .... " + e.StackTrace);
}
}
private static void Main()
{
Application.Run(new win());
}
private MainMenu fncBuildMenus()
{
/* build the menu's */mnuMain=new MainMenu();
mnuFile=new MenuItem();
mnuOpen=new MenuItem();
mnuSave=new MenuItem();
mnuExit=new MenuItem();
mnuSep=new MenuItem();
mnuFile.Text="&File";
mnuOpen.Text="&Open";
mnuSave.Text="Save &As";
mnuExit.Text="E&xit";
mnuSep.Text="-";
mnuFile.MenuItems.Add(mnuOpen);
mnuFile.MenuItems.Add(mnuSave);
mnuFile.MenuItems.Add(mnuSep);
mnuFile.MenuItems.Add(mnuExit);
mnuMain.MenuItems.Add(mnuFile);
mnuOpen.Click+=new EventHandler(fncOpen);
mnuSave.Click+=new EventHandler(fncSave);
mnuExit.Click+=new EventHandler(fncExit);
return mnuMain;
}
private void setControls() 
{
/* initialize and add the controls to the form. */gpbRotate = new GroupBox();
gpbRotate.Location = new Point(0,0);
gpbRotate.Size=new Size(300,50);
gpbRotate.Text = "Rotate";
gpbFlip = new GroupBox();
gpbFlip.Location = new Point(300,0);
gpbFlip.Size = new Size(300,50);
gpbFlip.Text = "Flip";
rbnRotNone = fncRadBtns("None","None",50,10,20);
rbnFlipNone = fncRadBtns("None","None",50,10,20);
rbnRotX = fncRadBtns("90 deg","90",70,80,20);
rbnRotY = fncRadBtns("180 deg","180",70,150,20);
rbnRotXY = fncRadBtns("270 deg","270",70,220,20);
rbnFlip90 = fncRadBtns("X - axis","X",70,80,20);
rbnFlip180 = fncRadBtns("Y - axis","Y",70,150,20);
rbnFlip270 = fncRadBtns("XY - axis","XY",70,220,20);rbnRotNone.Checked = true;
rbnFlipNone.Checked = true;
btnTransform = new Button();
btnTransform.Text="Transform Image";
btnTransform.Location = new Point(0,65);
btnTransform.Width=100;
btnOrg = new Button();
btnOrg.Text = "Original Position";
btnOrg.Location = new Point(200,65);
btnOrg.Width = 100;
lblPicMode = new Label();
lblPicMode.Text = "Picture Mode ";
lblPicMode.Location = new Point(350,67);
lblPicMode.Width = 70;
cmbPicMode = new ComboBox();
cmbPicMode.Location = new Point(420,65);
cmbPicMode.DropDownStyle=ComboBoxStyle.DropDownList;
cmbPicMode.Items.Add("Auto Size");
cmbPicMode.Items.Add("Center Image");
cmbPicMode.Items.Add("Normal");
cmbPicMode.Items.Add("Stretch Image");
cmbPicMode.SelectedIndex=2;
pbxImg = new PictureBox();
pbxImg.Location = new Point(0,100);
pbxImg.Size = new Size(750,400);
stbBtm=new StatusBar();
stbBtm.Text = "Normal mode - Image is clipped if it is bigger than the Picture Box.";
stbBtm.BackColor=Color.Green;
stbBtm.Size=new Size(750,20);
stbBtm.Location = new Point(0,550);
gpbRotate.Controls.Add(rbnRotNone);
gpbRotate.Controls.Add(rbnRotX);
gpbRotate.Controls.Add(rbnRotY);
gpbRotate.Controls.Add(rbnRotXY);
gpbFlip.Controls.Add(rbnFlipNone);
gpbFlip.Controls.Add(rbnFlip90);
gpbFlip.Controls.Add(rbnFlip180);
gpbFlip.Controls.Add(rbnFlip270);
pnlTop.Controls.Add(gpbRotate);
pnlTop.Controls.Add(gpbFlip);
pnlTop.Controls.Add(btnTransform);
pnlTop.Controls.Add(btnOrg);
pnlTop.Controls.Add(lblPicMode);
pnlTop.Controls.Add(cmbPicMode);
Controls.Add(stbBtm);
pnlTop.Controls.Add(pbxImg);
blnPicLoaded=false;
strStatus=stbBtm.Text;
}
private RadioButton fncRadBtns(string strText,string strName,int intWidth,int intX,int intY){
RadioButton rbnTmp;
rbnTmp = new RadioButton();
rbnTmp.Text = strText;
rbnTmp.Name = strName;
rbnTmp.Width = intWidth;
rbnTmp.Location = new Point(intX,intY);
return rbnTmp;
}
private void fncOpen(object obj,EventArgs ea) 
{
/* load the picture. */ 
try{
dlgFile=new OpenFileDialog();
dlgFile.Filter="JPEG Images (*.jpg,*.jpeg)|*.jpg;*.jpeg|Gif Images (*.gif)*.gif|Bitmaps (*.bmp)|*.bmp";
dlgFile.FilterIndex=1;
if (dlgFile.ShowDialog()== DialogResult.OK)
{
if((stm=dlgFile.OpenFile())!=null)
{
strImgName=dlgFile.FileName;
stm.Close();
pbxImg.Image=Image.FromFile(strImgName);
blnPicLoaded=true;
}
}
if (blnPicLoaded) 

/* if the picture is loaded then enable the events. */rbnRotNone.Click+=new EventHandler(fncRot);
rbnRotX.Click+=new EventHandler(fncRot);
rbnRotY.Click+=new EventHandler(fncRot);
rbnRotXY.Click+=new EventHandler(fncRot);
rbnFlipNone.Click+=new EventHandler(fncFlip);
rbnFlip90.Click+=new EventHandler(fncFlip);
rbnFlip180.Click+=new EventHandler(fncFlip);
rbnFlip270.Click+=new EventHandler(fncFlip);
btnTransform.Click+= new EventHandler(fncTransform);
btnOrg.Click += new EventHandler(fncTransform);
cmbPicMode.SelectionChangeCommitted += new EventHandler(fncPicMode);
}
}
catch(Exception e)
{
Console.WriteLine(e.StackTrace);
}
}
private void fncSave(object sender, EventArgs ea)
{
try{
/* save the image in the required format. */SaveFileDialog dlgSave = new SaveFileDialog();
dlgSave.Filter="JPEG Images (*.jpg,*.jpeg)|*.jpg;*.jpeg|Gif Images (*.gif)*.gif|Bitmaps (*.bmp)|*.bmp";
if (dlgSave.ShowDialog()==DialogResult.OK)
{
strImgName=dlgSave.FileName;
if (strImgName.EndsWith("jpg"))
pbxImg.Image.Save(strImgName,ImageFormat.Jpeg);
if (strImgName.EndsWith("gif"))
pbxImg.Image.Save(strImgName,ImageFormat.Gif);
if (strImgName.EndsWith("bmp"))
pbxImg.Image.Save(strImgName,ImageFormat.Bmp);
}
}
catch(Exception e)
{
Console.WriteLine(e.StackTrace);
}
}
private void fncRot(object obj,EventArgs ea)
{
rbnTemp = (RadioButton)obj;
strRot=rbnTemp.Name;
setStatus();
}
private void fncFlip(object obj,EventArgs ea) 
{
rbnTemp = (RadioButton)obj;
strFlip = rbnTemp.Name;
setStatus();
}
private void fncTransform(object obj,EventArgs ea)
{
Button btnTemp=(Button)obj;
if (btnTemp.Text=="Transform Image")
{
strRotFlip=strRot + strFlip;
switch (strRotFlip)
{
case "180None" :
pbxImg.Image.RotateFlip(RotateFlipType.Rotate180FlipNone);
break;
case "180X" :
pbxImg.Image.RotateFlip(RotateFlipType.Rotate180FlipX);
break;
case "180Y" :
pbxImg.Image.RotateFlip(RotateFlipType.Rotate180FlipY);
break;
case "180XY" :
pbxImg.Image.RotateFlip(RotateFlipType.Rotate180FlipXY);
break;
case "270None" :
pbxImg.Image.RotateFlip(RotateFlipType.Rotate270FlipNone);
break;
case "270X" :
pbxImg.Image.RotateFlip(RotateFlipType.Rotate270FlipX);
break;
case "270Y" :
pbxImg.Image.RotateFlip(RotateFlipType.Rotate270FlipY);
break;
case "270XY" :
pbxImg.Image.RotateFlip(RotateFlipType.Rotate270FlipXY);
break;
case "90None" :
pbxImg.Image.RotateFlip(RotateFlipType.Rotate90FlipNone);
break;
case "90X" :
pbxImg.Image.RotateFlip(RotateFlipType.Rotate90FlipX);
break;
case "90Y" :pbxImg.Image.RotateFlip(RotateFlipType.Rotate90FlipY);
break;
case "90XY" :
pbxImg.Image.RotateFlip(RotateFlipType.Rotate90FlipXY);
break;
case "NoneNone" :
pbxImg.Image.RotateFlip(RotateFlipType.RotateNoneFlipNone);
break;
case "NoneX" :
pbxImg.Image.RotateFlip(RotateFlipType.RotateNoneFlipX);
break;
case "NoneY" :
pbxImg.Image.RotateFlip(RotateFlipType.RotateNoneFlipY);
break;
case "NoneXY" :
pbxImg.Image.RotateFlip(RotateFlipType.RotateNoneFlipXY);
break;
default :
pbxImg.Image.RotateFlip(RotateFlipType.RotateNoneFlipNone);
break;
}
}
else if (btnTemp.Text=="Original Position")
{
pbxImg.Image=Image.FromFile(strImgName);
pbxImg.Refresh();
}
pbxImg.Refresh();
}
private void fncPicMode(object obj,EventArgs ea)
{
ComboBox objTemp = (ComboBox)obj;
switch (objTemp.SelectedIndex)
{
case 0 :
pbxImg.SizeMode=PictureBoxSizeMode.AutoSize;
strStatus="AutoSize mode - The PictureBox is sized equal to the size of the image
that it contains.";
break;
case 1 :
pbxImg.SizeMode=PictureBoxSizeMode.CenterImage;
strStatus="CenterImage mode - Image is placed in the center of the Picture Box.";
strStatus=strStatus + "If the image is big then outside edges of Image is clipped.";
break;
case 2 :
pbxImg.SizeMode=PictureBoxSizeMode.Normal;
strStatus="Normal mode - Image is clipped if it is bigger than the Picture Box.";
break;
case 3 :
pbxImg.SizeMode=PictureBoxSizeMode.StretchImage;
strStatus="Stretch mode - Image is stretched or shrunk to fit the Picture Box.";
break;
}
pbxImg.Refresh();
stbBtm.Text=strStatus;
}
private void setStatus()
{
strStatus="The Image is rotated ";
if (strRot != null && strRot != "None")
strStatus=strStatus + strRot + " degrees";
if (strFlip !=null && strFlip != "None")
strStatus=strStatus +" around " + strFlip + " axis.";
stbBtm.Text=strStatus;
}
private void fncExit(object obj,EventArgs ea)
{
Application.Exit();
}
}

ref:
http://www.c-sharpcorner.com

Please watch this vedio
http://msdn.microsoft.com/en-us/vstudio/gg278409.aspx

Saturday 29 December 2012

FormsAuthentication.Authenticate Always Returns false


I was trying to create a custom authentication screen without

 using any of the standard ASP.Net security controls (i.e. Login control). 

 So, I created my custom form and was calling the

 System.Web.Security.FormsAuthentication.Authenticate(UserName, Password) method. 

 However, it was always returning false and in fact did not appear

 to even be hitting my SQL database (which contained the security) 

as the failed login attempts, etc. were all unaltered.  Furthermore,

 I changed my connection string to be a bogus reference and the Authenticate

 still simple returned false (I was expecting it to error). 

 I then found out that the

 System.Web.Security.FormsAuthentication.Authenticate(UserName, Password) method is

 for user information stored in the web.config file.  Instead,

 I used the System.Web.Security.Membership.ValidateUser(UserName, Password) method

 which is for the user information stored in the SQL database.


NOTE: When doing this I also then set the authorization cookie by calling:

System.Web.Security.FormsAuthentication.SetAuthCookie(UserName, true);

Here is some sample code:

static public string Login(string UserName, string Password)
{
  if (System.Web.Security.Membership.ValidateUser(UserName, Password))
  {
    System.Web.Security.FormsAuthentication.SetAuthCookie(UserName, true);
    return "1|" + DateTime.Now.ToString();
  }
  else
    return "0|Login failed!";
}



How integrate Facebook, Twitter, LinkedIn, Yahoo, Google and Microsoft Account with your ASP.NET MVC application

Friday 28 December 2012

mobile application tutorial


MVC:

Azure

http://www.windowsazure.com/en-us/develop/net/tutorials/aspnet-mvc-4-mobile-website/

other ways

http://www.w3schools.com/dotnetmobile/default.asp
http://www.asp.net/mobile

http://www.satter.org/2008/01/mobile-web-deve.html
http://wiki.asp.net/page.aspx/459/namespaces-for-aspnet-mobile-development/


ASP.NET is excellent for Mobile web application development.The beauty of asp.net is, it will render the content based on the requested device. Normal asp.net code works perfectly in Mobile browsers[HTML capable browsers].

For iPhone development,

http://developer.apple.com/safari/library/documentation/AppleApplications/Reference/SafariWebContent/Introduction/Introduction.html#//apple_ref/doc/uid/TP40002051



For Blackberry development,

http://na.blackberry.com/eng/developers/browserdev/



For Android,Symbian,  & Other OS

Asp.net renders the content absolutely fine on these phones.






compare validation in gridview asp.net


I did a sample for :

<asp:GridView ID="GridView1" runat="server" DataSourceID="SqlDataSource1" AutoGenerateColumns="false"OnRowDataBound="GridView1_RowDataBound">
        <Columns>
          <asp:TemplateField HeaderText="Start Date">
            <ItemTemplate>
              <asp:Label runat="server" ID="Label1" Text='<%# Eval("StartDate") %>'></asp:Label>
            </ItemTemplate>
            <EditItemTemplate>
              <asp:TextBox runat="server" ID="TextBox1" Text='<%# Eval("StartDate","{0:d}")  %>'></asp:TextBox>
            </EditItemTemplate>
          </asp:TemplateField>
          <asp:TemplateField HeaderText="End Date">
            <ItemTemplate>
              <asp:Label runat="server" ID="Label2" Text='<%# Eval("EndDate") %>'></asp:Label>
            </ItemTemplate>
            <EditItemTemplate>
              <asp:TextBox runat="server" ID="TextBox2" Text='<%# Eval("EndDate","{0:d}") %>'></asp:TextBox>
            </EditItemTemplate>
          </asp:TemplateField>
          <asp:CommandField ShowEditButton="true" />
        </Columns>
</asp:GridView>

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowState == DataControlRowState.Edit)
        {
            CompareValidator cv = new CompareValidator();
            e.Row.Cells[1].Controls.Add(cv);
            cv.ControlToValidate = "TextBox2";
            cv.Type = ValidationDataType.Date;
            cv.Operator = ValidationCompareOperator.GreaterThan;
            cv.ErrorMessage = "End date should be later than start date!";
            cv.ValueToCompare = ((TextBox)e.Row.FindControl("TextBox1")).Text;
        }
    }

You can change index or anything as your real situation.

refer from asp.net forum

Validation - CustomValidator in asp.net

If none of the other validators can help you, the CustomValidator usually can. It doesn't come with a predefined way of working; you write the code for validating your self. This is of course very powerful, since the possibilities are basically endless. A common way of using the CustomValidator is when you need to make a database lookup to see if the value is valid. Since this tutorial hasn't treated database access yet, we will do a simpler example, but hopefully you will see that you can do just about everything with the CustomValidator. The control allows you to validate both clientside and serverside, where the serverside approach is probably the most powerful. Of course, doing serverside validation requires a postback to validate, but in most cases, that's not really a problem. 

In this example, we will simply check the length of the string in the TextBox. This is a very basic and that useful example, only made to show you how you may use the CustomValidator.


Custom text:<br />
<asp:TextBox runat="server" id="txtCustom" />
<asp:CustomValidator runat="server" id="cusCustom" controltovalidate="txtCustom" onservervalidate="cusCustom_ServerValidate" errormessage="The text must be exactly 8 characters long!" />
<br /><br />


As you can see, it's pretty simple. The only unknown property is the onservervalidate event. It's used to reference a method from CodeBehind which will handle the validation. Switch to our CodeBehind file and add the following method:
protected void cusCustom_ServerValidate(object sender, ServerValidateEventArgs e)
{
    if(e.Value.Length == 8)
        e.IsValid = true;
    else
        e.IsValid = false;
}
This is very simple. The validator basically works by setting the e.IsValid boolean value to either true or false. Here we check the e.Value, which is the string of the control being validated, for it's length. If it's exactly 8 characters long, we return true, otherwise we return false. 

Although the serverside approach is probably the most powerful, you need to consider your site hosting, especially if your database receives plenty of queries. 


Properties






Example

CustomValidator
Declare two Label controls, one TextBox control, one Button control, and one CustomValidator control in an .aspx file. The user() function checks the length of the input value. If the length is <8 or >16 the text "A username must be between 8 and 16 characters!" will appear in the CustomValidator control.







Could not load file or assembly 'DotNetOpenAuth.AspNet' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040)

Add this reference on the flow

1)DotNetOpenAuth.AspNet.dll
2)DotNetOpenAuth.Core.dll
3)DotNetOpenAuth.Core.UI.dll
4)DotNetOpenAuth.InfoCard.dll
5)DotNetOpenAuth.OAuth.Common.dll
6)DotNetOpenAuth.OAuth.Consumer.dll
7)DotNetOpenAuth.OAuth.dll
7)DotNetOpenAuth.OpenId.dll
8)DotNetOpenAuth.ServiceProvider.dll

This all reference was must be version in 4.1


and build  your applications,load this dll in Bin folder .then run

Thursday 27 December 2012

How to Login With SQL Server Database with VB(or C#) Language

The following example demonstrates how to use a Login control to provide a user interface to log on to a Web site with sql server database. VB : Imports System.Data , Imports System.Data.SqlClient and Imports System.Web.Configuration , C# : using System.Data; , using System.Data.SqlClient; and using System.Web.Configuration;

User Name: aspxcode , Password: 2008

   1. xml file or web.config


<?xml version="1.0"?>

  <configuration>

<connectionStrings>
 <add name="ConnectionASPX" connectionString="Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Northwind.mdf;Integrated Security=True" providerName="System.Data.SqlClient"/>
</connectionStrings>

  </configuration>


2. how-to-login-with-sql-server.aspx (Design Page)
Login Coltrol ASP.NET
3. how-to-login-with-sql-server.aspx (Source Page)


<%@ Page Language="VB" AutoEventWireup="false" CodeFile="how-to-login-with-sql-server.aspx.vb" Inherits="how_to_login_with_sql_server" %>

<!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>how to login with sql server database</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    
         <asp:Login ID="Login1" runat="server" BackColor="#FFFBD6" BorderColor="#FFDFAD" BorderPadding="4"
            BorderStyle="Solid" BorderWidth="1px" Font-Names="Verdana" Font-Size="0.8em"
            ForeColor="#333333" OnAuthenticate="Login1_Authenticate" TextLayout="TextOnTop"
            Width="293px" 
               Height="172px">
            <TitleTextStyle BackColor="#990000" Font-Bold="True" Font-Size="0.9em" 
                   ForeColor="White" />
            <InstructionTextStyle Font-Italic="True" ForeColor="Black" />
            <TextBoxStyle Font-Size="0.8em" />
            <LoginButtonStyle BackColor="White" BorderColor="#CC9966" BorderStyle="Solid" BorderWidth="1px"
                Font-Names="Verdana" Font-Size="0.8em" ForeColor="#990000" />
        </asp:Login>
    
    </div>
    </form>
</body>
</html>


4. how-to-login-with-sql-server.aspx.vb (Code Behind VB Language)

Imports System.Data
Imports System.Data.SqlClient
Imports System.Web.Configuration
Partial Class how_to_login_with_sql_server
    Inherits System.Web.UI.Page

    Protected Sub Login1_Authenticate(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.AuthenticateEventArgs) Handles Login1.Authenticate
        Dim username As String
        Dim pwd As String
        Dim pName As String

        username = Login1.UserName
        pwd = Login1.Password
        pName = ""
        Dim strConn As String
        strConn = WebConfigurationManager.ConnectionStrings("ConnectionASPX").ConnectionString

        Dim Conn As New SqlConnection(strConn)
        Conn.Open()


        Dim sqlUserName As String
        sqlUserName = "SELECT UserName,Password FROM UserName "
        sqlUserName &= " WHERE (UserName = @UserName"
        sqlUserName &= " AND Password = @Password)"

        Dim com As New SqlCommand(sqlUserName, Conn)
        com.Parameters.AddWithValue("@UserName", username)
        com.Parameters.AddWithValue("@Password", pwd)


        Dim CurrentName As String
        CurrentName = CStr(com.ExecuteScalar)

        If CurrentName <> "" Then
            Session("UserAuthentication") = username

            Response.Redirect("how-to-StartPage.aspx")
        Else
            Session("UserAuthentication") = ""
        End If

    End Sub
End Class

5. how-to-login-with-sql-server.aspx (View in Browser)
Login Coltrol ASP.NET
Login Coltrol ASP.NET

Convert to C#


refer from:http://www.aspxcode.net

The SMTP server requires a secure connection or the client was not authenticated error while sending email from asp.net

I am trying to send an email from my asp.net application, the function worked fine on my machine, but when I deployed it on the webserver, I got the error :The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.5.1 Authentication Required,

But finally i get the solution .I has shared it


The SSL should be enable on the webserver as well, here is a link to enable ssl on the IIS7

dynamic DataGrid in silverlight

Set and Get values in string resource file


Creating Resources From a Web Page

The following feature is not available with Visual Web Developer Express.

To generate a local resource file from an ASP.NET Web page

  1. Open the page for which you want to create a resource file.
  2. Switch to Design View.
  3. In the Tools menu, click Generate Local Resource.
    Visual Web Developer creates the App_LocalResources folder if it does not already exist. Visual Web Developer then creates the culturally neutral base resource file for the current page, which includes a key/name pair for each control property or page property that requires localization. Finally, Visual Web Developer adds a meta attribute to each ASP.NET Web server control to configure the control to use implicit localization. For more information about implicit and explicit localization, see ASP.NET Web Page Resources Overview and How to: Use Resources to Set Property Values in Web Server Controls.
    Note:
    {Do not attempt to embed a graphic directly in a resource file because controls will not read the resource string as a streamed image file. Resource files represent graphics by storing the URL of the graphic as a string.}
  4. If the latest resource changes are not displayed, refresh Design view by switching to Source view and then switching back to Design view.
  5. Create resource files for additional languages by following steps 6 and 7 in the preceding procedure

    Add Values  to resource file
    Open with xml(text)Edit
    then
    <data name="PasswordError" xml:space="preserve">
        <value>Password or user name is invalid</value>
      </data>

    Call Resource file value in code-behind
     Strings.PasswordError

    MVC Razor side
     @Strings.PasswordError 

How to reduce angular CLI build time

 Index: ----- I am using angular cli - 7 and I am going to tell how to reduce the build time as per my knowledge. Problem: -------- Now the ...