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

Europe ASP.NET/MVC Hosting :: Creating ASP.NET WebApplication/ASP.NET MVC Application Membership Database on SQL Server Rather Than LocalDb

clock January 21, 2013 03:43 by author Scott

How can a DB be created in SQL Server rather than locally (LocalDb) which is the default?

When you create a new ASP.NET MVC Application (using regular template "Internet") or ASP.NET WebApplication, you will notice the following connection string in the Web.config file:

<add name="DefaultConnection" connectionString="Data Source=(LocalDb)\v11.0;Initial Catalog=aspnet-MvcApplication1-20121005163323;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|\aspnet-
 MvcApplication1-20121005163323.mdf" providerName="System.Data.SqlClient" />


Actually this helps the MVC Application or ASP.NET WebApplication to generate a database locally (within the project's App_Data folder) at run-time for accounts and login management (membership). If however you want to generate this database in SQL Server then you can make some quick changes in the above Web.config file to do that, so here is what you need replace in the above db mapping.

<add name="DefaultConnection" connectionString="Data Source=ITORIAN-PC;Initial Catalog=ASPNETMembership;Integrated Security=True;MultipleActiveResultSets=True;" providerName="System.Data.SqlClient" />

You probably have a different data source so change it before running. Now, run the application and click on the "Register" link to create an account and then you are all done.

Open the SQL Server Management Studio and look at the generated DB for this application.

 



European ASP.NET 4.5 Hosting - Amsterdam :: How to Create ASP.NET Permanent User Login

clock October 16, 2012 08:48 by author Scott

Introduction

This article describes how to create a permanent user login session in ASP.NET. The sample code includes an ASP.NET MVC4 project to control the user registration and login process. But you can use this technique in any type of ASP.NET project.

Forms Authentication


Before getting into the depth of this article, you must be familiar with forms authentication in ASP.NET. The configuration of form authentication resides in web.config file which has the following configuration-file fragment with the assigned values.


<authentication mode="Forms">
      <forms loginUrl="~/Account/LogOn"
             protection="All"
             timeout="1"
             name=".USERLOGINCONTROLAUTH"
             path="/"
             requireSSL="false"
             slidingExpiration="true"
             defaultUrl="~/Home/Index"
             cookieless="UseDeviceProfile"
             enableCrossAppRedirects="false"/></authentication>

The default values are described below:

-
loginUrl points to your application's custom logon page. You should place the logon page in a folder that requires Secure Sockets Layer (SSL). This helps ensure the integrity of the credentials when they are passed from the browser to the Web server.

-
protection is set to All to specify privacy and integrity for the forms authentication ticket. This causes the authentication ticket to be encrypted using the algorithm specified on the machineKey element, and to be signed using the hashing algorithm that is also specified on the machineKey element.

-
timeout is used to specify a limited lifetime for the forms authentication session. The default value is 30 minutes. If a persistent forms authentication cookie is issued, the timeout attribute is also used to set the lifetime of the persistent cookie.

-
name and path are set to the values defined in the application's configuration file.

-
requireSSL is set to false. This configuration means that authentication cookies can be transmitted over channels that are not SSL-encrypted. If you are concerned about session hijacking, you should consider setting requireSSL to true.

-
slidingExpiration is set to true to enforce a sliding session lifetime. This means that the session timeout is periodically reset as long as a user stays active on the site.

-
defaultUrl is set to the Default.aspx page for the application.

-
cookieless is set to UseDeviceProfile to specify that the application use cookies for all browsers that support cookies. If a browser that does not support cookies accesses the site, then forms authentication packages the authentication ticket on the URL.

-
enableCrossAppRedirects is set to false to indicate that forms authentication does not support automatic processing of tickets that are passed between applications on the query string or as part of a form POST.

FormsAuthentication.SetAuthCookie Method

This method creates an authentication ticket for the supplied user name and adds it to the cookies collection of the response, or to the URL if you are using cookieless authentication. The first overload of this function has two parameters:


-
userName: The name of the authenticated user

-
createPersisntentCookie: True to create a persistent cookie (one that is saved across browser sessions); otherwise, false.

This method add a cookie or persistent cookie to the browser with an expire time set in "timeOut" parameter with the name and path set in "name" and "path" parameter. The user will be automatically logged out once the cookie is expired. So the user login session depends on the expire of forms authentication ticket saved in browser cookie. Here, I will create a permanent user login session using this technique.

Cookie Helper

The functionality of this class is to add a form authentication ticket to the browser cookie collection with a life time expiry.


public sealed class CookieHelper
{
    private HttpRequestBase _request;
    private HttpResponseBase _response;

    public CookieHelper(HttpRequestBase request,
      HttpResponseBase response)
      {
            _request = request;
            _response = response;
      }

    //[DebuggerStepThrough()]
    public void SetLoginCookie(string userName,string password,bool isPermanentCookie)
    {
        if (_response != null)
        {
            if (isPermanentCookie)
            {
                FormsAuthenticationTicket userAuthTicket =
                  new FormsAuthenticationTicket(1, userName, DateTime.Now,
                  DateTime.MaxValue, true, password, FormsAuthentication.FormsCookiePath);
                string encUserAuthTicket = FormsAuthentication.Encrypt(userAuthTicket);
                HttpCookie userAuthCookie = new HttpCookie
                  (FormsAuthentication.FormsCookieName, encUserAuthTicket);
                if (userAuthTicket.IsPersistent) userAuthCookie.Expires =
                                    userAuthTicket.Expiration;
                userAuthCookie.Path = FormsAuthentication.FormsCookiePath;
                _response.Cookies.Add(userAuthCookie);
            }
            else
            {
                FormsAuthentication.SetAuthCookie(userName, isPermanentCookie);
            }
        }
    }
}

This function is used in login page or control on the click of login button. In the attached sample project, the following function is written in AccountController class. This function validates the login of the user and then add a permanent form authentication ticket to the browser.

private bool Login(string userName, string password,bool rememberMe)
{
    if (Membership.ValidateUser(userName, password))
    {
        CookieHelper newCookieHelper =
            new CookieHelper(HttpContext.Request,HttpContext.Response);
        newCookieHelper.SetLoginCookie(userName, password, rememberMe);
        return true;
    }
    else
    {
        return false;
    }
}

 



European ASP.NET 4 Hosting - Amsterdam :: How to Fix ValidateRequest="false" in ASP.NET 4

clock September 27, 2012 06:03 by author Scott

If you are someone like me who have recently upgrade to ASP.NET 4.0, you may have come across Yellow Screen of Death with Http Request Validation Exception, something like:

“A potentially dangerous Request.Form value was detected from the client”

Exception Details
: System.Web.HttpRequestValidationException: A potentially dangerous Request.Form value was detected from the client

Surprisingly, you will still see this exception even if you have set ValidateRequest to false in either the Page Tag or Web.Config.


ValidateRequest="false" or  <pages validateRequest="false" />


This may end you being freak out identifying the problem.


The solution is perhaps very simple. I would recommend to go and read
ASP.NET 4 Breaking Changes.

“In ASP.NET 4, by default, request validation is enabled for all requests, because it is enabled before the BeginRequest phase of an HTTP request. As a result, request validation applies to requests for all ASP.NET resources, not just .aspx page requests. This includes requests such as Web service calls and custom HTTP handlers. Request validation is also active when custom HTTP modules are reading the contents of an HTTP request.and therefore request validation errors might now occur for requests that previously did not trigger errors.”


In order to revert to the behavior we had previously, you need to add the following setting in Web.config file:


<httpRuntime requestValidationMode="2.0"/>


And this should work!


Hope this helps!

 



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.



European ASP.NET 4 Hosting - Amsterdam :: How to Solve Error - ASP.NET 4.0 has not been registered on the Web server

clock April 25, 2012 08:07 by author Scott



The above error message indicate that you haven’t configured your ASP.NET 4 on your IIS. To configure IIS7.0 to use ASP.NET 4, please follow this steps:


- Open command prompt under Administrative privileges.

- Navigate to this location C:\Windows\Microsoft.NET\Framework\v4.0.30319.
- Locate aspnet_regiis.exe file.
- Run the utility with –i switch to register ASP.NET 4.0 with IIS7



And you can see it will work now.



European ASP.NET Hosting - Amsterdam :: How to Fix - "Server Error in '/application name' Application" while browsing an asp.net application

clock March 16, 2012 05:38 by author Scott

You may receive the following error message while browsing an asp.net application

"Server Error in '/application name' Application
--------------------------------------------------------------------------------

Runtime Error
Description: An application error occurred on the server. The current custom error settings for this application prevent the details of the application error from being viewed remotely (for security reasons). It could, however, be viewed by browsers running on the local server machine.

Details: To enable the details of this specific error message to be viewable on remote machines, please create a tag within a "web.config" configuration file located in the root directory of the current web application. This tag should then have its "mode" attribute set to "Off". "


This error might occur due to two scenarios.


1. There is an error in the application's logic with the inputformat, Type etc., and you have set the Custom Error Mode in the web.config to "On" and not specified a default redirect error page.


2. The web.config file is not well formed or having invalid characters and the application is not able to pick up the settings from the same.


Solution

1. Set the custom error mode to "Off" to view the error. After rectifying it and before deployment, change it to "On" and specify a default error page, as follows:-


<customErrors defaultRedirect="ErrorPage.aspx" mode="On">
</customErrors>


such that your users will not be able to see the actual error and get your friendly error page where you can politely say "An error has occured! Sorry for the inconvenience ..." .


2. If the above solution is not working (i.e. even after setting the custom error mode to On, the same "Server Error" occurs, then the likely chance is that your web.config file is not well formed and has invalid characters etc.,


To resolve, it copy paste the contents of the file to a notepad, save it as an xml file and try to browse the xml file in the browser. If the xml file is unable to be rendered by the browser and throws error, then you can find the place where the tags are not well formed or invalid character(s) exist and rectify them.


Things worth noting is Web.config is case sensitive and even trailing / leading spaces can cause the above error.


This article applies to .NET - ASP.NET 1.0, 1.1 Versions. Hope it help



European ASP.NET 4 Hosting - Amsterdam :: How to Fix Error - An ASP.NET setting has been detected that does not apply in Integrated managed pipeline mode

clock March 1, 2012 10:01 by author Scott

Sometime when you try to setup a application for your website on IIS7 you get following error when you load your website.



This happens when ASP.NET modules and handlers should be specified in the IIS and configuration sections in Integrated mode. This problem can be fixed using following workaround


1) Change application configuration: First way to fix this issue is to migrate the application configuration to work properly in Integrated mode. You can use “
AppCmd“ command to migrate the application configuration:

%windir%/system32/inetsrv/>Appcmd migrate config “<AppPath>


Where “
<AppPath>“ is the virtual path of the application, such as “Default Web Site/virtualapp1“.

2) Modify web.config: You have to manually move the customer entries in the
<system.web>/<httpModules> and configuration to the <system.web>/<httpHandlers><system.webServer>/<handlers> and <system.webServer>/<modules> configuration sections, and either remove the <httpHandlers> and <httpModules> configuration OR add the following to your application’s or websites web.config:

