Category Archives: C#

Configure ASP.NET role provider

  1. Run “aspnet_regsql.exe” from c:windowsmicrosoft.netframeworkv2.0.50727
  2. Add the Network Service account to your logins for the SQL Server be sure to set the User Mapping for this account to aspnetdb (the default database)
  3. Select in the databse aspnetdb the role “aspnet_membership_Fullaccess; right click and add the Network Service account to this role
  4. Add the following entry to your connectionstrings settings in the web.config:
        <add name="MySqlRoleManagerConnection" connectionString="Data Source=.;Initial Catalog=aspnetdb;Integrated Security=SSPI;" />
        

    Alternatively you could adjust the connectionstring section as shown below:

        <remove name="LocalSqlServer" /><add name="LocalSqlServer" connectionString="Data Source=.;Integrated Security=True;Initial Catalog=aspnetdb" />
        

    This removes the LocalSqlServer (which points to a SQLExpress instance) from the connectionstrings provided by the machine.config.
    There is no need to define the membership provider (step 5) this way.

  5. Add the membership provider settings to your system.web settings (important: connectionStringName points to the name specified in step 4):
    <membership defaultProvider="CustomizedProvider"> <providers>       
        <add name="CustomizedProvider"       
            type="System.Web.Security.SqlMembershipProvider"       
            connectionStringName="MySqlRoleManagerConnection"       
            applicationName="aex_project"       
            minRequiredPasswordLength="5"       
            minRequiredNonalphanumericCharacters="0" /> </providers>       
    </membership>    
  6. In Visual Studio go to the Project menu and choose ASP.NET Configuration. In the configuration tool change the “Authentication type” to “From the internet” (this adjusts your authentication mode in the web.config from “Windows” to “Forms”)

See also http://weblogs.asp.net/scottgu/archive/2005/08/25/423703.aspx

Share

Add “After build” event in project file Visual Studio

After build events can be added to the property page of a visual studio project. You can also add your own “targets” file to the afterbuild (or beforebuild) in the project file itself. Use the following method:

  1. Add a targets file to your project with the following contents (for example)
    <?xml version="1.0" encoding="utf-8" ?>
    <Project DefaultTargets="WSPBuild"
       xmlns=http://schemas.microsoft.com/developer/msbuild/2003>
       <PropertyGroup>
          <WSPBuilderPath>"....ToolsWSPBuilder.exe"</WSPBuilderPath>
       </PropertyGroup>
       <Target Name="WSPBuild">
          <Exec Command="cd $(ProjectDir)" Outputs="null" />
          <Message Text="Executing WSP Builder in directory $(ProjectDir)"/>
          <Exec Command="$(WSPBuilderPath) "/>
       </Target>
    </Project>
    
  2. Unload the project file
  3. Right click the project file and choose Edit…..
  4. Add an import tag below the last import tag in the projectfile:
    <Import Project="wspbuilder.Targets" />
    
  5. Uncomment the AfterBuild tag and add the following statements; remember to specify the adjust CallTarget!
    <Target Name="AfterBuild">    
         <CallTarget Targets="BuildSharePointPackage" />
    </Target> 
    
Share

HTML Injection

In de Page_load of a ASP.NET page called inject.aspx:

Response.Write("Hello "  + Request.QueryString["name"]); 

Direct your browser to “…./…../inject.aspx?name=alert(“script injected”);”

To avoid HTML injection adjust the code below to:

Response.Write("Hello "  + Server.HtmlEncode(Request.QueryString["name"]));
Share

Sign a MSI

Start a Visual Studio command prompt and create a test certificate with the command:

makecert -r -ss My -n “CN=Berend his Certificate” mycert.cer
-r create a self signed certificate.
This is a certificate without a certification path:

A regular certificate points to a Root agent:

-ss The store to use
-n The common name

Sign your MSI with this certificate:

signtool sign /n “Berend his Certificate” .msi

Result from signtool is something like:

Done Adding Additional Store
Successfully signed: .msi

You can display information about this certificate by following the steps in this article.

You can even check the public key (in C# code) by following the steps in this article.

Type certmgr.msc in a command prompt (or run command) and you will be directed to the Certification Manager snap-in. navigate to “Personal –> Certificates”; you can see your certificate created with MakeCert (command above) here:

Share

AssemblyInfoTask will fail with duplicate entries in AssemblyInfo.cs

AssemblyVersionIncrementer will fail when entries in the AssemblyInfo.cs are not unique. For example:

#if debug    
 AssemblyInfoDescription("Debug mode")
#else
  AssemblyInfoDescription("Release mode") 
#endif 

The version incrementer will read the AssemblyInfo.cs and tries to store the entries in an internal Hashtable. This fails because of the multiple “AssembyInfoDescription” (line 2 and 4) entries (the preprocessor directives are ignored).

Exception text in build log:

Task “AssemblyInfo”
C:Program FilesMSBuildRdwDefaultBuildReleaseAssemblyInfoTaskMicrosoft.VersionNumber.Targets.Test(92,5):
error MSB4018: The “AssemblyInfo” task failed unexpectedly.
error MSB4018: System.ArgumentException: An item with the same key has already been added.
error MSB4018: at System.ThrowHelper.ThrowArgumentException(ExceptionResource resource)
error MSB4018: at System.Collections.Generic.Dictionary`2.Insert(TKey key, TValue value, Boolean add)
error MSB4018: at Microsoft.Build.Extras.AssemblyInfoWrapper..ctor(String filename)
error MSB4018: at Microsoft.Build.Extras.AssemblyInfo.Execute()
error MSB4018: at Microsoft.Build.BuildEngine.TaskEngine.ExecuteInstantiatedTask(EngineProxy engineProxy, ItemBucket bucket, TaskExecutionMode howToExecuteTask, ITask task, Boolean& taskResult)

Share

LINQ example

using System;    
using System.Collections.Generic;    
using System.Linq;    
using System.Text;    
  
namespace LINQSamples    
{    
    public class Person    
    {   
        public string Name { get; set; }   
        public int Age { get; set; }   
     
        public override string ToString()   
        {   
            return this.Name + " " + this.Age;   
        }   
    }   
     
    class Program   
    {   
        static void Main(string[] args)   
        {   
            List persons = new List();   
     
            persons.Add(new Person() { Name = "Berend", Age = 38 });   
            persons.Add(new Person() { Name = "Nynke", Age = 6 });  
            persons.Add(new Person() { Name = "Marije", Age = 5 });   
            persons.Add(new Person() { Name = "Bennie", Age = 2 });   
            persons.Add(new Person() { Name = "Marian", Age = 38 });   
            Console.WriteLine("All persons:");   
            foreach (var p in persons)   
            {   
                Console.WriteLine(p);   
            }   
            Console.WriteLine();   
    
            Console.WriteLine("All persons order by name descending:");   
            var query = from person in persons orderby person.Name descending select person;   
            foreach (var p in query)   
            {   
                Console.WriteLine(p.Name);   
            }   
            Console.WriteLine();   
    
            Console.WriteLine("# of persons that are 6 years old:");   
            Console.WriteLine(persons.Count(person => person.Age == 6).ToString());   
    
            Console.ReadKey();   
        }   
    }   
}
Share