Windows 2012 Hosting - MVC 6 and SQL 2014 BLOG

Tutorial and Articles about Windows Hosting, SQL Hosting, MVC Hosting, and Silverlight Hosting

ASP.NET Hosting :: Using ADO.NET Entity Framework 4.1 with SQL Server Compact 4.0

clock September 30, 2013 07:01 by author Mike

ADO.NET Entity Framework, an object-relational mapper (ORM) built into the .NET framework, provides an easy way to map your classes into a database tables and vice versa.

SQL Server Compact (CE)
Yet another useful small scale tool. Of course you can map your entities into a full robust database. There are a number of pre-built providers, not counting Microsoft SQL and SQL Express (the default). I've chosen to use MS SQL Server Compact as a first option (later to be replaced or give the user/administrator the option to set a different provider) mainly because it's super-lightweight, builds the database in a file, and does not require heavy installation and licenses. It's free and is supported by mobile devices. For small applications it may be sufficient. For larger scale apps perhaps not so much.

Prerequisites checklist

  • ADO.NET Entity Framework 4.1, available here.
  • Microsoft SQL Server Compact 4.0, available here.
  • MS SQL Server CE has no fancy management application (like MS SQL Server Management Studio for more robust SQL Server versions) and it is not natively browsable from Visual Studio. 
    However, in order to query your tables and see what's going on, I recommend using SQL Server Compact Toolbox Visual Studio extension, available here.
    Mind you that in order for it to run properly, you will need to have both SQL Server CE 4.0 (from the link above) and the SQL Server CE 3.5 SP2 runtime from here installed on your machine.
    If you are running a 64 bit version of Windows, you will have to download, extract and install both the 32 bit and the 64 bit versions of the SQL Server CE 3.5 SP2.

Project references
Once all prerequisites are in place, the following assembly references are to be added to the project:

  • EntityFramework
    Should reside in the folder where the Microsoft ADO.NET Entity Framework 4.1 has been installed. By default it would be something like:
    C:\Program Files (x86)\Microsoft ADO.NET Entity Framework 4.1\Binaries\
  • System.ComponentModel.DataAnnotations
    This is required in order to use data attributes for annotating your persisted class properties, such as [Key] to denote a primary key property.

Code first: Data classes
The approach I'm implementing here assumes you have the data classes created first, and wish to map those into database tables. There are ways to implement in the opposite direction, meaning you have your database and wish to create corresponding classes ("Model first"). I'll use a simple structure of a Person class and Company class.
The simpler of the two is the company class, which consists of 2 properties: an ID and a name.

public class Company
{
    public Company()
    {
 
    }
 
    public Company(Guid companyId, string companyName)
    {
        this.CompanyId = companyId;
        this.CompanyName = companyName;
    }
 
    [KeyColumn(Order =1)]
    public Guid CompanyId { getset; }
 
    [KeyColumn(Order = 2)]
    public string CompanyName { getset; }
}

A few points to note, though:

  • Notice it has an empty default constructor with no arguments. Even if this constructor does nothing, it is required for reconstructing the object once it's fetched back from the database.
  • For this example, I've defined  both public properties, CompanyId and CompanyName as parts of a compound primary key.  It is also necessary to order the key parts as demonstrated here.

For this demo, I've also included a simple enum. Enums were quite clumsy to use in previous CTP versions of the Entity Framework, but as of version 4.x they are supported more easily.
Hence the following enum is also defined:

public enum Prefix 
{ 
    Mr,
    Ms,
    Mrs,
    Dr
}


The Person class:

public class Person
{
    public Person()
    {
 
    }
 
    public Person(Guid personId, string name, int age, Prefix pref, Company workplace)
    {
        this.PersonId = personId;
        this.Name = name;
        this.Age = age;
        this.NamePrefix = pref;
        this.Workplace = workplace;
    }
 
    [Key]
    public Guid PersonId { getset; }
 
    public string Name { getset; }
 
    public int Age { getset; }
 
    public Company Workplace { getset; }
 
    [Required]
    public virtual Prefix NamePrefix { getset; }
 
    public virtual int NamePrefixId
    {
        get { return (int)NamePrefix; }
        set { NamePrefix = (Prefix)value; }
    }
}

 

  • A more complex class. It has a member of type Company.
  • It has 2 member properties: NamePrefix and NamePrefixId, which relate to the enum of type Prefix. The NamePrefixId member is a helper for translating the enum to/from int, which is the actual underlying type which will be stored in the database.
  • It also has an empty default non-argumentative constructor for the sake of reconstructing the retrieved object.

