RSS Feed

Asp .Net Mvc [Authorize] over Wcf – Role Check

In Asp.Net MVC you can attach various attributes to the controllers actions. One of them is Authorize which is used to managed access.

        [Authorize]
        public ActionResult Index()
        {
            var profile = _service.GetByName(UserName);

            return RedirectToAction(“Details”, new { id = profile.ID });
        }

In this example every time user runs the Index action Authorize class performs :

  1. Check if user is in list of users in the Authorize User parameter.
    • you can set usernames parameter
      • [Authorize(Users=“Mike,Tim”)]
  2. Check if the user is logged in.
    • if (!user.Identity.IsAuthenticated)
      {
              return false;
      }
  3. Check if user is atlest in one role definied in authorize parameters
    • [Authorize(Roles=“admin”)]
    • role check looks like this
    • if (!Enumerable.Any<string>(roles, new Func<string, bool>(user.IsInRole)))
      {
              return false;
      }

 

In my scenario I have database with all the data required for the membership provider on another server. Simple methods like ValidateUser are on the wire. Default Authorize class uses the user.IsInRole which needs “local” role provider . With DB behind the service layer it won’t work at all.  I have launched ILSpy and made a little research.

It appears that Authorize Attribute is not sealed and you can extend its behaviors. Mehods inside class are marked as virtual so you can easily override them.

So here is my implementation of Authorize class over WCV. Most important part is the call service.IsUserInroles(name). Service through WCF check the roles and return boolean value.

    public class AuthorizeAttributeWCF : AuthorizeAttribute
    {
        protected override bool AuthorizeCore(HttpContextBase httpContext)
        {
            if (httpContext == null)
            {
                throw new ArgumentNullException(“httpContext”);
            }
            IPrincipal user = httpContext.User;
            if (!user.Identity.IsAuthenticated)
            {
                return false;
            }
            if (this.Users.Length > 0 && !Enumerable.Contains<string>(this.Users.Split(‘,’), user.Identity.Name, StringComparer.OrdinalIgnoreCase))
            {
                return false;
            }
            if (this.Roles.Length > 0)
            {
                string [] roles = this.Roles.Split(‘,’);
                var service = new ProfileService.ProfileServiceClient();
                return service.IsUserInRoles(user.Identity.Name,roles);
            }
            return true;
        }
    }

Method used in my service

        public bool IsUserInRoles(string userName,string[] roles)
        {
            foreach (string s in roles)
            {
                if (Roles.IsUserInRole(userName,s))
                {
                    return true;
                }
            }
            return false;
        }
Advertisements

FluentNHibernate–Testing

FluentNHibernate

 

FluentNhibernate framework provides easy way to define mappings in NHibernate. You don’t need to create complex xml files , instead you can use C# syntax and write the code in the “.cs” file. FluentNH generates cfg from it.

Just to show you how this is simple check this class mapping,

        public GroupModelMap()
        {
            Id(x => x.ID);
            Map(x => x.GroupName).Not.Nullable();

            //One
            References(x => x.GroupType).Not.LazyLoad();

            //Many
            HasMany(x=>x.Users);          
        }

Mapped class looks like this :

    public class GroupModel
    {
        public virtual int ID { get; private set; }
        public virtual string GroupName { get; set; }

        public virtual GroupTypeModel GroupType { get; set; }
        public virtual IList<ProfileModel> Users { get; set; }

    }

Every property needs to be marked as virtual and every mapped class needs ID property. It’s just simple as that. There are many options you can use. But I wont go into details in this post. If you want to try it just check the site.

In this post ,I want to show you other aspects of FluentNHibernate , that can make your life easier. FluentNH is not only about mappings anymore it provides lots of more functionalities.

 

In Memory Testing

 

When testing NHibernate layer , it is a good way to use database stored in memory. Unit tests should be isolated , so by running tests on Database Engine you break this rule.

For InMemory DB  , I  prefer the SqlLite database engine. Its quite good and FluentNH has a good “out of box” support for it. Creating InMemory DB can be a painful experience. You can encounter various problems and one of them is session management. With InMemory DB when session is closed data is deleted from memory and you don’t have access to data. In one of the projects , I have implemented my own mechanism based on the Maciej Aniserowicz samples. It worked fine, but also required a lot of testing and improving.

