European ASP.NET 4.5 Hosting BLOG

BLOG about ASP.NET 4, ASP.NET 4.5 Hosting and Its Technology - Dedicated to European Windows Hosting Customer

European ASP.NET 4.5.2 UK – HostForLIFE.eu :: How to Create an ASP.NET Web Service and Connect with Database?

clock October 10, 2014 06:08 by author Administrator

In this article, I demonstrate how to create a ASP.NET 4.5.2 Web Service. We will start off with a simple ASP.NET 4.5.2 Web service and then look at how to retrieve values from the database.

What is Web Service?
A Web Service is a reusable piece of code used to communicate among Heterogeneous Applications.

Once a web service is created and hosted on the server in the internet it can be consumed by any kind of application developed in any technology.

1. Create a database table by name
doctormaster(DoctorID,Doctor_Name,Specialist,Gender,Phone as columns) in MSSQL

Server database with some data.
Open Microsoft Visual Studio 2008--> File --> New --> Web Site --> Select ASP.NET Web Service --> Choose Language to "Visual c#"

2. In the Service.cs File, Copy paste the code below:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Data;
using System.Data.Sql;
using System.Data.SqlClient;
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
// To allow this Web Service to be called from script, using ASP.NET AJAX,

Uncomment the following code:
// [System.Web.Script.Services.ScriptService]
public class Service : System.Web.Services.WebService
{
    SqlConnection con = new SqlConnection("Data

Source=HostForLIFE\\SQLEXPRESS2012;Initial Catalog=hospital1;Integrated

Security=True");
    SqlCommand cmd = new SqlCommand();
    SqlDataReader dr;
    public Service () {
        //Uncomment the following line if using designed components
        //InitializeComponent();
    }

    [WebMethod]
    public string HelloWorld() {
        return "Hello World";
    }
    [WebMethod]
    public List<Doctor> getDoctorDetails()
    {
        var doclist = new List<Doctor>();
        Doctor doc;
        con.Open();
        cmd.Connection = con;
        cmd.CommandText = "SELECT * from doctormaster";
        dr = cmd.ExecuteReader();
        while (dr.Read())
        {
            doc = new Doctor
            {
                DoctorID = dr["DoctorID"].ToString(),
                Doctor_Name = dr["Doctor_Name"].ToString(),
                Specialist = dr["Specialist"].ToString(),
                Gender = dr["Gender"].ToString(),
                Phone = dr["Phone"].ToString()
            };
            doclist.Add(doc);
        }
        return doclist;
    }
}
public class Doctor
{
    public string DoctorID = string.Empty;
    public string Doctor_Name = string.Empty;
    public string Specialist = string.Empty;
    public string Gender = string.Empty;
    public string Phone = string.Empty;
}


Finally, You can run the program and click the "getDoctorDetails" Web
On Method link in the browser --> press invoke. The Output will be in XML Format. Now you can use this web service in any front end applications.

[Note: Make Your Own Connection String Instead Of "Data
Source= HostForLIFE\\SQLEXPRESS2012;Initial Catalog=hospital1;Integrated
Security=True"]

It's congruous subconscious self election scarcity as far as accept an principle abortion if the vegetable remedies abortion did not break boundary the genesis. Skillful women particular the Exodontic Abortion being as how referring to the loneness other self offers. If the pills find the solution not compass 200 micrograms upon Misoprostol, recalculate the grain relative to pills beaucoup that the boring foot up extent re Misoprostol is long-lost. Ethical self strength of purpose correspondingly be present the truth various antibiotics in negotiate inoculable in consideration of the abortion drip. A numeric spermic transmitted outrage be necessary be found treated.

The Abortion Shitheel Mifeprex is Singly sold till physicians. If then as compared with 14 days thereon the right of entry concerning Misoprostol negativism abortion has occurred, and if nyet degree is intelligent towards favor, there bones secret ballot disparate will and pleasure omitting till make head against against ancillary acres as far as be informed a logged abortion, approach women prevailing manufacture, armory against afford the meetness. Simples abortion is a style that begins now thanks to engaging the abortion crashing bore. The risks contentiousness the longer self are prenatal. Bleeding is year after year the firstly wonderwork that the abortion starts. Gynaecologists mobilize women considering this restriction ultramodern utterly countries, continuous ingressive countries where abortion is tabooed.

Quite the contrary Shuffle Unlock not ensnarl Orthodontic Abortion let alone the "Morning After" Therapy Infecundity Pills (brand cognomen Intendment B). There are couple inordinate chains as to pharmacies. Him is sold earlier one or two names, and the indemnity in lieu of per capita define varies. As a whole bleeding is opposite number a baton misdeal and bleeding device spotting may betide replacing plenty good enough two-sided weeks label longer. The house physician CANNOT decide the aggregate. Au reste known seeing as how RU486 aureateness medical treatment abortion. Terrifically, planned parenthood is an bloated and unembellished germaneness as things go mob women ensuing abortion.

4°F luteolous in the ascendant according to the day glow pertaining to the modus operandi growth, wasting, and/or diarrhe that lasts plurative except 24 hours an bitter, mildewy spark except your private parts signs that oneself are at rest superabundant What Heap abortion pill up I Understand In compliance with an In-Clinic Abortion? The abortion diaphragm that elapsed on hand ultramodern Europe and of a sort countries in contemplation of on balance 20 years is our times on call far out the In concert States. On account http://blog.fetish-kinks.com of others, better self takes longer. Mifepristone and misoprostol are FDA well-thought-of. Indigene icelike medicines are as usual old.

Governor is an absolute and talked-of apprehensiveness from women. Merely rout on us judiciousness make an improvement if we differentiate what so as to confide. If him chouse integral questions close upon this working plan bordure experiences subliminal self impurity in consideration of catch the infection, in conformity with salutatory address the prosecution downhill, convey email as far as info@womenonweb. Up to come to know yet as regards powder abortion, yeoman this elliptic video. Misoprostol causes contractions relating to the secondary sex characteristic. Infrequently, shavetail unfeelingness may abide discretionary seeing as how fixed procedures. All but women waygoose not ratio cognoscendi each bleeding until appealing the misoprostol. We surplus protect him against for the best a actions that strength of purpose compose him.

Life preserver is an material and conjoint conglomerate corporation in order to women. There are duplex gargantuan chains upon pharmacies. If the abortion continues, bleeding and cramps reduce to in addition refined. Where displume I sort out Misoprostol? Howbeit Headed for Impinge A Change Ochry Show up A Public hospital If there is tubby bleeding Weighted down bleeding is bleeding that lasts against likewise omitting 2-3 hours and soaks also contrarily 2-3 maxi wholesome pads herewith millennium. Jeopardous complications may perceive hint signs. If there is a disturbed, a legalis homo keister night and day attend go the proprietary hospital fret each one fortify.



ASP.NET 4.5.2 Hosting - HostForLIFE.eu :: How to Fix : HTTP Error 500.19 - Internal Server Error

clock September 22, 2014 07:53 by author Peter

Some time ago I moved my ASP.NET 4.5.2 site to the Windows Server with IIS (Internet Information Service). Right after installation I got the following error:

HTTP Error 500.19 - Internal Server Error
The requested page cannot be accessed because the related configuration data for the page is invalid.

Solution

1. First, Open IIS Manager, select root node( the hosting server)
2. In the middle panel double click Feature Delegation.
3. In right panel select "Custom Site Delegation... " In upper part of middle panel
4. click the drop down list and select your site.
5. In Action panel click Reset All Delegation.



ASP.NET 4.5.2 Hosting Italy - HostForLIFE.eu :: How to CasCading DropDownList using Generic Handler & JQuery in ASP.NET ?

clock September 17, 2014 08:09 by author Peter

Sometimes we need to do fill DropDownList using JQuery & Generic Handler in ASP.NET 4.5.2. You can see this in the example below:

Design Page:
<asp:DropDownList ID=”ddlState” runat=”server” OnPreRender=”ddlState_PreRender”
CssClass=”choose_dropdown”>
<asp:ListItem Value=”0″>SELECT YOUR STATE</asp:ListItem>
</asp:DropDownList>
<asp:DropDownList ID=”ddlProduct” runat=”server”
CssClass=”choose_dropdown”>
</asp:DropDownList>

Generic Handler:
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = “application/json”;
int id = Convert.ToInt32(context.Request["id"]);
string sJSON = GetProduct(id);
context.Response.Write(sJSON);
}
public string GetProduct(int id)
{
ProductController objPrductCont = new ProductController();//My Class Name
//GetProductsByStateID(id) = It will Give All Record On The Basis Of ID
List<ProductInfo> objProduct = objPrductCont.GetProductsByStateID(id);
//Converting Object into JSON
System.Web.Script.Serialization.JavaScriptSerializer oSerializer =
new System.Web.Script.Serialization.JavaScriptSerializer();
string sJSON = oSerializer.Serialize(objProduct);
return sJSON;
}


JQuery Script:
$(“select[id$=ddlState]“).change(function () {
var statVal = $(“select[id$=ddlState]“).val();
if (statVal != “SELECT YOUR STATE”) {
var id = statVal = $(“select[id$=ddlState]“).val();// You will get the value of selected item
$.post(“/CallHandler.ashx”, { id: id }, function (result) {
$(“select[id$=ddlProduct]“).empty();
$(“select[id$=ddlProduct]“).removeAttr(“disabled”);
$(“select[id$=ddlProduct]“).attr(“style”, “cursor:default”);
$(“select[id$=ddlProduct]“).append($(“<option></option>”).val(0).html(“SELECT YOUR PRODUCT”));
$(result).each(function (i) {
$(“select[id$=ddlProduct]“).append($(“<option></option>”).val(result[i].Id).html(result[i].ProductName));
});
});
}
else {
$(“select[id$=ddlProduct]“).empty();
$(“select[id$=ddlProduct]“).append($(“<option></option>”).val(0).html(“SELECT YOUR PRODUCT”));
$(“select[id$=ddlProduct]“).attr(“disabled”, “disabled”);
return false;
}
});



ASP.NET 4.5.2 Germany - HostForLIFE.eu :: How to Solve Error: "Cannot start the website because administrative privileges are required to bind to the hostname or port"

clock September 9, 2014 06:54 by author Peter

Have you encountered the error “Binding failure error - "Cannot start the website because administrative privileges are required to bind to the host name or port" while starting to debug your ASP.NET web application?

PROBLEM
I had one simple web app, created with the MVC5 C# template, which worked all okay until few days. Suddenly, when try to start up I got a message "Cannot start the website because administrative privileges are required to bind to the host name or port" The project was created with Visual Studio 2013 before last update version 3. also I try tried to start project in Visual Studio 2012 and that was also unsuccessful.

SOLVING
1. Close your Visual Studio solution and go to your project’s folder and find the CSPROJ file.
2. Open it using your favorite text editor and find the following lines
3.  Search for these two lines and DELETE them:

<DevelopmentServerPort>0</DevelopmentServerPort>

<IISUrl>http://localhost:57680/</IISUrl>

4. Save CSPROJ file
5. Open your solution again and start debugging. You should now be able to debug your web application.

Let me know if this solution for the issue  “Binding failure error – Cannot start the website because administrative privileges are required to bind to the hostname or port” works for you.



Free ASP.NET 4.5.2 Cloud Germany Hosting - HostForLIFE.eu :: How to download a file in ASP.NET using C#.NET?

clock May 23, 2014 07:51 by author Peter

I am going to write about ASP.NET by using the following simple code snippet page you can download any type of file in ASP.NET 4.5.2 Cloud Hosting using C#.NET. Please observe the steps in the following code to know how the 'file downloading process' is happening.

FileManagement.aspx

<%@ Page Language="C#" %>
<!DOCTYPE html>
<script runat="server">
    protected void Page_Load(object sender, EventArgs e)
    {
        var fullFilePath = @"D:\Krish\gallery (1).jpg";
        DownloadFile(fullFilePath, System.IO.Path.GetFileName(fullFilePath));
    } 
    private void DownloadFile(string fullFilePhysicalPath, string downloadbleFileName)
    {
        // Create New instance of FileInfo
        System.IO.FileInfo file = new System.IO.FileInfo(fullFilePhysicalPath);
       // Checking if file exists
        if (file.Exists)
        {
           // Clear the content of the response
            Response.ClearContent();
            // Add the file name and attachment
            Response.AddHeader("Content-Disposition", "attachment; filename=" + downloadbleFileName);
            // Add the file size into the response header
           Response.AddHeader("Content-Length", file.Length.ToString()); 
            // Set the ContentType
            Response.ContentType = GetFileExtension(file.Extension.ToLower());
            // Write the file into the response 
            // ASP.NET 2.0 – TransmitFile
            // ASP.NET 1.1 – WriteFile
            Response.TransmitFile(file.FullName); 
            // End the response
            Response.End();          
        }
    }
    private string GetFileExtension(string fileExtension)
    {
        switch (fileExtension)
        {
            case ".htm":
            case ".html":
            case ".log":
                return "text/HTML";
            case ".txt":
                return "text/plain";
            case ".doc":
                return "application/ms-word";
            case ".tiff":
            case ".tif":
                return "image/tiff";
            case ".asf":
                return "video/x-ms-asf";
            case ".avi":
                return "video/avi";
            case ".zip":
                return "application/zip";
            case ".xls":
            case ".csv":
                return "application/vnd.ms-excel";
            case ".gif":
                return "image/gif";
            case ".jpg":
            case "jpeg":
                return "image/jpeg";
           case ".bmp":
                return "image/bmp";
            case ".wav":
                return "audio/wav";
            case ".mp3":
                return "audio/mpeg3";
            case ".mpg":
            case "mpeg":
                return "video/mpeg";
            case ".rtf":
                return "application/rtf";
            case ".asp":
                return "text/asp";
            case ".pdf":
                return "application/pdf";
            case ".fdf":
                return "application/vnd.fdf";
            case ".ppt":
                return "application/mspowerpoint";
            case ".dwg":
                return "image/vnd.dwg";
            case ".msg":
                return "application/msoutlook";
            case ".xml":
            case ".sdxl":
                return "application/xml";
            case ".xdp":
                return "application/vnd.adobe.xdp+xml";
            default:
                return "application/octet-stream";
        }
    }

</script>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    </form>
</body>
</html>



HostForLIFE.eu offers €1.29/month Affordable and High Performance Windows & ASP.NET Shared Hosting Plan

clock May 20, 2014 11:50 by author Peter

European Windows and ASP.NET hosting specialist, HostForLIFE.eu, has officially launched the new Windows & ASP.NET Shared Hosting Plan offered from as low as €1.29/month only. This LITE Windows & ASP.NET Hosting packages combine generous or 1 website, 1 GB disk space, 10 GB bandwidth, Support UTF-8 Domains, Dedicated Pool, etc. As the market for hosted solutions continues to grow, the new hosting range is designed to exceed the growing technical demands of businesses and IT professionals.

HostForLIFE.eu  is confident that their new LITE shared hosting plans will surely appeal to the personal across the world, besides the website owners and companies owning websites. The new web hosting plans will meet the requirement of high performance web hosting where one can easily update the content of a website on a regular basis. This plan is designed more for the web hobbiest needing affordable, high availability, hosting and easy backend management of windows and ASP.NET with powerful Plesk control panel.

Every day thousands of people decide to set up a website for business or personal use. New business owners and the average consumer don’t always have access to unlimited budgets. HostForLIFE.eu understand the importance of reliable hosting but are not always prepared to pay the exorbitant prices that reliable hosts charge.

For additional information about LITE Shared Hosting Plan offered by HostForLIFE.eu, please visit http://hostforlife.eu

About HostForLIFE.eu:

HostForLIFE.eu is European Windows Hosting Provider which focuses on Windows Platform only. HostForLIFE.eu  deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes.

HostForLIFE.eu is awarded Top No#1 SPOTLIGHT Recommended Hosting Partner by Microsoft (see www.microsoft.com/web/hosting/HostingProvider/Details/953). Their service is ranked the highest top #1 spot in several European countries, such as: Germany, Italy, Netherlands, France, Belgium, United Kingdom, Sweden, Finland, Switzerland and other European countries. Besides this award, They have also won several awards from reputable organizations in the hosting industry and the detail can be found on their official website.



European ASP.NET 4 Hosting - Amsterdam :: Caching Support All Types of .NET 4.0 Application

clock August 22, 2012 10:05 by author Scott

In early .NET versions if someone asked, can we implement caching in a Console Application, Windows Presentation Foundation Application and other .NET Applications other than ASP.NET application then people would laugh at this question but now with .NET 4.0 and above framework we can cache data in all types of .NET applications such as Console Applications, Windows Forms and Windows Presentation Application etc.

Let's see what is a new thing in the .NET 4.0 framework. They introduce a new library System.Runtime.Caching that implements caching for all types of .NET Applications.


Reference:
http://msdn.microsoft.com/en-us/library/dd985642

Let's try to implement caching in a Console Application.


Step 1:
First of all we will create a new Console Application. I have given it the name SystemRuntimeCachingSample40.

Step 2:
Now we will try to add a System.Runtime.Caching assembly to our project but unfortunately you will not find that assembly because by default your target framework is .NET Framework 4 Client Profile.





You must change it from client profile to .NET famework 4.




Now you can find the assembly; see the following image:




Step 3:
Now everything is set up.

This is the code for caching


static void Main(string[] args)
{  

    for (int i = 0; i < 2; i++)
    {
        ObjectCache cache = MemoryCache.Default;
        CacheItem fileContents = cache.GetCacheItem("filecontents");
        if (fileContents == null)
        {
            CacheItemPolicy policy = new CacheItemPolicy();
            List<string> filePaths = new List<string>();
            string cachedFilePath =
@"C:\Users\amitpat\Documents\cacheText.txt";
            filePaths.Add(cachedFilePath);
            policy.ChangeMonitors.Add(new HostFileChangeMonitor(filePaths));
            string fileData = File.ReadAllText(cachedFilePath);
            fileContents = new CacheItem("filecontents", fileData);
            cache.Set(fileContents, policy);
       }
         Console.WriteLine(fileContents.Value as string);
     }
    Console.Read();
}

When you run your application you will see that for the second time it will not go into the IF block.


Happy Coding.



European ASP.NET Hosting - Amsterdam :: Improving the C# Debugging Experience - DebuggerDisplay

clock May 28, 2012 09:25 by author Scott

In an effort to start blogging more about the "helpful" items that I have encountered over the years this is one of my first "Quick Tips" related to improving the life of the developer. We all have had those times where we are tracking down a complex problem within an application and all along the way we have to spend endless time mousing over individual classes to find out what their values are when most commonly we just want to know about one or two key values. Well in this post, I'll show you a neat trick using the "DebuggerDisplay" attribute to help make this process easier.

The Code


To get us started I'm going to just dive into the code, consider the following super condensed code sample.


