ASP.NET 4.5 and ASP.NET Core 1 Hosting BLOG

Tutorial and Articles about ASP.NET 4.0 and the latest ASP.NET 4.5 Hosting

ASP.NET Hosting - ASPHostPortal.com :: How to Configure ASP.NET Core Project

clock December 9, 2016 10:09 by author Dan

According to tutorialspoint website about the configuration related to ASP.NET Core project. In Solution Explorer, you will see the Startup.cs file. If you have worked with previous versions of ASP.NET Core, you will probably expect to see a global.asax file, which was one place where you could write codes to execute during startup of a web application.

  • You would also expect to see a web.config file containing all the configuration parameters your application needed to execute.
  • In ASP.NET Core those files are all gone, and instead of configuration and startup code are loaded from Startup.cs.
  • There is a Startup class inside the file and in this class you can configure your application and even configure your configuration sources.

Here is the default implementation in the Startup.cs file.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;

using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging; 

namespace FirstAppDemo {
   public class Startup {
      // This method gets called by the runtime.
      // Use this method to add services to the container.
      // For more information on how to configure your application,
      // visit http://go.microsoft.com/fwlink/?LinkID=398940
      public void ConfigureServices(IServiceCollection services) {
      } 
     
      // This method gets called by the runtime. Use this method to configure
      // the HTTP request pipeline.
      public void Configure(IApplicationBuilder app, IHostingEnvironment env,
         ILoggerFactory loggerFactory) {
         loggerFactory.AddConsole(); 
        
         if (env.IsDevelopment()) {
            app.UseDeveloperExceptionPage();
         } 
         app.Run(async (context) => {
            await context.Response.WriteAsync("Hello World!");
         });
      }
   }
}


In the Startup class, there are two methods where most of our work will take place. The Configure method of the class is where you build your HTTP processing pipeline.

  • This defines how your application responds to requests. Currently this application can only say Hello World! and if we want the application to behave differently, we will need to change the pipeline around by adding additional code in this Configure method.
  • For example, if we want to serve the static files such as an index.html file, we will need to add some code to the Configure method.
  • You can also have an error page or route requests to an ASP.NET MVC controller; both of these scenarios will also require to do some work in this Configure method.
  • In the Startup class, you will also see the ConfigureServices() method. This helps you configure components for your application.

Right now, we have a hard-coded string for every response — the Hello World! string. Instead of hard-coding the string, we want to load this string from some component that knows the text that we want to display.

  • This other component might load that text from a database or a web service or a JSON file, it doesn't matter where exactly it is.
  • We will just set up a scenario so that we do not have this hard-coded string.

In the Solution Explorer, right-click on your project node and select Add → New Item.

In the left pane, select Installed → Code and then in the middle pane, select the JSON File. Call this file AppSettings.json and click on the Add button as in the above screenshot.

We can also have our program read the text from the file instead of having the Hello World! String in Startup.cs. Let us add the following code in AppSettings.json file.

{
   "message": "Hello, World! this message is from configuration file..."
}


Now we need to access this message from the Startup.cs file. Here is the implementation of the Startup.cs file which will read the above message from the JSON file.

using Microsoft.AspNet.Builder;
using Microsoft.AspNet.Hosting;
using Microsoft.AspNet.Http;

using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Configuration; 

namespace FirstAppDemo {
   public class Startup {
      public Startup() {
         var builder = new ConfigurationBuilder()  
            .AddJsonFile("AppSettings.json");
         Configuration = builder.Build();
      } 
      public IConfiguration Configuration { get; set; } 
     
      // This method gets called by the runtime.
      // Use this method to add services to the container.
      // For more information on how to configure your application,
      // visit http://go.microsoft.com/fwlink/?LinkID=398940
      public void ConfigureServices(IServiceCollection services) {
      } 
     
      // This method gets called by the runtime. 
      // Use this method to configure the HTTP request pipeline.
      public void Configure(IApplicationBuilder app) {
         app.UseIISPlatformHandler(); 
         app.Run(async (context) => {
            var msg = Configuration["message"];
            await context.Response.WriteAsync(msg);
         }); 
      } 
       