Fortunately for us Fluent NH provides mechanism for creating the session object leaving you problem of implementing the tests. We just need to provide the SqlLite configuration.

Something like :

                    _configuration = Fluently.Configure()
                            .Database(() => SQLiteConfiguration.Standard.InMemory().ShowSql())
                            .Mappings(x => x.FluentMappings.AddFromAssembly(typeof(ProfileModel).Assembly))
                            .BuildConfiguration();

Then you can create session and use it for tests.

var sessionSource = new SingleConnectionSessionSourceForSQLiteInMemoryTesting(configuration);

ISession session = sessionSource.CreateSession()

 

Testing Nhibernate Mappings

In unit test world with ORM layers it is good idea to test mappings. Writing your own tests can be a mundane and boring task. FluentNHibernate provides  a way to test it quite simply.

You can use the PersistenceSpecification class

                new PersistenceSpecification<ForumModel>(session, new IDEqualityComparer())
                   .CheckProperty(c => c.Name, “test”)
                   .CheckProperty(c => c.Author, “test”)
                   .CheckList<TopicModel>(c => c.Topics,
                   new List<TopicModel>()
                        {
                            new TopicModel(){ Text=“test”}
                        }
                   )
                   .VerifyTheMappings();

This class performs:

  • create ForumModel instance
  • insert this instance to DB
  • retrieve it
  • and verify if returned data is correct

Besides the session parameter this class can take Comparer class which defines the your own comparison idea .

Look at this example. In one of the projects , I am performing comparison based on the unique ID to check if Reference is correct.

    public class IDEqualityComparer : IEqualityComparer
    {
        new public bool Equals(object x, object y)
        {
            #region Comparer

            if (x == null || y == null)
            {
                return false;
            }
            if (x is IModel && y is IModel)
            {
                return ((IModel)x).ID == ((IModel)y).ID;
            }

            return x.Equals(y);
            #endregion
        }

        public int GetHashCode(object obj)
        {
            throw new NotImplementedException();
        }
    }

IModel is used here to shorten the code. It contains only ID property. Every model class implements it.

More info

http://wiki.fluentnhibernate.org/Persistence_specification_testing


NUnit Test Visual Studio Snippet

I am using NUnit framework to write Unit Tests. To simplify my work I have a simple snippet which generates test method.

[Test]
public void TestName()
{
#region Arrange
#endregion 

#region Act

Assert.Fail();

#endregion

#region Assert
#endregion
}

As you can see there are regions for different actions.

Here is a code for this snippet. If you want to use it. Just copy paste it to the xml file and name it with extensions “*.snippet”. Then in Visual Studio go to (Tools –> Code Snippet Manager) and import this file.

<CodeSnippets
xmlns=http://schemas.microsoft.com/VisualStudio/2010/CodeSnippet&#8221;>
<CodeSnippet Format=“1.0.0”>
<Header>
<Title>
NUnit Test
</Title>
</Header> 

<Snippet>
<Declarations>
<Literal>
<ID>TestName</ID>
<ToolTip>Replace with TestName.</ToolTip>
<Default>TestName</Default>
</Literal>
</Declarations>
<Code Language=“CSharp”>
<![CDATA[
[Test]
public void $TestName$()
{
#region Arrange
#endregion

#region Act

Assert.Fail();

#endregion

#region Assert
#endregion
}
]]>
</Code>
</Snippet>
</CodeSnippet>
</CodeSnippets>


FluentNHibernate , NHibernate–Notes

I m currently implementing some project using the NHibernate. I dont like the mappongs stored in xml files so I am using FluentNhiberante.

 

1. Mapping Whole Assembly.

Before discovering this feature , I created one line foreach mapping defined in the assembly. You can replace this “useless” code with the procedure to map whole assembly. FluentNH  will scan the assembly and look for classes inheriting from ClassMap<>

            return Fluently.Configure().
                Database(MsSqlConfiguration.MsSql2008.ConnectionString
                (“connstring”))
                 .Mappings(x => x.FluentMappings.AddFromAssembly(System.Reflection.Assembly.GetExecutingAssembly()))
                 .ExposeConfiguration(func)
                  .BuildSessionFactory();
 
