Saturday, 30 April 2011

how to use web User Control in asp.net

Add A web user control file and write code for that control

Add Place Holder in .aspx file
<asp:PlaceHolder ID="ControlPlace" runat="server"></asp:PlaceHolder>

Add line <%@ Reference Control="~/UserControls/ScoreCardControl.ascx" %>  in .aspx file in which you want to use the web user control.

In .aspx.cs file-
make object of user control in .cs file
  private UserControls_ScoreCardControl controlObj = new UserControls_ScoreCardControl();
load control
controlObj = (UserControls_ScoreCardControl)LoadControl("~/UserControls/ScoreCardControl.ascx");
 ControlPlace.Controls.Add(controlObj);



How To set Rules For A folder in asp.net

Create a folder in your application Named Administrator and put all the files which are related to administrator
add web.config in this folder and write in web.config
<configuration>
    <system.web>
        <authorization>
            <allow roles="Administrator" />
            <deny users="*" />
        </authorization>
    </system.web>

Authentication And Authorization Settings in Web.Config

 <system.web>
<authentication mode="Forms">
      <forms name="skillify" defaultUrl="menulist.aspx" /> 
 </authentication>

<authorization>
      <deny users="?"/>
    </authorization>
  </system.web>

Membership, Roles And Profile Settings In Web.Config

<system.web>
    ... authentication & authorization settings ...

    <membership defaultProvider="CustomizedProvider">
      <providers>
         <add name="CustomizedProvider"
              type="System.Web.Security.SqlMembershipProvider"  
              connectionStringName="MyDB"
              applicationName="/"
              minRequiredPasswordLength="5"
              minRequiredNonalphanumericCharacters="0" />
      </providers>
    </membership>

<roleManager enabled="true   cookieProtection="All">
<providers>
<add name="RainbowSqlRoleProvider"
type="System.Web.Security.SqlRoleProvider"
connectionStringName="csRainbowAspNetDb"
applicationName="/" />
</providers>
</roleManager>

<profile defaultProvider="SqlProfileProvider">
    <providers>
      <remove name="AspNetSqlProfileProvider"/>
      <add name="SqlProfileProvider" 
       type="System.Web.Profile.SqlProfileProvider" 
       connectionStringName="LocalSqlServer"/>
    </providers>
   <properties>
      <add name="FirstName" type="string"/>
      <add name="LastName" type="string"/>
      <add name="AdvancedMode" type="bool"/>
      <group name="Address">
        <add name="Street" type="string"/>
        <add name="City" type="string"/>
        <add name="State" type="string"/>
        <add name="Zip" type="string"/>
      </group>    </properties>  </profile>
How To Save Profile Information in DB
In profile.aspx.cs file-
protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            MembershipUser user = Membership.GetUser();
            ProfileCommon profile = (Profile as ProfileCommon).
GetProfile(user.UserName);
            txtFirstName.Text = profile.FirstName;
            txtLastName.Text = profile.LastName;
            txtMobile.Text = profile.MobileNo;
        }
        
    }
protected void btnSubmit_Click(object sender, EventArgs e)
    {
    MembershipUserCollection allUsers = Membership.GetAllUsers();

        foreach (MembershipUser us in allUsers)
        {
ProfileCommon prof = (HttpContext.Current.Profile as ProfileCommon)
.GetProfile(us.UserName);
if (prof.MobileNo == txtMobile.Text && us.UserName != Membership.
GetUser().UserName)
            {
     lablError.Text = "<br/>Phone Number is already assign to 
another user";
                return;
            }
        }
   MembershipUser user = Membership.GetUser();
 ProfileCommon profile = (Profile as ProfileCommon).
GetProfile(user.UserName);
        profile.FirstName = txtFirstName.Text;
        profile.LastName = txtLastName.Text;
        profile.MobileNo = txtMobile.Text;
        profile.Save();
        clearAll();
        lablError.Text = "Profile Updated Successfully";
    }

How To Create Charts In ASP.NET

First Downoad MsChart.exe from
http://www.microsoft.com/downloads/en/details.aspx?FamilyID=130f7986-bf49-4fe5-9ca8-910ae6ea442c

 Run MsChart.exe and chart tools will be added to VS 2010 in Data Tab-


Drag And Drop Chart Tool

Add a TempImages folder in your application.


From Smart Tag of Chart Control You Can Choose Chat Type Like Line And spline etc.

In Default.aspx page--
<asp:Chart ID="Chart1" EnableViewState="True"
            ImageStorageMode="UseImageLocation" ImageLocation="~/tempImages/ChartPic_#SEQ(300,5)" 
            ImageType="Jpeg" Height="400px"
            Width="900px"  runat="server" BackColor="MistyRose"
            BackGradientStyle="TopBottom" BackImageTransparentColor="255, 128, 0"
            BackSecondaryColor="192, 192, 0" BorderlineColor="Maroon" Palette="Berry">
            <Series>
                <asp:Series Name="Series1" ChartType="Line">

                </asp:Series>
            </Series>
            <ChartAreas>
                <asp:ChartArea Name="ChartArea1">
                <AxisX LineColor="Brown" Title="Test Name" TitleFont="Verdana">
                </AxisX>
                <AxisY LineColor="Brown" Title="Percentage" TitleFont="Verdana">
                </AxisY>
                </asp:ChartArea>
            </ChartAreas>
 </asp:Chart>


How to bind a chart to a stored procedure in Asp.Net-> in code behind file means .aspx.cs file