      // Entry point for the application.
      public static void Main(string[] args) =7gt; WebApplication.Run<Startup>(args);
   }
}


Let us now run the application. Once you run the application, it will produce the following output.

Best ASP.NET Hosting Recommendation

ASPHostPortal.com provides its customers with Plesk Panel, one of the most popular and stable control panels for Windows hosting, as free. You could also see the latest .NET framework, a crazy amount of functionality as well as Large disk space, bandwidth, MSSQL databases and more. All those give people the convenience to build up a powerful site in Windows server. ASPHostPortal.com offers ASP.NET hosting starts from $1/month only. They also guarantees 30 days money back and guarantee 99.9% uptime. If you need a reliable affordable ASP.NET Hosting, ASPHostPortal.com should be your best choice.



ASP.NET Hosting - ASPHostPortal.com :: How to set Defaultbutton property in ASP.NET

clock December 2, 2016 07:09 by author Dan

According to DotNetTricks website, Suppose, you want to press/click submit button on Enter key press or you are trying to post the form on Enter key press. In asp.net, to achieve this functionality we need to set "Defaultbutton" property either in Form or in panel.

Form DefaultButton Property

    <form id="form1" runat="server" defaultbutton="btnSubmit">
    <div>
    <asp:TextBox ID="txtUserID" runat="server"/> <asp:TextBox ID="txtUserpwd" runat="server"/> <asp:Button ID="btnSubmit" runat="server" OnClick="btnSubmit _Click" Text="Submit"/>
    </div>
    </form>


Panel DefaultButton Property

    <asp:Panel ID="Panel1" runat="server" defaultbutton="btnSubmit">
    <div>
    <asp:TextBox ID="txtUserID" runat="server"/> <asp:TextBox ID="txtUserpwd" runat="server"/> <asp:Button ID="btnSubmit" runat="server" OnClick="btnSubmit _Click" Text="Submit"/>
    </div>
    </asp:Panel >


Note

  • We specify the defaultbutton property at the Form level in the form tag when there is only one Submit Button for post back.
  • We specify the defaultbutton property at the Panel level in the Panel tag when there are multiple Submit Button for post back.

Summary

In this article I try to explain the default submit behavior of form and panel. I hope you will refer this article for your need.

Best ASP.NET Hosting Recommendation

ASPHostPortal.com provides its customers with Plesk Panel, one of the most popular and stable control panels for Windows hosting, as free. You could also see the latest .NET framework, a crazy amount of functionality as well as Large disk space, bandwidth, MSSQL databases and more. All those give people the convenience to build up a powerful site in Windows server. ASPHostPortal.com offers ASP.NET hosting starts from $1/month only. They also guarantees 30 days money back and guarantee 99.9% uptime. If you need a reliable affordable ASP.NET Hosting, ASPHostPortal.com should be your best choice.



ASP.NET Hosting - ASPHostPortal.com :: How to Solve Unexpected Error in ASP.NET

clock November 25, 2016 10:06 by author Dan

According to dotnettricks website, Some times after hosting web application on the server, we get unexpected error as shown in the below fig. But we did get the detailed message for the unexpected errror. In this article, I would like to share how can we get detailed message for the unexpected error.

This type of unexpected error may occurs on local or remote server. In asp.net, we can find the exact error message by setting mode="Off" with in customErrors tag in web.config of our application. This is the way by which we can find out the exact error in our web application.

     <system.web>
    <customErrors mode="Off">
     </customErrors>
     ...
     ...
     </system.web>


When we set the customErrors mode="Off" then we can easily track the error in the application as shown in the fig.

In Asp.net, there are three error modes to trace an error. These modes decide whether or not an error message is displayed. RemoteOnly mode is default mode for displaying error messages.

Off Mode

This mode is responsible for displaying error mesage on local and remote server in case of an error.

On Mode

This mode is responsible for displaying custom error page with message on local and remote server in case of an error. By using this mode, we can show our own custom error messages page for specific errors on local and remote server.

