Friday, April 19, 2013

Run Visual Studio 2012 as administrator every time


As a developer I spend my life inside Visual Studio. Since I installed Windows 8, I was having trouble opening web projects. Turns out that I need to run Visual Studio as an administrator.

Rather than right clicking the shortcut every time and another click to run as administrator, I found a permanent solution. For the lazy me, it saves two extra clicks.

Open properties of the shortcut to Visual Studio 2012, go to Shortcut tab.


Click on Advanced and then check Run as administrator checkbox.


Yipppie !!!


Thursday, March 28, 2013

Adding custom fields to a VS2012 MVC4 SimpleMembership system

Adding custom fields to a VS2012 MVC4 SimpleMembership system
Add custom columns/fields to your MVC4 SimpleMembership "UserProfile" table
MVC 4 in Visual Studio 2012 introduces the new SimpleMembership Provider as its default web-based authentication system. While this system is much simpler than the earlier ASPNETDB system that it replaces, there definitely are a few new and neat tricks to be learnt.

One of them is: How do I add custom fields to my MVC 4 registration system?

It can be done in just 4 simple steps:

1. Start up VS 2012, and create a new MVC 4 web project. Set up your SimpleMembership registration system - for some help, please see post on setting up a SimpleMembership Provider in a VS2012 MVC4 project.

2. Next, run the project and navigate to the login page, so that the tables get created. It is not necessary to create a user at this point.

3. Then, in your database, alter the table UserProfile, and add a column: FullName (nvarchar(50)).

