Friday, 29 April 2011

C# Database Access: SQL Server 2008 & ASP.NET CODE, Generic Data Access

1. Web.config file- put the database connection

<connectionStrings>
<add name="BalloonShopConnection" connectionString="Server=(local)\SqlExpress;
         Integrated Security=True;
         Database=BalloonShop"
         providerName="System.Data.SqlClient"/>
</connectionStrings>
//put the <add> key in one line.

2. ApplicationConfiguration.cs- DataLayer- read the database connection from web.config and make a database connnection Property.


using System;
using System.Configuration;
//remember here class is static and constructor is static. no access modifier can be used for constructor
public static class BalloonShopConfiguration
{
    // Caches the connection string
    private static string dbConnectionString;
    // Caches the data provider name
    private static string dbProviderName;
   
    static BalloonShopConfiguration()
    {
        dbConnectionString =
        ConfigurationManager.ConnectionStrings["BalloonShopConnection"].
        ConnectionString;
        dbProviderName =
        ConfigurationManager.ConnectionStrings["BalloonShopConnection"].
        ProviderName;
      
    }
    // Returns the connection string for the BalloonShop database
    public static string DbConnectionString
    {
        get
        {
            return dbConnectionString;
        }
    }
    // Returns the data provider name
    public static string DbProviderName
    {
        get
        {
            return dbProviderName;
        }
    }
  
}


3. GenericDataAccess.cs- DataLayer- make the connection with database using the Property created in ApplicationConfiguration.cs. You can also create other database related operation for example: Insert, Update, Delete


using System.Data;
using System.Data.Common;

public static class GenericDataAccess
{
    // static constructor
    static GenericDataAccess()
    {
    }
  
    // creates and prepares a new DbCommand object on a new  connection
   
    public static DbCommand CreateCommand()
    {
        // Obtain the database provider name
        string dataProviderName = BalloonShopConfiguration.DbProviderName;
        // Obtain the database connection string
        string connectionString = BalloonShopConfiguration.DbConnectionString;
        // Create a new data provider factory
        DbProviderFactory factory = DbProviderFactories.
        GetFactory(dataProviderName);
        // Obtain a database specific connection object
        DbConnection conn = factory.CreateConnection();
        // Set the connection string
        conn.ConnectionString = connectionString;
        // Create a database specific command object
        DbCommand comm = conn.CreateCommand();
        // Set the command type to stored procedure
        comm.CommandType = CommandType.StoredProcedure;
        // Return the initialized command object
        return comm;
    }

    //execute a command and returns the results as DataTable
    public static DataTable ExecuteSelectCommand(DbCommand command)
    {
        DataTable table;
        try
        {
            command.Connection.Open();//open the data connection
            DbDataReader reader = command.ExecuteReader();
            //execute command and save into reader
            table = new DataTable();
            table.Load(reader);
            reader.Close();//close the reader
        }
        catch (Exception ex)
        {
            throw ex;
        }
        finally
        {
            command.Connection.Close();//close the connection
        }
        return table;
    }
    // execute an update, delete, or insert command
    // and return the number of affected rows
    public static int ExecuteNonQuery(DbCommand command)
    {
        // The number of affected rows
        int affectedRows = -1;
        // Execute the command making sure the connection gets closed in the end
        try
        {
            // Open the connection of the command
            command.Connection.Open();
            // Execute the command and get the number of affected rows
            affectedRows = command.ExecuteNonQuery();
        }
        catch (Exception ex)
        {
            // Log eventual errors and rethrow them
            //Utilities.LogError(ex);
            throw ex;
        }
        finally
        {
            // Close the connection
            command.Connection.Close();
        }
        // return the number of affected rows
        return affectedRows;
    }



  
}
4. CatalogAccess.csBussinessLogic-Acess the related database function from GenericDataAccess.cs
public static class CatalogAccess
{
    public struct DepartmentDetails
    {
        public string Name;
        public string Description;
    }
      //constructor
static CatalogAccess()
    {
    }
// Retrieve the list of departments
    public static DataTable GetDepartments()
    {
        // get a configured DbCommand object
        DbCommand comm = GenericDataAccess.CreateCommand();
        // set the stored procedure name
        comm.CommandText = "GetDepartments";
        // execute the stored procedure and return the results
        return GenericDataAccess.ExecuteSelectCommand(comm);
    }
public static bool UpdateDepartment(string id, string name, string description)
    {
        //get a configured dbcommand object
        DbCommand comm = GenericDataAccess.CreateCommand();
        //set the stored procedure name
        comm.CommandText = "UpdateDepartment";
        //create new parameter
        DbParameter param = comm.CreateParameter();
        param.ParameterName = "@DepartmentId";
        param.Value = id;
        param.DbType = DbType.Int32;
        comm.Parameters.Add(param);
        //create new parameter
        param = comm.CreateParameter();
        param.ParameterName = "@DepartmentName";
        param.Value = name;
        param.DbType = DbType.String;
        param.Size = 50;
        comm.Parameters.Add(param);
        //create new parameter
        param = comm.CreateParameter();
        param.ParameterName = "@DepartmentDescription";
        param.Value = description;
        param.DbType = DbType.String;
        param.Size = 1000;
        comm.Parameters.Add(param);
        //result will represent the number of changed rows
        int result = -1;
        try
        {
            //execute the stored procedure
            result = GenericDataAccess.ExecuteNonQuery( comm);
        }
        catch
        {
            //nothing
        }
       //result will be 1 in case of success
        return (result != -1);
    }
}