2. not null fields

If you want to create some fields in the DB as “not null”. use the Not.Nullable() sequence.

Map(x => x.IDCourse).Not.Nullable();
 
3. Reseting Schema for Testing

I don’t know if this is a good approach but when , I am working with NH i create an instance of test database with sample data. Everytime , I am running tests i m reseting schema , filling DB with sample data and then database is erased from memory (SQLite) or the server.

Session Factory Class

In my session factory Class i have methods to reset and update Schema

 public static class SessionFactory
{
    public static ISession OpenSession()
    {
        return GetSessionFactory().OpenSession();
    }
     private static ISessionFactory GetSessionFactory()
     {
        if (_sessionFactory == null)
        {
            _sessionFactory = CreateSessionFactory(UpdateSchema);
         }
         return _sessionFactory;
     }
        private static ISessionFactory _sessionFactory;

        public static void ResetSchema()
        {
            CreateSessionFactory(ResetSchema);
        }

        private static ISessionFactory CreateSessionFactory(Action<Configuration> func)
        {

          return Fluently.Configure().
               Database(MsSqlConfiguration.MsSql2008.ConnectionString
               (“connstring”))
               .Mappings(x => x.FluentMappings.AddFromAssembly(System.Reflection.Assembly.GetExecutingAssembly()))
               .ExposeConfiguration(func)
               .BuildSessionFactory();
        }
        private static void UpdateSchema(Configuration config)
        {
            new SchemaUpdate(config).Execute(true, true);
        }

        public static void ResetSchema(Configuration config)
        {
            new SchemaExport(config).Create(true, true);
        }

 

4. Generic Repository

I am the fan of the repositories used to perform all the CRUD and complex query operations. In the code I have a base repository class and complex repositories deriving from the base class.

public  class Repository<T> : IRepository<T>
        where T : class
    {
        public T GetById(int id)
        {
            T klient;

            klient = GetByFilter(“Id”,id).FirstOrDefault();

            return klient;
        }

        public IList<T> GetByFilter(string parameterName, object value)
        {
            IList<T> returnedList = null;
            using (var session = SessionFactory.OpenSession())
            {
                returnedList = session.CreateCriteria(typeof(T)).Add(Expression.Eq(parameterName, value)).List<T>();
                session.Flush();
            }
            return returnedList;
        }

        protected IList<T> GetByQuery(string query)
        {
            IList<T> returnedList = null;
            using (var session = SessionFactory.OpenSession())
            {
                returnedList = session.CreateQuery(query).List<T>();
                session.Flush();
            }
            return returnedList;
        }

      …..

    }

Simple Repository used for most CRUD operations.

For more complex queries , I just create a new class deriving from the base one.

    public class KlientRepository : Repository<Klient>
    {