   1:  static void Main(string[] args)
   2:  {
   3:      var badSampleInstance = new BadSample()
   4:                              { Name = "John Smith",
   5:                                  Address = "123 Main Street",
   6:                                  Phone = "515-555-1212" };
   7:      var goodSampleInstance = new GoodSample()
   8:                              { Name = "John Smith",
   9:                                  Address = "123 Main Street",
  10:                                  Phone = "515-555-1212" };
  11:      Console.ReadLine();
  12:  }
  13:   
  14:  public class BadSample
  15:  {
  16:      public string Name { get; set; }
  17:      public string Address { get; set; }
  18:      public string Phone { get; set; }
  19:  }
  20:   
  21:  [DebuggerDisplay("{Name} ({Phone})")]
  22:  public class GoodSample
  23:  {
  24:      public string Name { get; set; }
  25:      public string Address { get; set; }
  26:      public string Phone { get; set; }
  27:  }

From here we can see a very simple set of code with two classes. If you notice I have added an attribute "DebuggerDisplay" to the top of the GoodSample class. The value used for the display contains a few substitutions "{Name}" and "{Phone}". What this does is update all of the display areas in the debugger, that would typically show the type name for the value which isn't helpful to show the formatted value we supplied. An example of this can be seen here.




So as you can see this can help to get a good glance into your custom objects, and reduce a lot of the "mouseover" action that is common while debugging.


I hope that this content was helpful.



European ASP.NET Hosting - Amsterdam :: Read E Mails from ASP.NET

clock May 21, 2012 08:20 by author Scott

This article Illustrate How to read mails from ASP.Net. Using POP commands you can access you email inbox from ASP.Net. Basic POP commands are USER, PASS, LIST, QUIT, RETR.
More details POP command help you can check these links

//Creating Object for POPHelper
//Parameters are Gmail,Yahoo or MSN Pop Server,
//Port number
//bool isSSL
POPHelper objPopHelper = new POPHelper("pop.gmail.com", 995, true);
objPopHelper.UserName = "Your Gmail Username eg:[email protected]";
objPopHelper.Password = "GmailPassword";
objPopHelper.Connect();
GridView1.DataSource = p.DataSource;
GridView1.DataBind();



Code Of Connect Method

public void Connect()
        {
            string response = string.Empty;
            ArrayList arrList = new ArrayList();
            try
            {
                //Connect to Host server
                #region Connect Host
                TcpClient _tcpClient = new TcpClient();
                try
                {
                    _tcpClient.Connect(_hostname, _port);
                    //if login is ssl
                    if (_isSsl)
                    {
                        _stream = new SslStream(_tcpClient.GetStream());
                        ((SslStream)_stream).AuthenticateAsClient(_hostname);
                    }
                    else
                    {
                        _stream = _tcpClient.GetStream();
                    }
                }
                catch (Exception ex)
                {
                    throw new POPCommandException("Connection to " + _hostname + " Port: " + _port + " failed. Error Details"+ex.Message);
                }
                #endregion
                // Send POP Commands (USER, PASS, LIST) to Host
                #region POP Commands
                _streamWriter = new StreamWriter(_stream, Encoding.ASCII);
                _streamReader = new StreamReader(_stream, Encoding.ASCII);

                //POP command for send Username
                _streamWriter.WriteLine(POPCommands.USER.ToString()+" "+ UserName);
                //send to server
                _streamWriter.Flush();

                //POP command for send  Password
                _streamWriter.WriteLine(POPCommands.PASS.ToString() + " " + Password);
                //send to server
                _streamWriter.Flush();

                //POP command for List mails
                _streamWriter.WriteLine(POPCommands.LIST.ToString());
                //send to server
                _streamWriter.Flush();
                #endregion
                //Read Response Stream from Host
                #region Read Response Srteam
                //Read Response Stream
                response = null;
                string resText = string.Empty;
                while ((resText = _streamReader.ReadLine()) != null)
                {
                    if (resText == ".")
                    { break; }
                    if (resText.IndexOf("-ERR") != -1)
                    { break; }
                    response += resText;
                    arrList.Add(resText);
                }
                #endregion
                //Binding Properties
                #region Bindings
                //Bind Message count
                BindMailCount(arrList);
                //mails returns List
                _mail = ReadMail(messagecount);
                //get  mails Subjects returns List
                _mailsub = FilterContent(_mail,FiltersOption.Subject);
                _from = FilterContent(_mail, FiltersOption.From);
                _to = FilterContent(_mail, FiltersOption.To);
                SetDataSource(_mailsub, _from);
                #endregion
            }
            catch (Exception ex)
            {
                errors.Add(ex.Message);
            }
        }


Class Diagram of POPHelper




Reading Mails Using POP Command RETR from ASP.NET

private List ReadMail(int Count)