private void bindChart()    {

        SqlConnection con = newSqlConnection(ConnectionString);

        SqlCommand cmd = new SqlCommand();

        cmd.Connection = con;

        cmd.CommandText = "ProcedureName";

        cmd.CommandType = CommandType.StoredProcedure;

        DataTable dt = new DataTable();

        SqlDataAdapter da = newSqlDataAdapter(cmd);

        da.Fill(dt);

        Chart1.DataSource = dt;

        Chart1.Series["Series1"].XValueMember = "Test";

        Chart1.Series["Series1"].YValueMembers = "Percentage";

        Chart1.DataBind();    }

How to change the color and Increase thickness of line generated in chart-

Chart1.Series["Series1"].BorderWidth = 5;  --For Thickness of line

Chart1.Series["Series1"].Color = System.Drawing.Color.Green; -- For Line color

 In Web.Config->


<system.web>

    <httpHandlers>
      <remove path="*.asmx" verb="*"/>
      <add path="*.asmx" verb="*" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" validate="false"/>
      <add path="*_AppService.axd" verb="*" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" validate="false"/>
      <add path="ScriptResource.axd" verb="GET,HEAD" type="System.Web.Handlers.ScriptResourceHandler, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" validate="false"/>
      <add path="ChartImg.axd" verb="GET,HEAD" type="System.Web.UI.DataVisualization.Charting.ChartHttpHandler, System.Web.DataVisualization, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" validate="false"/>
    </httpHandlers>

</system.Web>





 

 

 


How To Send An EMail From ASP.NET Web Page.

In Web.Config:

<appSettings>
    <add key="ContactEmailTo" value="Id To Which You Have to Send Mail"/>
    <add key="ContactEmailFrom" value="Id From Which You Have to Send Mail"/>
    <add key="ContactEmailPassword" value="Password of Id From Which You Have to Send Mail"/>
  </appSettings>

In .CS File:

Create Mail Format-
StringBuilder sbMail = new StringBuilder();
sbMail.Append("<table width='70%'><tr><td>EmpId:<b> " + 1000  + "</b></td></tr>");
sbMail.Append("<tr><td>Emp Name:<b> " + Ankur + "</b></td></tr><tr><td></td></tr>");





if (SendEmail(ConfigurationManager.AppSettings["ContactEmailFrom"],
ConfigurationManager.AppSettings["ContactEmailPassword"], ConfigurationManager.AppSettings["ContactEmailTo"],"Subject Of Mail", sbMail.ToString(), System.Web.Mail.MailFormat.Html, "") == true)
{

 }





public static bool SendEmail(string pGmailEmail,string pGmailPassword,string pTo,string pSubject,string pBody,System.Web.Mail.MailFormat pFormat,string pAttachmentPath)
    {
        try
        {
            System.Web.Mail.MailMessage myMail = new System.Web.Mail.MailMessage();
            myMail.Fields.Add
                ("http://schemas.microsoft.com/cdo/configuration/smtpserver",
                              "smtp.gmail.com");
            myMail.Fields.Add
                ("http://schemas.microsoft.com/cdo/configuration/smtpserverport",
                              "465");
            myMail.Fields.Add
                ("http://schemas.microsoft.com/cdo/configuration/sendusing",
                              "2");
           
            myMail.Fields.Add
            ("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate", "1");
            //Use 0 for anonymous
            myMail.Fields.Add
            ("http://schemas.microsoft.com/cdo/configuration/sendusername",
                pGmailEmail);
            myMail.Fields.Add
            ("http://schemas.microsoft.com/cdo/configuration/sendpassword",
                 pGmailPassword);
            myMail.Fields.Add
            ("http://schemas.microsoft.com/cdo/configuration/smtpusessl",
                 "true");
            myMail.From = pGmailEmail;
            myMail.To = pTo;
            myMail.Subject = pSubject;
            myMail.BodyFormat = pFormat;
            myMail.Body = pBody;
           

            System.Web.Mail.SmtpMail.SmtpServer = "smtp.gmail.com:465";
            System.Web.Mail.SmtpMail.Send(myMail);
            return true;
        }
        catch (Exception ex)
        {
            throw;
        }
    }

How To Create ASPNET DB in Sql server 2008 And Move It From VS 2010

Using aspnet_regsql command:
Open the Visual Studio 2005 command prompt from Start --> All Programs --> Microsoft Visual Studio 2005 --> Visual Studio Tools --> Visual Studio 2005 Command Prompt



  1. type aspnet_regsql and press enter key
  2. This will open the ASP.Net SQL Server Setup wizard. Click next to continue…

 In the next screen select the option to Configure SQL Server for application services. This option executes a script to configure the database for managing user profiles, roles, membership and personalization. Click next to continue…
 In this step enter the sql server name and choose the right authentication method. Leave the database field to default and click next…

 Confirm your settings and click next to finish.





IN Web.config:

 <connectionStrings>
    <remove name="LocalSqlServer"></remove>
    <add name="LocalSqlServer" connectionString="Data Source=SQLSERVER;Initial Catalog=DBNAME;User ID=ID;Password=PASS" providerName="System.Data.SqlClient"/></connectionStrings>


How To use Connection String From web.config

In Web.config
<configuration>
<connectionStrings>
          <add name="ConnectionStringName" connectionString="Data Source=SQLSERVER;Initial Catalog=DBNAME;User ID=ID;Password=PASS" providerName="System.Data.SqlClient"/>  </connectionStrings>
</configuration>

In DAL file
using System.Configuration;
static string connStr =ConfigurationManager.ConnectionStrings["ConnectionStringName"].ConnectionString;