4. Next, add/reference the new FullName field in the following programs in your project:
In class UserProfile, in AccountModels.cs (to ensure the class matches the table columns):

    [Table("UserProfile")]
    public class UserProfile
    {
        [Key]
        [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
        public int UserId { get; set; }
        public string UserName { get; set; }
        // Customization: Field(s) added
        public string FullName { get; set; }
    }

In class RegisterModel, in AccountModels.cs (to enable handling on the registration form):

    public class RegisterModel
    {
        // Existing code
        // ...

        // Customization: Field(s) added
        [Required]
        [Display(Name = "Your full name")]
        [DataType(DataType.Text)]
        public string FullName { get; set; }
    }

In the Register.cshtml view (so it'll appear on the user registration form), add a new li element with the following content:
    @Html.LabelFor(m => m.FullName)
    @Html.TextBoxFor(m => m.FullName)

In the [HttpPost] Register ActionResult, in AccountController.cs, modify the call to the CreateUserAndAccount method (to write the new column to your database):
    // Customization: Field(s) added when creating a new account
    WebSecurity.CreateUserAndAccount(
        model.UserName,
        model.Password,
        new { FullName = model.FullName }
        );

Now run your program and register a new user, supplying a value for the FullName field... success! The new row created in your database table contains the value supplied for the new column!

Note: This post covers how to create a custom column. A near-future post will explain how to access the value of that column from within your VS 2012 MVC 4 projects. Please re-visit my blog occasionally :)

Happy coding!

Tuesday, March 26, 2013

Solution to Sys.WebForms.PageRequestManagerParserErrorException

If all of the above doesn't Work I have a full proof Working solution :)
Add this Attribute to your script Manager EnablePartialRendering="true"

  Like below:  
  <ajaxToolkit:ToolkitScriptManager ID="_scriptManager" runat="server" ScriptMode="Release" CompositeScript-ScriptMode="Release" AllowCustomErrorsRedirect="False"  
     EnablePartialRendering="true" >  
   </ajaxToolkit:ToolkitScriptManager>  
 And in code behind write this code   
  Protected Sub _scriptManager_HandleErrors(ByVal sender As Object, ByVal e As AsyncPostBackErrorEventArgs) Handles _scriptManager.AsyncPostBackError  
     If e IsNot Nothing AndAlso e.Exception IsNot Nothing Then  
       Logger.Current.LogError(e.Exception.Message, e.Exception)  
       'Changed to catch the Error in Master Page Ajax Error Control Sys.webforms  
       _scriptManager.AsyncPostBackErrorMessage = e.Exception.Message  
     End If  
   End Sub  

Monday, March 11, 2013

Deploying your site with SQL CE 4.0 to shared webhosting

If you have a VPS or dedicated server, you got full access to it and normally shouldn’t run into any problems. But when you’re using shared webhosting, your actions are very limited. This post describes the errors you’ll most likely run into the first time you try this, and how to solve them.
You can either deploy from within Visual Studio or FTP the files to your host. If you hit the URL to your website, you’ll most likely get following configuration error with the according web.config fragment below:
Parser Error Message: Could not load file or assembly 'System.Data.SqlServerCe, Version=4.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91' or one of its dependencies. The system cannot find the file specified.
You get this error because most providers don’t have SQL CE 4.0 assemblies installed (yet?). This means you’ll have to 'bin deploy' the assemblies together with your site. Visual Studio 2010 provides a "Add Deployable Dependencies..." context menu item, which let you choose to add the required assemblies for Razor or SQL Server Compact to the Bin folder.


With some 'luck' you hit the next error once you solved the problem above and refreshed the page:
Parser Error Message: Access to the database file is not allowed. [ 1884,File name = somepath\App_Data\YourDatabase.sdf,SeCreateFile ]
For this error you have to give read + write access to the App_Data folder, usually done in the File Manager of your hosting control panel. If you got this error on your private server, check if the service running the Application Pool (e.g. Network Service) has these rights on the folder. You will also have to add following line of code (e.g. in the global.asax file):
AppDomain.CurrentDomain.SetData("SQLServerCompactEditionUnderWebHosting", true);
This is because, by default, SQL CE blocks access when the connection is opened under the ASP.NET networking process. Once I ran through these steps, I got everything up and running without any hiccups.

Source: http://www.bartlannoeye.be/blog/deploying-your-site-with-sql-ce-4.0-to-shared-webhosting-part-2

Saturday, March 2, 2013

Upgrading- Updating- Migrating ASP.Net 2.0 to ASP.Net 4.0


Today I upgraded our ASP.Net 2.0 project from Visual Studio 2008 to Visual Studio 2010 targeting .Net 4.0.
I ran into some issues and just wanted to list them here so others might be forewarned.
  1. Our solution has 5 web applications and many other class library projects. When the upgrade "wizard" was running it asked me with a prompt dialog if I wanted the web application project to target .Net 4.0 instead of .Net 2.0. There is also a check box on that dialog "Do this for all other web projects" which I checked.
However, after the upgrade was completed I found that none of the web application projects other than the initial one it asked me about had been set to .Net 4.0. I had to make these changes manually.
Also, none of the other class libraries were set to .Net 4.0 either. My preference would be that it asks once for the whole solution. I can't imagine that many people would want some projects targeting 2.0 and some targeting 4.0 in the same solution.
  1. When setting the targeting for C# project the option is on the application page of the properties designer. However, in VB projects to get to the targeting selection you have to change to the compile page then click on the "Advanced Options..." dialog to get to the targeting selection.
  2. the membership, profile, role providers have been moved from the System.Web assembly to the System.Web.ApplicationServices. When you modify the target version on your Web application projects to 4.0 this reference is added for you. However, if you have class libraries that use those provider classes you'll have to add this reference to the project yourself.
  3. While we are moving to Entity Framework our current primary data access method is currently typed Datasets and TableAdapters. (Yes I know, it was not my design). Be aware that some of the dataset classes have been moved into System.Data.DataSetExtensions. This reference will be added to the classes where you define your typed datasets when you change the targeting to version 4.0. However it will not be added to projects where you consume your datasets and tableadapters. You must add this reference manually.
  4. It appears that a change was made to the MSDataSetGenerator custom tool. One of our datasets had a "Name" property that was misspelled and didn't match the name of the .XSD file. In .Net 2.0 the dataset's name was used. It appears that in .Net 4 the dataset name property is used. Fixing the typo in the dataset name property resolved all the errors where the dataset was not found.
Well that's about it. All in all upgrading to VS 2010 and .Net framework 4 is not too painful. Of course I am only to the point where it compiles without error. I expect I will run into some issues when we start testing.

The Complete List of Migration Issues Upgrading from 3.5 to .NET 4.0


Today I upgraded our ASP.Net 3.5 project from Visual Studio 2008 to Visual Studio 2010 targeting .Net 4.0.
I ran into some issues and just wanted to list them here so others might be forewarned.
Microsoft has published a complete list of issues migrating from .NET Framework 3.5 SP1 to .NET 4.0. The list contains changes in 6 domains: Core, ASP.NET, ADO.NET, WCF, WPF, and XML.
.NET applications compiled for .NET 3.5 run without any problem if .NET Framework 4.0 is installed on the same machine because the two frameworks are installed in parallel and do not interfere with each other. But there are problems if an application is recompiled for .NET 4.0 because Microsoft’s latest runtime introduces some breaking changes but also some enhancements.
The changes appear in the following 6 domains:
The list of changes is relatively long, so we won’t cover them here. Some of them are:
Core
Application configuration file name change“If your application configuration file is named application-name.config, rename it to application-name.exe.config. For example, renameMyApp.config toMyApp.exe.config.”
Code Access Policy has been turned off.See Code Access Security Policy Compatibility and Migration.
ASP.NET
Apps running trusted code in the global cache might fail due to CAS policy change.See Code Access Security in ASP.NET 4 Applications.
ASP.NET 2.0 apps installed on IIS 6.0 may generate errors after ASP.NET 4.0 is installed.Either disable ASP.NET 4.0 or move ASP.NET 2 apps to an IIS instance that does not have ASP.NET 4 installed.
The Page Parser in ASP.NET 4.0 is stricter.Errors generated by invalid markup should be fixed.
Data
Streams“WCF Data Services no longer closes the underlying stream for read and write operations.”
Events“A System.Data.Linq.EntitySet(Of TEntity) collection now raises the ListChanged event for add and remove operations if the EntitySet(Of TEntity) is unloaded, in addition to raising the event when the collection is loaded.”
Queries“Skip(0) is no longer ignored in LINQ to SQL queries. As a result, queries that have this method might behave differently. For example, in some cases, an OrderBy clause is required with Skip(0) and the query will now throw a NotSupportedException exception if the OrderBy clause was not included.”
WCF
Configuration filesWCF support merging across config files.
Service hosting“You can no longer specify the configuration element at the service level by adding the attribute allowDefinition="MachineToApplication" to the element definition.Specifying the element at the service level is technically incorrect and causes inconsistent behavior.”
WPF
Exception handling“To enable errors to be detected earlier, WPF throws a TargetInvocationException and sets the InnerException property to critical exceptions, such as NullReferenceException,OutOfMemoryExceptionStackOverflowException, and SecurityException, instead of catching the original exception.”
Windows style“An InvalidOperationException is thrown if you try to set WindowStyle to a value other thanNone when AllowsTransparency is true andWindowState is Minimized.”
Dialog boxes“To improve reliability, the CommonDialog.ShowDialogmethod is called on the same thread that created theMicrosoft.Win32.FileDialog control.”
XML
Namespace resolvers“The XmlReader.ReadContentAs method no longer ignores theIXmlNamespaceResolver resolver passed to it.”
Whitespace“To prevent data loss when you are creating a reader, the XmlReader.Create method no longer discards significant white space.”

Tuesday, February 19, 2013

Specify an Identity for an Application Pool (IIS 7)

The identity of an application pool is the name of the service account under which the application pool's worker process runs. By default, application pools operate under the Network Service user account, which has low-level user rights. You can configure application pools to run under one of the built-in user accounts in the Windows Server® 2008 operating system. For example, you can specify the Local System user account, which has higher-level user rights than either the Network Service or Local Service built-in user accounts. However, remember that running an application pool under an account that has high-level user rights is a serious security risk.




You can also configure a custom account to serve as an application pool's identity. Any custom account you choose should have only the minimum rights that your application requires. A custom account is useful in the following situations:

•When you want to improve security and make it easier to trace security events to the corresponding application.
•When you are hosting Web sites for multiple customers on a single Web server. If you use the same process account for multiple customers, source code from one customer's application may be able to access source code from another customer's application. In this case, you should also configure a custom account for the anonymous user account.

•When an application requires rights or permissions in addition to the default permissions for an application pool. In this case, you can create an application pool and assign a custom identity to the new application pool.


User Interface


To use the UI

1.Open IIS Manager. For information about opening IIS Manager, see Open IIS Manager (IIS 7).

2.In the Connections pane, expand the server node and click Application Pools.

3.On the Application Pools page, select the application pool for which you want to specify an identity, and then click Advanced Settings in the Actions pane.

4.For the Identity property, click the ... button to open the Application Pool Identity dialog box.

5.If you want to use a built-in account, select the Built-in account option and select an account from the list.

6.If you want to use a custom identity, select the Custom account option and click Set to open the Set Credentials dialog box. Then type the custom account name in the User name text box, type a password in the Password text box, retype the password in the Confirm password text box, and then click OK.

7.Click OK to dismiss the Application Pool Identity dialog box.



Command Line

To specify the account identity for an application pool to use, use the following syntax:

appcmd set config /section:applicationPools /[name='string'].processModel.identityType:SpecificUser
NetworkService
LocalService
LocalSystem

The variable string is the name of the application pool that you want to configure. For example, to change the identity type from Network Service to Local Service for an application pool named Marketing, type the following at the command prompt, and then press ENTER:

appcmd set config /section:applicationPools /[name='Marketing'].processModel.identityType:LocalService

To configure an application pool to use a custom identity, use the following syntax:

appcmd set config /section:applicationPools /[name='string'].processModel.identityType:SpecificUser
NetworkService
LocalService
LocalSystem /[name='string'].processModel.userName:string /[name='string'].processModel.password:string

The variable name string is the name of the application pool that you want to configure, userName string is the user name of the account that you want the application pool to use, and password string is the password for the account. For example, to configure an application pool named Marketing to use a custom identity with a user name of Marketer and a password of M@dr1d$P, type the following at the command prompt, and then press ENTER:

appcmd set config /section:applicationPools /[name='Marketing'].processModel.identityType:SpecificUser /[name='Marketing'].processModel.userName:Marketer /[name='Marketing'].processModel.password: M@dr1d$P

For more information about Appcmd.exe, see Appcmd.exe (IIS 7).