Database context
This class is required as a management context for our persisted objects against the framework. It inherits DbContext and its properties, which are of the generic DbSet type represent the queryable collections of the persisted objects.

public class PersonsContext : DbContext
{
    public PersonsContext()
        : base(PersonsContext.ConnectionString)
    {
    }
 
    public DbSet<Person> Persons { getset; }
    public DbSet<Company> Companies { getset; }
 
    public static string ConnectionString
    {
        get
        {
            return @"Data Source=" + 
                System.Reflection
                    .Assembly
                    .GetExecutingAssembly()
                    .Location
                    .Substring(0, 
                        System
                        .Reflection
                        .Assembly
                        .GetExecutingAssembly()
                        .Location
                        .LastIndexOf("\\") + 1) 
                + @"\\people.sdf";
        }
    }
}

Furthermore:

  • Notice the constructor.
    It invokes the base class constructor, providing a simple connection string to our database.
    It could have also provided the name of a connection string from the App.Config file, or it could provide no connection string at all (in which case our database would be created on the local instance of SQL Express, with a name similar to our executing application.
  • The connection string provided here corresponds with MS SQL Compact, and refers to a database file, people.sdf, which is expected to be created/found on the same folder of our application's assembly (If debug/run the solution from Visual Studio, the folder would be Bin\Debug by default)

Showing the seeds
Many times when we run a newly built database-oriented application, we'd want to start with some predefined data already stored in the database. If we generate the database manually with some SQL script, we could easily include some INSERT statements in order to generate and store the initial data. In the case of Entity Framework, we can generate and store our initial data by creating the following class:

public class DatabaseInitializer : CreateDatabaseIfNotExists<PersonsContext>
{
    protected override void Seed(PersonsContext context)
    {
        Company telerik = new Company(Guid.NewGuid(), "Telerik");;
        Person alon = new Person(Guid.NewGuid(), "Alon", 38, Prefix.Mr, telerik);
 
        context.Companies.Add(telerik);
        context.Persons.Add(alon);
 
        context.SaveChanges();
    }
}

Notice:

  • This class inherits the generic CreateDatabaseIfNotExists class. This is the default policy of the Entity Framework (to create the database if it does not already exist). Other options are listed on the MSDN library.
  • We override the Seed method, and populate the context argument with our predefined objects. Once the new database is created, this data should be automatically inserted into the underlying tables. In this case, one company (telerik) and one person (alon) are created and seeded.

Helper classes

Now almost everything is in its right place. We will need to tie everything together, though. I love helper classes. They are just so damn helpful. I've created this helper class in order to simplify and wrap the interaction with the data context nicely.

public class DataManager
{
    public static PersonsContext DataContext
    {
        get
        {
            if (DataManager.dataContext == null)
            {
                Database.DefaultConnectionFactory = new SqlCeConnectionFactory("System.Data.SqlServerCe.4.0");
                DataManager.dataContext = new PersonsContext();
                bool dbExists = DataManager.dataContext.Database.Exists();
                if (dbExists)
                {
                    //UpgradeScript();
                }
                if (!dbExists)
                {
                    Database.SetInitializer(new DatabaseInitializer());
                }
                else
                    Database.SetInitializer<PersonsContext>(null);
            }
            return DataManager.dataContext;
        }
    }
    private static PersonsContext dataContext = null;
}

About this class:

  • The main purpose here is to statically cache (in memory) and manage our PersonsContext object. A few important settings are also applied here:Setting the default database factory to SQL Server Compact (SqlServerCe).
  • If the database does not exist, an initializer of type DatabaseInitializer is assigned. That is, the seeding class defined above will kick in and create the persisted entities in the database.
  • If the database already exists, no initializer is assigned, but I'm leaving the option to run upgrade scripts (i.e. check the version of our data and apply changes in the database schema according to changes in our persisted classes and/or seeded data to match the current product version) if they are needed.
    Those should manipulate tables, and need to be run directly against the database.

Manipulations
To demonstrate the ease of use of this shameless production and manipulation through basic CRUD operations, I've constructed a small console application. Here is its main function:

class Program
{
    static void Main(string[] args)
    {
        //Check seeding:
        Console.WriteLine("{0} persons are in your database.\n"DataManager.DataContext.Persons.Count());
 
        //Basic CRUD operations:
 
        //C(reate)
        if (DataManager.DataContext.Companies.FirstOrDefault(
        c => c.CompanyName == "Microsoft") == null)
        {
            DataModel.Company microsoft = new DataModel.Company(Guid.NewGuid(), "Microsoft");
            DataManager.DataContext.Companies.Add(microsoft);
            DataManager.DataContext.Persons.Add(new DataModel.Person(
                Guid.NewGuid(), 
                "John doe", 
                20, 
                DataModel.Prefix.Dr, 
                microsoft));
            DataManager.DataContext.Persons.Add(new DataModel.Person(
                Guid.NewGuid(), 
                "Klark Kent", 
                30, 
                DataModel.Prefix.Dr, 
                microsoft));
            DataManager.DataContext.SaveChanges();
        }
 
        //R(ead)
        IQueryable<DataModel.Person> microsoftWorkers = DataManager.DataContext.Persons.Where(
            person => person.Workplace.CompanyName == "Microsoft");
        Console.WriteLine("{0} persons are working in Microsoft.\n", microsoftWorkers.Count());
 
        //U(pdate)
        DataModel.Person johnDoe = DataManager.DataContext.Persons.FirstOrDefault(
            p => p.Name == "John Doe");
        if (johnDoe != null)
        {
            johnDoe.Name = "Changed Name";
            DataManager.DataContext.SaveChanges();
        }
 
        //D(elete)
        DataModel.Person klark = DataManager.DataContext.Persons.FirstOrDefault(
            p => p.Name == "Klark Kent");
        if (klark != null)
        {
            DataManager.DataContext.Persons.Remove(klark);
            DataManager.DataContext.SaveChanges();
        }
            
        //Done.
        Console.ReadKey();
    }
}

 

Where is my data?
As written in the prerequisites section above, I'm using the very comfortable SQL Server Compact Toolbox Visual Studio extension.
Once installed, it can be accessed through the Tools menu:

Connecting to your database file is then extremely simple:

In the dialog, browse to select your created SDF database file, the connection string will be automatically created:

And you can now browse through your database and run queries like any civilized respectful person would do, if they were you:

A query execution window will open



Web Deploy Hosting :: ASPHostPortal.com - How to Fix “Error: An unsupported response was received. The response header ‘MSDeploy.Response’ was ” but ‘v1' was expected

clock September 23, 2013 07:32 by author Ben

When you get this error from MSDeploy: 

“Error: An unsupported response was received. The response header ‘MSDeploy.Response’ was ” but ‘v1′ was expected.

Error: The remote server returned an error: (401) Unauthorized.”

This means that you do not have access. On our newer servers web deploy is enabled from the Management tab in your website. Older servers require web deploy to be enabled for each account, so please submit a support ticket if you need it enabled.

So you can follow this step fo fix error :

1. Web Deploy package is not installed on the IIS server in question . To install find the " Web Deploy " or " Web Deploy 2.0 " from the top level IIS.Net \ Download ( for downloading all extensions ) or directly on the Web Deploy 2.0 page . Alternately if the Platform installer addin is installed one can find it through the IIS Server Manager where one can also install it and other goodies . ( The platform installer as shown below can be found in the server list and individual website or list of icons in the management section . )



2. Even if Web Deploy package is installed , the service is not running automatically . Follow these steps to find the correct service and get it running .

a. Run services.msc from the start bar or command line .

 

b. Search for the service named Web Deployment Agent Service . Once found verify it is running and also starts up automatically after a reboot .



3. Also your account may not have permissions to publish to the web site in question . In IIS Management Studio , find the website in question and the make sure your ( or other 's ) credentials are found in the IIS Manager Permission list .





ASP.NET Hosting - IIS 7.5 Hosting - ASPHostPortal.com :: Configure Costum Error in IIS 7.5 With ASP.NET

clock September 21, 2013 09:17 by author Ben

Now, I will explain how to configure custom error pages in IIS (Internet Information Service). For this example we will be using IIS 7.5 which shipped with Windows Server 2008 R2.

First Step, Open Internet Information Services (IIS) Manager.  Select your website. Note: This could also be set at the server level and applied to all sites on the server. DoubleClick on the “.NET Error Pages” icon.


The .NET Error Pages features view will be displayed.


Click the “Edit Feature Settings” link to enable this feature. The “Edit Error Page Settings” dialog box will appear.


How to determine the error code 404 explicitly..

First, On the .NET Error Pages Actions menu click the Add link.


The “Add Custom Error Page” dialog will appear. This is where we define individual error pages per status code. For our example we will add a custom page for the HTTP 404 Error.




Now that we have turned on the feature and added a custom page for the 404 status code we can verify it is working. Please reload your website.

As mentioned above this can also be managed from the site’s web.config file. Consider the following configuration section from our site’s web.config file.



ASP.NET Hosting - ASPHostPortal :: How to Resolve "~/Telerik.Web.UI.WebResource.axd' is missing in web.config"

clock September 13, 2013 08:23 by author Mike

Problem 1:
When attempting to run an application that uses certain Telerik controls, you may run into the error below:

System.InvalidOperationException:
‘~/Telerik.Web.UI.WebResource.axd’ is missing in web.config.
RadStyleSheetManager requires a HttpHandler registration in web.config. Please,
use the control Smart Tag to add the handler automatically, or see the help for
more information: Controls > RadStyleSheetManager at
Telerik.Web.UI.RadStyleSheetManager.OnPreRender(EventArgs e) at
System.Web.UI.Control.PreRenderRecursiveInternal() at
System.Web.UI.Control.PreRenderRecursiveInternal() at
System.Web.UI.Control.PreRenderRecursiveInternal() at
System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint,
Boolean includeStagesAfterAsyncPoint)


Solution:
I’ve seen that error on new DotNetNuke installations but it certainly isn’t specific to DNN, nor is it a problem with the Telerik controls. The issue is that the Integrated Pipeline Mode and Classic Modes handle the registration slightly differently within the web.config file.
To resolve this error you can make changes to your web.config file, or, a perhaps faster and easier solution, is to change your site’s ASP.NET version to Classic Mode – both seem to work equally well.

Problem 2:
When you place RadScriptManager on aspx page and compile it gives error like, 

" '~/Telerik.Web.UI.WebResource.axd' is missing in web.config. RadScriptManager requires a HttpHandler registration in web.config. 
Please, use the control Smart Tag to add the handler automatically, or see the help for more information: Controls > RadScriptManager "


Solution:
Its Simple And fast you Just Have to register The radScriptmanager and it will modify the web config file automatically.

  • Click RadScriptManager Menu Cursor .It Will Display RadScript Manager Tasks click on Regiter Telerik.Web>UI.WebResource.axd
Telerik.Web.UI.WebResource.axd
  • Telerik.WebUI.WebResources.axd Is Now Succeessfully Register in Web Config.

    Telerik.Web.UI.WebResource.axd



ASP.NET 4.0 Hosting :: Multiselect Dropdown for Web Applications ASP.NET 4.0

clock September 4, 2013 11:18 by author Mike

In this article, I will show you how to create a multiselect in an ASP.NET 4.0 page. I will keep this article short and sweet so you can just use the code in your applications. Lets see how I implement this.

Now, place one textbox in your design view and assign the popup extender for that textbox. Important note here is you must be place your textbox control within the "Updatepanel". Afterwards, you create one panel and within this panel you put one checkboxlist. You assign this panel to the "PopupControlID" property of the Popup Extender.

Now see this code:

Finally we must do only one modification in code behind, because each time clicking the checkboxlist that selected value will added into the textbox control. So in selected index changed event you will place this code.


Finish. Hopefully this article can help you.



Windows 2012 Hosting :: Introduction Dynamic Access Control 2012

clock September 2, 2013 12:09 by author Ben

Do you know what is Dynamic Access Control??
Microsoft Dynamic Access Control (DAC) is a data governance tool in Windows Server 2012 that lets administrators control access settings. DAC uses centralized policies to let administrators review who has access to individual files. Files can be manually or automatically classified.

Windows Server 2012 Dynamic Access Control basically organize information automatically on file servers in order to meet business needs and regulatory requirements .

With the use of technology in the DAC classification , organization or company can identify or provide " tags " or labels to files on the file server . This capability to control access to files that were tagged through centralized access policies , perform audits and related reporting events related to access or attempts to access , use RMS ( Rights Management Services ) to encrypt Office documents so that the documents safe when the data out of the file server .

A number of the features found in Windows Server 2012 that are beneficial to the administrator in this regard :

  •     File owner , or the owner can directly provide information " tags " or labels to their own information , so do not need to be done by the administrator .
  •     Apply to the central access policy files ( information ) that has been in the " tag " or label given
  •     Provide " access denied remediation " when the user can not access the information .
  •     Configure the central audit trail records policies for information access ( access logs ) that can later be used for analysis and forensic needs .
  •     Protect certain sensitive information to the protection of the RMS automatically.


Label or tag used to identify the protected file can be used to classify files in logic . In Windows Server 2012 , this label can be applied in four ways :

  •     Based on location . When files are stored on a file server , the file inherits the label of its parent folder .
  •     Manually . Users and administrators can manually file labeling .
  •     Automatic . Files can be automatically labeled based on content or other characteristics .
  •     With the application , using the API for labeling file maintained by the application .

 



About ASPHostPortal.com

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

Sign in