        public Klient GetByImieNazwisko(string imie, string nazwisko)
        {
            return GetByQuery(String.Format(“from Klient k where k.Imie = ‘{0}’ and k.Nazwisko = ‘{1}'”,imie,nazwisko)).FirstOrDefault();
        }

        public IList<Klient> GetByRodzaj(string rodzaj)
        {
            return GetByQuery(String.Format(“from Klient k where k.Rodzaj.Rodzaj = ‘{0}’ “, rodzaj)).ToList();

        }
    }


Yey 70-536 passed

I passed my first ms exam Microsoft .NET Framework – Application Development Foundation. Some questions were simple and some quite difficult , with a lot of details. I spent quite some time to prepare. Some concepts like Code Access Security or App Domains , well this was something  new to me.

This is just the beginning . Next step 70-562.


Generics and Object Casting– Boxing , Unboxing

There are multiple scenarios in which we need to create generic classes for different objects. In this case we have two options. Either we can create generic class and specify the type/types of the object in the code  or ,  we can create a class operating on the System.Object types which are the base for every object / class in the framework.

If we have two options available then  the question is which one is better ?

To test both approaches , I created a simple logic which performs assignment and some kind of operation which returns value. This logic is encapsulated in two classes. ClassGeneric is built with generics built in .Net .You can see that type is represented by “U” letter. ClassObject is based on casting to System.Object.

 

Code:

    class ClassGeneric<U>
    {
        U test;

        public ClassGeneric(U value)
        {
            test = value;
        }

        public void Operation()
        {
            U t = test;
        }
    }

    class ClassObject
    {
        Object test;

        public ClassObject(Object value)
        {
            test = value;
        }

        public void Operation()
        {
            int t = (int)test;
        }
    }

 

Test :

Now lets perform a simple test by creating instances of both classes and performing operation. Stopwatch will be used to check performance.

 

        static Stopwatch sw = new Stopwatch();

        static void Main(string[] args)
        {
            sw.Start();
            for (int i = 0; i < 10000000; i++)
            {
                new Labs.ClassGeneric<int>(1).Operation();
            }
            sw.Stop();

            Console.WriteLine(sw.ElapsedMilliseconds);

            sw.Reset();
            sw.Start();
            for (int i = 0; i < 10000000; i++)
            {
                new Labs.ClassObject((object)1).Operation();
            }
            sw.Stop();

            Console.WriteLine(sw.ElapsedMilliseconds);

            Console.ReadLine();
        }

 

Result :

Generics 471k ticks  -  Objects  710k ticks

Generics 212 ms    Objects 343 ms

Why there is a difference ?

Generics are defined on the runtime.  .Net Framework based on the specified type in the code for example  (Queue<int>) creates a class with the type and stores reference to it. This operation is performed once on the start by the JIT-er (Just in time compiler). This operation is performed once so there is a minimal performance loss.

In case of System.Object class when casting from and to int we are performing Boxing and Unboxing operation. 

Boxing is performed every time we are casting Value Type to the reference Type. Boxing operation wraps our Value Type in a class deriving from the System.Object. This operation requires some cpu work. Same thing applies for the Unboxing operation which is performed when casting from Reference Type to the Value Type.

In this example I am casting int to Object type 1000000 times. This is the cause of the difference in time / performance. Generic classes does not require additional operations.

Boxing , Unboxing and generic interfaces

Understaing when your code perfmors boxing and unboxing is  really important. Check this example. In .Net we can implement various interfaces which are used in the Framework. Some of them are generic. We can define which type will be used.

Here I am implementing IComparable interface , which is usefull when you want to perform Sort operation on the Collection containing your custom Class.

First Class uses the Generic Interface.

    class ClassSort : IComparable<ClassSort>
    {
        public int A {get;set;}

       
        #region IComparable<int> Members

        public int CompareTo(ClassSort other)
        {
          throw new NotImplementedException();
        }

        #endregion
    }

Second class uses default Interface.

    class ClassSortOne : IComparable
    {
        public int A {get;set;}

        #region IComparable Members

        public int CompareTo(object obj)
        {
            throw new NotImplementedException();
        }

        #endregion
    }

As you can see IComparable without generic type forces boxing when comparing objects beacuase we have to cast the objects. CompareTo() method in example with default interface uses object as a parameter while generic interface implements method with specified class as a parameter. Interface with specified generic type doesn’t need boxing and it is faster.

 

Conclusion:

Use generic classes as often as you can. Especially when making a lot of operations with them. Simple casting which causes boxing and unboxing process consumes a lot of processor time.


One night in Microsoft

.Net group from Wroclaw University of Technology was invited by Microsoft to the event in their HQ in Warsaw . It was a first gathering of .Net groups from our country. Almost 200+ students showed up. Microsoft had problems with overcrowded hall but it was ok. As name suggests it was a all night event.

It was all about fun :

  • Couple of great presentations about Career in IT , WP7 Development and new Features in IE 9.
  • Lot of contest. Chees games , Guitar Hero Contest , Speaker Idol , Karaoke contest. Of course everything with nice prizes.

MS invests lot of resources into academic communities. This is a smart move. If a young developer or IT pro starts career on MS Stack , there is a big probability that he will stay here.In a long run this means more business and money for Microsoft.

 

image

 

Great event we had a lot of fun especially on “Kinect” and Xbox. We also tried MS Surface.I really liked the friendly  atmosphere in the MS. It’s a pity that I wont be able to attend next year edition.