Web.config file - ASP.NET

<connectionStrings>
<add name="BalloonShopConnection" connectionString="Server=(local)\SqlExpress;
         Integrated Security=True;
         Database=BalloonShop"
         providerName="System.Data.SqlClient"/>
</connectionStrings>
//put the <add> key in one line. and use first bracket () in server=(local)\SqlExpress
<appSettings>
    <add key="MailServer" value="www.mail.stcharles.ac.uk" />
    <add key="EnableErrorLogEmail" value="false" />
    <add key="ErrorLogEmail" value="mah@stcharles.ac.uk" />
    <add key="SiteName" value="BalloonShop"/>
    <add key="ProductsPerPage" value="6"/>
    <add key="ProductDescriptionLength" value="60"/>
</appSettings>

<!--Only administrators are allowed to access CatalogAdmin.aspx-->
<location path="CatalogAdmin.aspx">
    <system.web>
      <authorization>
        <allow roles="Administrators"/>
        <deny users="*"/>
      </authorization>
    </system.web>
</location>

<authentication mode="Forms">
<forms name="BalloonShopLogin" loginUrl="Login.aspx" timeout="15" />
</authentication>

<system.web>
    <roleManager enabled="true" />
    <customErrors mode="RemoteOnly" defaultRedirect="Oooops.aspx">
    </customErrors>

<pages theme="BalloonShopDefault">
                  <controls>
                        .. .. ..
                  </controls>
</pages>

Friday, 22 April 2011

How to Zoom web page asp.net

        zoom the webpage

onload="this.style.zoom='75%'";

or,
iframe{
    zoom: 0.75;
    -moz-transform: scale(0.75);
    -moz-transform-origin: 0 0;
    -o-transform: scale(0.75);
    -o-transform-origin: 0 0;
    -webkit-transform: scale(0.75);
    -webkit-transform-origin: 0 0;
}

Your login attempt was not successful. Please try again.

User name and password is correct but still showing the message: Your login attempt was not successful. Please try again.

Cause: I copied the project from another computer.
Solution:

  •        1. Create a new website and copy the content of the folder.

load another webpage into iFrame & remove border in iFrame - ASP.NET

1. Load another webpage into iFrame

<iframe src="bannermiddle.aspx" >
</iframe>
2. but just loading webpage does not solve the problem. Its shows unwanted scrollbar and border.
    a. To fit all the content into iFrame - put a fixed width=500px; and assume height so that it can contain all the
                  text say for example height=700px;
    b. To remove border
                  frameborder="0" and
                  scrolling="no"

Thursday, 21 April 2011

Ajax UpdatePanel: with Placeholder control

Helpful Website