RemoteOnly

This mode is responsible for displaying error mesage on remote server only in case of an error. By using this mode, we can show our own custom error messages page for specific errors on remote server only.

Best ASP.NET Hosting Recommendation

ASPHostPortal.com provides its customers with Plesk Panel, one of the most popular and stable control panels for Windows hosting, as free. You could also see the latest .NET framework, a crazy amount of functionality as well as Large disk space, bandwidth, MSSQL databases and more. All those give people the convenience to build up a powerful site in Windows server. ASPHostPortal.com offers ASP.NET hosting starts from $1/month only. They also guarantees 30 days money back and guarantee 99.9% uptime. If you need a reliable affordable ASP.NET Hosting, ASPHostPortal.com should be your best choice.



ASP.NET Hosting - ASPHostPortal.com :: All About ASP.NET DBNull Value

clock November 18, 2016 10:14 by author Dan

According to asp.net-informations website, The DBNull represents an uninitialized variant or nonexistent database column. It is not the number zero or it is not an empty string value. DBNull is a singleton class, which means only this instance of this class can exist. The DBNull.Value member represents the sole DBNull object.

In many situations while reading data from DataSource, we have seen the error message like the following :

  Conversion from type 'DBNull' to type '' is not valid

This message is getting because the ASP.NET program unable to handle DBNull value. In these cases you can determine whether a value retrieved from a database field is a DBNull value by passing the value of that field to the DBNull.Value.Equals method.

vb.net

  If IsDBNull(ds.Tables(0).Rows(i).Item(0)) Then
    Label1.Text = "DBNULL exist in the field "

  End If


C#

  if (ds.Tables[0].Rows[0].ItemArray[0] == System.DBNull.Value)
  {
    Label1.Text = "DBNULL exist in the field ";

  }


The following ASP.NET program is checking wether the retrieved values is DBNull.

Default.aspx

<!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 id="Head1" runat="server">
    <title>Untitled Page</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <asp:Button ID="Button1" runat="server" Text="Button" onclick="Button1_Click" />
    <br />
    <asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
    </div>
    </form>
</body>
</html>

Best ASP.NET Hosting Recommendation

ASPHostPortal.com provides its customers with Plesk Panel, one of the most popular and stable control panels for Windows hosting, as free. You could also see the latest .NET framework, a crazy amount of functionality as well as Large disk space, bandwidth, MSSQL databases and more. All those give people the convenience to build up a powerful site in Windows server. ASPHostPortal.com offers ASP.NET hosting starts from $1/month only. They also guarantees 30 days money back and guarantee 99.9% uptime. If you need a reliable affordable ASP.NET Hosting, ASPHostPortal.com should be your best choice



ASP.NET Hosting - ASPHostPortal.com :: How To Create a Connection String and Working with SQL Server LocalDB

clock November 15, 2016 07:16 by author Armend

Creating a Connection String and Working with SQL Server LocalDB

The MovieDBContext class you created handles the task of  connecting to the database and mapping Movie objects to database  records. One question you might ask, though, is how to specify which database it will connect to. You don't actually have to specify which database to use,  Entity Framework will default to using  LocalDB. In this section we'll explicitly add  a connection string in the Web.config file of the application.

SQL Server Express LocalDB

LocalDB is a lightweight version of the SQL Server Express Database Engine that starts on demand and runs in user mode. LocalDB runs in a special execution mode of SQL Server Express that enables you to  work with databases as .mdf files. Typically, LocalDB database files  are kept in the App_Data folder of a web project.
SQL Server Express is not recommended for use in production web applications. LocalDB in particular should not be used for production with a web application because it is not designed to work with IIS. However, a LocalDB  database can be easily migrated to SQL Server or SQL Azure.
In Visual Studio 2013 (and in 2012), LocalDB is installed by default with Visual Studio.
By default, the Entity Framework looks for a connection string named the same as the object context class (MovieDBContext for this project).  For more  information see  SQL Server Connection Strings for ASP.NET Web Applications.
Open the application root Web.config file shown below. (Not the Web.config file in the Views folder.)

 