<system.webServer>
<validation validateIntegratedModeConfiguration=”false”/>
</system.webServer>


3) Switch to Classic ASP.NET: Switch the website or application to an application pool that is configured to run in Classic ASP.NET mode. To move back to classic mode go to
IIS7 Manager >> Select the site (which you want to switch) >> edit settings and you will get following screen



Press “
Select” button which will open a window “Select Application Pool” (check below image); Select “Classic .NET AppPool” from the drop-down and press OK.



Now try to Access your website/application.



European ASP.NET 4 Hosting :: How to Redirect From domain.com to www.domain.com in ASP.NET

clock February 21, 2012 07:35 by author Scott

If you want to redirect from domain.com to www.domain.com in asp.net application, then you can do it through IIS settings, but you can do it through code file also. You can write the code in the global.asax file in the Application_BeginRequest method.

void Application_BeginRequest(object sender, EventArgs e)
    {
        string FromHomeURL = "http://yourdomain.com";
        string ToHomeURL = "http://www.yourdomain.com";


       if (HttpContext.Current.Request.Url.ToString().ToLower().Contains(FromHomeURL))
        {
            HttpContext.Current.Response.Status = "301 Moved Permanently";
            HttpContext.Current.Response.AddHeader("Location",
            Request.Url.ToString().ToLower().Replace(FromHomeURL, ToHomeURL));
        }
}



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