1. Create a menu.
2. Depending on the selected menu load the specific control - code should be placed in c# file
3. In the update panel put trigger control id = menu id
4.You must add a ScriptManager control to the page


Menu code:
<asp:MenuItem Text="File">
   <asp:MenuItem Text="Load Control1"></asp:MenuItem>
   <asp:MenuItem Text="Load Control2"></asp:MenuItem>
   <asp:MenuItem Text="Load Control3"></asp:MenuItem>
</asp:MenuItem>

Menu item click event code:

*protected void Menu1_MenuItemClick(object sender, MenuEventArgs e)
    {
        MenuItem menu = e.Item;

        string controlPath = string.Empty;

        switch (menu.Text)
        {
            case "Load Control2":
                controlPath = BASE_PATH + "SampleControl2.ascx";
                break;
            case "Load Control3":
                controlPath = BASE_PATH + "SampleControl3.ascx";
                break;
            default:
                controlPath = BASE_PATH + "SampleControl1.ascx";
                break;
        }

        LastLoadedControl = controlPath;
        LoadUserControl();
    }


*private void LoadUserControl()
    {
        string controlPath = LastLoadedControl;

        if (!string.IsNullOrEmpty(controlPath))
        {
            PlaceHolder1.Controls.Clear();
            UserControl uc = (UserControl)LoadControl(controlPath);
            PlaceHolder1.Controls.Add(uc);
        }
    }

Ajax Update panel code:
*<asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional">
         <ContentTemplate>
            <asp:PlaceHolder ID="PlaceHolder1" runat="server"></asp:PlaceHolder>
         </ContentTemplate>
         <Triggers>
                <asp:AsyncPostBackTrigger ControlID="Menu1" />
          </Triggers>
            
        </asp:UpdatePanel>
Note: 
<contentTemplate>
                 "here put the menu1 item based on which trigger will occur."
</contentTemplate>

Troubleshooting:

Re: Sys.WebForms.PageRequestManagerParserErrorException: The message received from the server cou...

Mar 05, 2009 05:19 AM|LINK
 AsyncPostBackTrigger is incorrect.  It's actually required to be a PostBackTrigger.  This is because we *don't want a partial postback; we are redirecting to a new execution thread*. 
The idea is that on the linkbutton's PreRender event we're adding the NewScriptManager.RegisterPostBackControl(MyButton) -- there's no need to set it declaritively in the ASPX page, it won't find it anyway and will throw a runtime error because the LinkButton is inside a databound templated control. 

 PlaceHolder vs ContentPlaceHolder

Nov 01, 2007 12:46 PM|LINK
A PlaceHolder control is used as a container for any controls you wish to add and can be used on any page. A ContentPlaceHolder is used to hold content from Content Pages and can only be used on a Master Page.

Wednesday, 20 April 2011

ASP.NET: A network-related or instance-specific error occurred while establishing a connection to SQL Server

I have installed windows7 and SQL Server R2 and Visual Web developer 2008 express edition without SQL server 2008. Then I tried to open the asp.net configuration and tried to connect the default aspnet.mdf database using database explorer. It showed the following error message:
Provider: SQL network interfaces, error 26. error locating server/instances specified.

Solution:
I installed the visual web developer 2008 express edition with optional SQL server 2008 express edition then it solved the problem. 





Also:
1.     Download & Install IIS 7.0
2.     Using Turn windows features on or off - Install IIS feature

Sunday, 3 April 2011

Change the Service Startup Account for SQL Server 2008

To change the SQL Server service startup account

  1. On the Start menu, point to All Programs, point to Microsoft SQL Server 2008 R2, point to Configuration Tools, and then click SQL Server Configuration Manager.
  2. In SQL Server Configuration Manager, click SQL Server Services.
  3. In the details pane, right-click the name of the SQL Server instance for which you want to change the service startup account, and then click Properties.
  4. In the SQL Server <instancename> Properties dialog box, click the Log On tab, and select a Log on as account type.
  5. After selecting the new service startup account, click OK.
    A message box asks whether you want to restart the SQL Server service.
  6. Click Yes, and then close SQL Server Configuration Manager.