Find  the <connectionStrings>  element:

 

Add the following connection string to the <connectionStrings>  element in the Web.config file.

<add name="MovieDBContext"
   connectionString="Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\Movies.mdf;Integrated Security=True"
   providerName="System.Data.SqlClient"
/>

The following example shows a portion of the Web.config file with  the new connection string added:

<connectionStrings>
    <add name="DefaultConnection" connectionString="Data Source=(LocalDb)\v11.0;AttachDbFilename=|DataDirectory|\aspnet-MvcMovie-20130603030321.mdf;Initial Catalog=aspnet-MvcMovie-20130603030321;Integrated Security=True" providerName="System.Data.SqlClient" />
    <add name="MovieDBContext"    connectionString="Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\Movies.mdf;Integrated Security=True" providerName="System.Data.SqlClient"
/>

The two connection strings are very similar. The first connection string is  named DefaultConnection and is used for the membership database to control who can access the application. The connection string you've added specifies a LocalDB database named Movie.mdf located in the App_Data  folder.  We won't use the membership database in this tutorial, for more information on membership, authentication and security, see my tutorial Create an ASP.NET MVC app with auth and SQL DB and deploy to Azure App Service.
The name of the connection string must match the name of the DbContext class.

using System;
using System.Data.Entity;
namespace MvcMovie.Models
{
    public class Movie
    {
        public int ID { get; set; }
        public string Title { get; set; }
        public DateTime ReleaseDate { get; set; }
        public string Genre { get; set; }
        public decimal Price { get; set; }
    }

    public class MovieDBContext : DbContext
    {
        public DbSet<Movie> Movies { get; set; }
    }
}

You don't actually need to add the MovieDBContext connection string. If you don't specify a connection string, Entity Framework will create a LocalDB database in the users directory with the fully qualified name of the DbContext class (in this case MvcMovie.Models.MovieDBContext). You can name the database anything you like, as long as it has the .MDF  suffix. For example, we could name the database MyFilms.mdf.
Next, you'll build a new MoviesController class that you can use  to display the movie data and allow users to create new movie listings.

Best ASP.NET Hosting Recommendation

ASPHostPortal.com provides its customers with Plesk Panel, one of the most popular and stable control panels for Windows hosting, as free. You could also see the latest .NET framework, a crazy amount of functionality as well as Large disk space, bandwidth, MSSQL databases and more. All those give people the convenience to build up a powerful site in Windows server. ASPHostPortal.com offers ASP.NET hosting starts from $1/month only. They also guarantees 30 days money back and guarantee 99.9% uptime. If you need a reliable affordable ASP.NET Hosting, ASPHostPortal.com should be your best c



ASP.NET Hosting - ASPHostPortal.com :: Handle Multiple Submit Buttons On The Same Form in MVC 6

clock November 8, 2016 07:11 by author Armend

In this post we will explain you about Handling multiple submit buttons on the same form in MVC.To fix this problem, I’m progressing to justify the varied techniques for handling multiple buttons on the same form in Sometimes you got situation like more than one submit buttons on a similar form in ASP.NET MVC 6. At that point, How we will handle the click event of every and each buttons on your form? Suppose you’ve got a user Login form.

On the above picture, we have the SignUp, SignIn and the Cancel buttons. Suppose on Signup button click you have to open Signup window & on SignIn button click you have to open Login window and on Cancel button click you are returning to home page. For handling all of the above buttons, we have the following methods:

  • Export Gridview to Excel: Gridview to Excel
  • Insert,Update,Delete in ModalPopup CRUD operation in ModalPopup
  • Read and Write in Text File in ASP.NET Read and Write File in ASP.NET

Now, Make the view Form with Multiple Button in Home Folder with the following code.