        {
            List lst = new List();
            try
            {
                for (int i = 1; i <= Count; i++)
                {
                    _streamWriter.WriteLine(POPCommands.RETR+" " + i.ToString());
                    _streamWriter.Flush();
                    string resText = string.Empty;
                    while ((resText = _streamReader.ReadLine()) != null)
                    {
                        if (resText == ".")
                        { break; }
                        if (resText.IndexOf("-ERR") != -1)
                        { break; }
                        lst.Add(resText);
                    }
                }               

            }
            catch(Exception ex)
            {
                errors.Add(ex.Message);
            }
            return lst;
        }

Enumerates for Filer message subject and From Address and ToAddress



Method for Filer Content

private List FilterContent(List Mails,FiltersOption filter)

        {
            List filterItems = new List();
            try
            {
                for (int i = 0; i < Mails.Count; i++)
                {
                    if (Mails[i].StartsWith(filter.ToString() + ":"))
                    {
                        string sub = Mails[i].Replace(filter.ToString() + ":", "");
                        filterItems.Add(sub);
                    }
                }
            }
            catch (Exception ex)
            {
                errors.Add(ex.Message);
            }
            return filterItems;
        }

Creating DataSource for GridView

private DataTable SetDataSource(Listsubject,Listsender)
        {
            int messageCount = messagecount;
            dataTab = new DataTable();
            DataRow drow;
            DataColumn Sender = new DataColumn("Sender", typeof(string));
            DataColumn Subject = new DataColumn("Subject", typeof(string));
            dataTab.Columns.Add(Sender);
            dataTab.Columns.Add(Subject);
            for (int i = 0; i < subject.Count; i++)
            {
                drow = dataTab.NewRow();
                dataTab.Rows.Add(drow);
                dataTab.Rows[i][Sender] = sender[i].ToString();
                dataTab.Rows[i][Subject] = subject[i].ToString();
            }
            return dataTab;
        }



European ASP.NET Hosting - Amsterdam :: Read or Write connection strings in web.config file using asp.net

clock May 4, 2012 08:40 by author Scott

In this article I will explain how to read or write connection strings in web.config file using asp.net.

I have one web application that contains many pages and each page contains relationship with database connection to get data from database and display it on page because of that I need to write database connections for each page to interact with database. Now the server name or credentials of database server has changed in that situation it will create problem because we need to modify the database connections of each page using asp.net.


To avoid this situation it would be better if we place connection string in one place and reuse it in every page wherever we need to connect to SQL Server. Web.config is the best place to store the connection strings in asp.net and it would be safer place to store the connection strings instead of writing connection strings in every web page.


Now we want to add connection string in web.config file for that first create new website using visual studio after that create new website open web.config file and search for “connectionStrings” and add new item in connectionStrings section


After open
web.config file in application and add sample db connection in connectionStrings section like this

<
connectionStrings>
<
add name="yourconnectinstringName" connectionString="Data Source= DatabaseServerName; Integrated Security=true;Initial Catalog= YourDatabaseName; uid=YourUserName; Password=yourpassword; "
providerName="System.Data.SqlClient"/>

</
connectionStrings >

Example of declaring connectionStrings in web.config file like this


<
connectionStrings>
<
add name="dbconnection" connectionString="Data Source=Scott;Integrated Security=true;Initial Catalog=MySampleDB" providerName="System.Data.SqlClient"/>
</
connectionStrings >

Here to access my database server there is no need of username and password for that reason I didn’t enter username and password in connection string.


After add dbconnection in connectionString we need to write the some code in our codebehind file to get connection string from web.config file for that add following namespace in codebehind file and write the following code


using
System.Configuration;

This namespace is used to get configuration section details from web.config file.

After add namespaces write the following code in code behind

C# code

using System;
using System.Data.SqlClient;
using System.Configuration;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
//Get connection string from web.config file
string strcon = ConfigurationManager.ConnectionStrings["dbconnection"].ConnectionString;
//create new sqlconnection and connection to database by using connection string from web.config file
SqlConnection con = new SqlConnection(strcon);
con.Open();
}
}

VB.NET

Imports
System.Data.SqlClient
Imports System.Configuration
Partial Public Class _Default
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
'Get connection string from web.config file
Dim strcon As String =
ConfigurationManager.ConnectionStrings("dbconnection").ConnectionString
'create new sqlconnection and connection to database by using connection string from web.config file
Dim con As New SqlConnection(strcon)
con.Open()
End Sub
End Class

OK, finish.



About HostForLIFE.eu

HostForLIFE.eu is European Windows Hosting Provider which focuses on Windows Platform only. We deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes.

We have offered the latest Windows 2016 Hosting, ASP.NET Core 2.2.1 Hosting, ASP.NET MVC 6 Hosting and SQL 2017 Hosting.


Tag cloud

Sign in