MultipleCommand.cshtml
@model Mvc4_Multiple_Submit_Button.Models.RegistrationModel
@{
ViewBag.Title = "Handling Multiple Command Buttons";
}
<script src="../../Scripts/jquery-1.7.1.min.js" type="text/javascript"></script>
<script src="../../Scripts/jquery.validate.min.js" type="text/javascript"></script>
<script src="../../Scripts/jquery.validate.unobtrusive.min.js" type="text/javascript"></script>
<h2>User's Signup Form</h2>
@using (Html.BeginForm("MultipleCommand", "Home", FormMethod.Post, new { id = "submitForm" }))
{
<fieldset>
<legend>Registration Form</legend>
<ol>
<li>
@Html.LabelFor(m => m.Name)
@Html.TextBoxFor(m => m.Name, new { maxlength = 50 })
@Html.ValidationMessageFor(m => m.Name)
</li>
<li>
@Html.LabelFor(m => m.Address)
@Html.TextAreaFor(m => m.Address, new { maxlength = 200 })
@Html.ValidationMessageFor(m => m.Address)
</li>
<li>
@Html.LabelFor(m => m.MobileNo)
@Html.TextBoxFor(m => m.MobileNo, new { maxlength = 10 })
@Html.ValidationMessageFor(m => m.MobileNo)
</li>
</ol>
<button type="submit" id="btnSave" name="Command" value="Save">
Save</button>
<button type="submit" id="btnSubmit" name="Command" value="Submit">
Submit</button>
<button type="submit" id="btnCancel" name="Command" value="Cancel" onclick="$('#submitForm').submit()">
Cancel (Server Side)</button>
<button type="submit" id="btnCancelSecForm" name="Command" value="Cancel" onclick="$('#cancelForm').submit()">
Cancel (Server Side by Second Form)</button>
<button name="ClientCancel" type="button" onclick=" document.location.href = $('#cancelUrl').attr('href');">
Cancel (Client Side)</button>
<a id="cancelUrl" href="@Html.AttributeEncode(Url.Action("Index", "Home"))" style="display:none;">
</a>
</fieldset>
}
@using (Html.BeginForm("MultipleButtonCancel", "Home", FormMethod.Post, new { id = "cancelForm" })) { }

Next step, in Homecontroller include the MultipleCommand Method to handle the multiple button with the following code.

HomeController.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Mvc4_Multiple_Submit_Button.Models;
namespace Mvc4_Multiple_Submit_Button.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
public ActionResult MultipleCommand()
{
return View();
}
[HttpPost]
public ActionResult MultipleCommand(RegistrationModel mReg, string Command)
{
if (Command == "Save")
{
//TO DO : for Save button Click
}
else if (Command == "Submit")
{
//TO DO : for Submit button Click
}
else
{
//TO DO : for Cancel button Click
return RedirectToAction("Index");
}
return View();
}
[HttpPost]
public ActionResult MultipleButtonCancel()
{
//TO DO : for Cancel button Click
return RedirectToAction("Index");
}
}
}


Best ASP.NET Hosting Recommendation

ASPHostPortal.com provides its customers with Plesk Panel, one of the most popular and stable control panels for Windows hosting, as free. You could also see the latest .NET framework, a crazy amount of functionality as well as Large disk space, bandwidth, MSSQL databases and more. All those give people the convenience to build up a powerful site in Windows server. ASPHostPortal.com offers ASP.NET hosting starts from $1/month only. They also guarantees 30 days money back and guarantee 99.9% uptime. If you need a reliable affordable ASP.NET Hosting, ASPHostPortal.com should be your best choice



ASP.NET Hosting - ASPHostPortal.com :: Easy steps to delete duplicate rows from table in sql server

clock November 4, 2016 11:25 by author Dan

Based on ASP.NET Corner blog. I have two columns Name and Age in my Table(MyTable). From the MyTable I want to delete only duplicate records. So the below Query will help you to delete or remove the duplicate rows from the MyTable.

Below is MyTable output:

SELECT * FROM MyTable

Current output:

Name    Age
vijay    30
antony    40
Aruna    28
antony    40
chander35
mark    42
vijay    30

Remove duplicate rows from the table:
The below query will help you to delete duplicate row from your table. Here we used Row_Number() function and PARTITION BY key words to remove the duplicate rows.

DELETE SUB FROM
(SELECT ROW_NUMBER() OVER (PARTITION BY Name, Age ORDER BY Name) cnt
 FROM MyTable) SUB
WHERE SUB.Cnt > 1


After the query execution the output is:

Name    Age
Aruna    28
antony    40
chander    35
mark    42
vijay    30

How to use Row_Number in SQL Select query:

SELECT ROW_NUMBER() OVER(ORDER BY Age) FROM mytable

Best ASP.NET Hosting Recommendation

ASPHostPortal.com provides its customers with Plesk Panel, one of the most popular and stable control panels for Windows hosting, as free. You could also see the latest .NET framework, a crazy amount of functionality as well as Large disk space, bandwidth, MSSQL databases and more. All those give people the convenience to build up a powerful site in Windows server. ASPHostPortal.com offers ASP.NET hosting starts from $1/month only. They also guarantees 30 days money back and guarantee 99.9% uptime. If you need a reliable affordable ASP.NET Hosting, ASPHostPortal.com should be your best choice



ASP.NET Hosting - ASPHostPortal.com :: How to publish ASP.NET Core web application via Visual Studio 2015

clock November 3, 2016 07:04 by author Armend

How to publish ASP.NET Core web application via Visual Studio 2015

Create a web app
From the Visual Studio Start page, tap New Project.
In the center pane, tap ASP.NET Core Web Application (.NET Core) Create a web app

In the New ASP.NET Core Web Application dialog, tap Web Application, and then tap OK.

 

Login to your hosting control panel --> Websites --> Select the target site --> click Show Web Deploy Info. If you have not enable this feature, please enable it first at the same place. You will able to see the web deploy settings there or download the publishing xml configuration file directly.
And then open your web application with Visual Studio 2015, right click the web application, then click"Publish" to start.
You can chose Import  with Publish XML and Custom to fill in the deploy info.

Click Validate Connections to check the deploy info,then you can tap Publish.

Note:If you get certificate error with publish,please add below code to your PublishProfiles.
<AllowUntrustedCertificate>True</AllowUntrustedCertificate>

 

Best ASP.NET Hosting Recommendation

ASPHostPortal.com provides its customers with Plesk Panel, one of the most popular and stable control panels for Windows hosting, as free. You could also see the latest .NET framework, a crazy amount of functionality as well as Large disk space, bandwidth, MSSQL databases and more. All those give people the convenience to build up a powerful site in Windows server. ASPHostPortal.com offers ASP.NET hosting starts from $1/month only. They also guarantees 30 days money back and guarantee 99.9% uptime. If you need a reliable affordable ASP.NET Hosting, ASPHostPortal.com should be your best choice

Save



ASP.NET Core 1.0.1 Hosting - ASPHostPortal.com :: Easy Steps to restart IIS in command line

clock October 21, 2016 12:11 by author Dan

According to ASP.NET Corner blog, Some time we need to restart the IIS to certain configuration changes take effect in the IIS server. There are different methods available to reset or restart the IIS. The below example will help you to restart IIS in command line.

How to restart IIS in command line:

From the Start menu, click Run and type iisreset . This is the simplest method to restart the IIS. The below list will help you to do other works in IIS.

To restart IIS using the IIS Restart command-line utility

1. From the Start menu, click Run.
2. In the Open box, type cmd, and click OK.
3. At the command prompt, type iisreset , and press ENTER.

The below examples for other way of managing IIS

• iisreset /stop – Stop the IIS services
• iisreset /start – Start the IIS services
• IISreset /restart - Stop and then restart all Internet services.
• iisreset /status - will show the current status of IIS
• iisreset /noforce - will prevent the server from forcing close applications and process. This can cause IIS to reset slower but is more graceful.
• iisreset /disable - this command disables IIS and prevents all iisreset calls from executing
• iisreset /enable - to re-enable the IIS Admin service
• iisreset /REBOOT - Reboot the computer.
• iisreset /REBOOTONERROR - Reboot the computer if an error occurs when starting, stopping, or restarting Internet services.
• iisreset /NOFORCE - Do not forcefully terminate Internet services if attempting to stop them gracefully fails.

Best ASP.NET Hosting Recommendation

ASPHostPortal.com provides its customers with Plesk Panel, one of the most popular and stable control panels for Windows hosting, as free. You could also see the latest .NET framework, a crazy amount of functionality as well as Large disk space, bandwidth, MSSQL databases and more. All those give people the convenience to build up a powerful site in Windows server. ASPHostPortal.com offers ASP.NET hosting starts from $1/month only. They also guarantees 30 days money back and guarantee 99.9% uptime. If you need a reliable affordable ASP.NET Hosting, ASPHostPortal.com should be your best choice.



ASP.NE Hosting - ASPHostPortal.com :: Easy Ways to dynamically update web config file in asp.net?

clock September 30, 2016 19:48 by author Dan

I want to configure my web config connection string in my aspx page. That mean I want to change my web.config file dynamically. User can change the connection string any time without touching the server. For that the below asp.net c# code will help you to change connection string , appsetting information and ect..  in dynamically.

private void SetConfigSettings()
        {
            try
            {
                // App setting settings
                System.Configuration.Configuration config = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("~");

                //APPsetting value change
                System.Configuration.KeyValueConfigurationElement setting = config.AppSettings.Settings["SupportFormat"];
                if (null != setting)
                    config.AppSettings.Settings["SupportFormat"].Value = txtFormat.Text.Trim();

                //APPsetting value change
                System.Configuration.KeyValueConfigurationElement Pathsetting = config.AppSettings.Settings["Path"];
                if (null != Pathsetting)
                    config.AppSettings.Settings["Path"].Value = txtPath.Text.Trim();


                //Connection string changes
                string newConnectionString = "Data Source=" + txtServer.Text + ";Initial Catalog='" + txtDatabaseName.Text.Replace("'", "") + "';User ID=" + txtUserName.Text + ";Password=" + txtPassword.Text + ";Persist Security Info=True;";

                //Configuration openWebConfiguration = WebConfigurationManager.OpenWebConfiguration("~");
                ConnectionStringsSection sections = config.GetSection("connectionStrings") as ConnectionStringsSection;
                if (sections != null)
                {
                    sections.ConnectionStrings["ConString"].ConnectionString = newConnectionString;
                    ConfigurationManager.RefreshSection("ConString");

                }
                config.Save();

                lblMSG.Text = "Updated successfully!!!";
                lblMSG.ForeColor = Color.Green;
            }
            catch (System.Exception exc)
            {
                lblMSG.Text = exc.Message;
                lblMSG.ForeColor = Color.Red;
            }
        }

Best ASP.NET Hosting Recommendation

ASPHostPortal.com provides its customers with Plesk Panel, one of the most popular and stable control panels for Windows hosting, as free. You could also see the latest .NET framework, a crazy amount of functionality as well as Large disk space, bandwidth, MSSQL databases and more. All those give people the convenience to build up a powerful site in Windows server. ASPHostPortal.com offers ASP.NET hosting starts from $1/month only. They also guarantees 30 days money back and guarantee 99.9% uptime. If you need a reliable affordable ASP.NET Hosting, ASPHostPortal.com should be your best choice.



Cheap ASP.NET 4.5 Hosting

We’re a company that works differently to most. Value is what we output and help our customers achieve, not how much money we put in the bank. It’s not because we are altruistic. It’s based on an even simpler principle. "Do good things, and good things will come to you".

Success for us is something that is continually experienced, not something that is reached. For us it is all about the experience – more than the journey. Life is a continual experience. We see the Internet as being an incredible amplifier to the experience of life for all of us. It can help humanity come together to explode in knowledge exploration and discussion. It is continual enlightenment of new ideas, experiences, and passions


Author Link


 

Corporate Address (Location)

ASPHostPortal
170 W 56th Street, Suite 121
New York, NY 10019
United States

Tag cloud

Sign in