Bye Bye Free WordPress
Posted: 2011/06/12 Filed under: Uncategorized Leave a commentI finally decided to make a move and create a wordpress blog on paid hosting. See you on the http://www.mfranc.com ;]
Git – gui , staging selected lines
Posted: 2011/06/11 Filed under: Git | Tags: git Leave a commentI m using Git for about half a year and boy it still amazes me with these little “gems” that you can find “inside”.
At the beginning I just hated the idea of a console management. I was using Svn with tortoise installed. Yeah those are symptoms of a “Windows User” which only knows how to point and click with mouse. Everything changed when I thought that it would be a great idea to learn Git . there was a huge hype , well it still here. I installed msysgit and started my journey.
Git changed everything . I just love the idea of managing a lot of things without the mouse. learning Git encouraged me to learn shortucts and keyboard commands in my “default” IDE (Visual Studio + R%). It’s a huge productivity boost and there is a cool side-efect. Work is more is fun : ).
Git Gui
I spent couple of months managing my project by console. You know
git commit , git push . I even learned some vim which is also cool and “nerdy”.
Then I discovered git gui. This simple app is almost everything you need to manage your git based repository.
To run it write “git gui” in the console.
Right now my standard scenario when pushing new commit is :
– review changes and prepare commits in git gui
– push changes to repo by the git push command in the console .Yeah I know that you can push from within git gui but a simple command in console is a lot easier to do (truth is I don’t know how to configure it ). I have two instances of msysgit running all the time.
Staging selected lines
When coding we sometimes forget to commit every “bigger” change. Big pile of changes with different functionalities emerges and we have the problem. We could commit everything in one try but that’s not a good idea. In ideal scenario commits should contain only one functionality. That way every revision is a functional app ready to clone and test. With one big commit , repository is not “flexible”.
There is a solution for it called “Stage Lines for Commit”. You just need to run git gui select changes inside git gui and right click then there is a option to commit only selected lines of code.
Git is full of little gems. It’s easy , it’s fun. It’s just great ;]
Asp.Net Mvc regular expression attribute Testing–DateTime validation problem
Posted: 2011/06/04 Filed under: Asp.Net MVC, UnitTests Leave a comment
Context
When developing simple validation logic in Asp.Net Mvc you can use the built in validators. One of them is the RegularExpression Validator. I had a simple scenario with a property of DateTime type called StartDate. Validation format (yyyy-mm-dd). It should be a simple task , but details are always messy.
I created a simple pattern and tested it with various examples in one of the Regex Editors.
public DateTime StartDate { get; set; }
To check if this solution works , two unit tests were created. First implementation of tests used the Regex class , but then I found out that you can use Attribute classes inside your code. I changed tests and used the RegularExpressionAttribute class inside test. Those tests are better because , with Regex our , we are checking if regex pattern is correct. With Attribute class used inside the test , we are testing actual scenario that is happening inside our app .
Here are the tests.
class CalendarEventRegExpTests
{
private string regex = @”^(19|20)(\d\d)[- /.](0[1-9]|1[012])[- /.](0[1-9]|[12][0-9]|3[01])$”;
[Test]
public void Should_match()
{
var dateTime = “2011-10-1”;
var attribute = new RegularExpressionAttribute(regex);
Assert.IsTrue(attribute.IsValid(dateTime));
}
SUCCESS
[Test]
public void Should_not_match()
{
var dateTime = “01-10-2001”;
var attribute = new RegularExpressionAttribute(regex);
Assert.IsFalse(attribute.IsValid(dateTime));
}
}
SUCCESS
Yey green light, They passed so it’s working ! I tested the app and … validation was always incorrect . First thought , my pattern is incorrect. But , it is working inside RegEx Editor so I it has to be correct.
Problem
It seems that when DateTime object is passed to the RegExpAttribute , something weird is happening and validation fails. I have simulated this scenario with simple test.
public void Should_match()
{
var dateTime = new DateTime(2011,11,10);
var attribute = new RegularExpressionAttribute(regex);
Assert.IsTrue(attribute.IsValid(dateTime));
}
FAIL
Maybe it’s the problem with the type of the object. This test converts DateTime object to string fail.
public void Should_match()
{
var dateTime = new DateTime(2011,10,10);
var attribute = new RegularExpressionAttribute(regex);
Assert.IsTrue(attribute.IsValid(dateTime.ToString()));
}
FAIL
Then I realized that .ToString() , method by default creates string including the hh-mm-ss. In my scenario those parameters were initialized with zeros My simple regex pattern wont match this string. Correctly formatted string passes the Test.
public void Should_match()
{
var dateTime = new DateTime(2011,10,10);
var attribute = new RegularExpressionAttribute(regex);
Assert.IsTrue(attribute.IsValid(dateTime.ToString(“yyyy-MM-dd”)));
}
SUCCESS
It’s time to look inside the RegularExpressionAttribute. Let me “Reflect” or “DotPeek” that for you.
Here is the code inside the class.
{
this.SetupRegex();
string input = Convert.ToString(value, (IFormatProvider) CultureInfo.CurrentCulture);
if (string.IsNullOrEmpty(input))
{
return true;
}
else
{
Match match = this.Regex.Match(input);
if (match.Success && match.Index == 0)
return match.Length == input.Length;
else
return false;
}
}
The Highlighted part is the problem. .IsValid() method uses default.ToString(). DateTime is parsed to the string with hh-mm-ss and that’s the root of the problem.
Solution
There is a simple solution to this problem. You just need to attach DisplayFormat.
Lessons Learned
– “green light” in test doesn’t mean that your code is working .
– create tests on “real” data
– try simulate environment and context as much as possible. To many assumptions and your test isn’t testing real scenario. In my case , I used the string inside test when my app used DateTime object.
Great presentations @TechEd Atlanta 2011
Posted: 2011/05/30 Filed under: Events | Tags: teched Leave a commentI have spent some time on the weekend watching Tech Ed on channel 9
1. Hack Proofing Your Microsoft ASP.NET Web Forms and MVC Applications
– Sql Injections
– Cross Site Scripting
– parameter tampering in MVC3
Great presentation with ton of useful information’s . I didn’t knew that you can exploit web applications in soo many ways.
– Software Development Crisis
– Great analogies to other engineering disciplines
If you don’t want to end as a Code Monkey in the near future. You have to watch this presentation.
3 . Demystifying Debugging with Microsoft Visual Studio Ultimate and IntelliTrace
– lots of good stuff about debugging features in VS
– IntelliTrace and VS Tests
Now I know that this window on the left side of the screen is called IntelliTrace and it’s a great tool ;]
<3 Git and how to – problem with ignoring by file extensions
Posted: 2011/05/28 Filed under: Git | Tags: git Leave a commentI started my adventure in Source Code Management systems with SVN. I was on my 3rd year at University and was quite impressed with it’s capabilities. Later on after hearing a lot of good things about Git and watching great presentation by Linus Torvalds, I persuaded myself to try it. This was a big move for me. I worked/learned on the MS stack so by moving to the GIT world I had to learn some Unix technology. I had problems with adoption : configuration problems , shift in thinking about repositories , branches , even something new like GitHub community. Lots of work and try and error learning but it was worth the time . Now , which is an irony , I have problems working with SVN at work Too much “git-ing” : ) . You just cant understand why something is in GIT and not in SVN. I m struggling now. Integration server is full of “build failures , caused by missing file in repository : D
I m still working with GIT at home , and I m not changing it to other SCM unless it’s really necessary eg. in work.
Recently I encountered a problem with ignoring files. I wanted to ignore some files by extension type. Well I was not working at all. I had to spent some time to find the solution. StackOverflow came to the rescue. Those simple commands fixed my problem.
1. git rm -r --cached .
2. git add .
3.git commit –m
This basically clears out the cache and “re-adds” files.
On a side note don’t be afraid with the git rm command , I have almost jumped off my chair when I saw whole thesis being deleted : )
Faking Controller User.Identity with Rhino Mocks and MvcContrib. Unit Tests in Asp.Net Mvc
Posted: 2011/05/25 Filed under: Asp.Net MVC, Mocks/Stubs, UnitTests | Tags: asp.net mvc, mvc contrib, rhino mocks 2 CommentsSome of the actions that we are writing in Asp.Net MVC contains logic which uses data from the User context eg. user authentication or user name. Controller base class contains User property which is the instance of IPrincipal with two important properties.
User.Identity.IsAuthenticated
The IPrincipal is taken from the HttpContext
{
get
{
if (this.HttpContext != null)
return this.HttpContext.User;
else
return (IPrincipal) null;
}
}
So if your action is using the User property directly (you can always wrap this property inside a class that implements mockable Interface ) there is a problem with unit testing. In a isolated enviroment like test case , Controller doesn’t have the HttpContext. It is an external dependency.
HttpContext is retrieved from the ControllerContext
{
get
{
if (this.ControllerContext != null)
return this.ControllerContext.HttpContext;
else
return (HttpContextBase) null;
}
}
In order to fake the User property First we need to create a fake ControllerContext. To create it we need HttpContext which also needs HttpRequest. User is created from IPrincipal and IIdentity , with those classes we can create a Stub inside the HttpContext.
Yep , It’s quite complicated. Fortunately MvcContrib Library helps a little by providing classes that are faking IIdentity and IPrincipal
If you want to create a fake user you just need to write
When creating FakeIdentity userName parametr is really important. If you want ,not authenticated user , pass Empty String as a parameter
Yey , it’s the end ! Check out this simple graph.
Using this information , I have implemented simple TestHelper with methods to generate Fake ControlleContext with faked User.
Code:
{
public static ControllerContext MockControllerContext(Controller controller)
{
var httpContext = MockRepository.GenerateMock<HttpContextBase>();
var httpRequest = MockRepository.GenerateMock<HttpRequestBase>();
httpContext.Stub(x => x.Request).Return(httpRequest);
return new ControllerContext(httpContext,new RouteData(),controller);
}
public static ControllerContext WithAuthenticatedUser(this ControllerContext context, string userName)
{
var user = new FakePrincipal(new FakeIdentity(userName),null);
context.HttpContext.Stub(x => x.User).Return(user);
return new ControllerContext(context.HttpContext,new RouteData(),context.Controller);
}
public static ControllerContext WithNotAuthenticatedUser(this ControllerContext context)
{
var user = new FakePrincipal(new FakeIdentity(String.Empty), null);
context.HttpContext.Stub(x => x.User).Return(user);
return new ControllerContext(context.HttpContext, new RouteData(), context.Controller);
}
}
Usage:
TestHelper.MockControllerContext(ProfileController).WithAuthenticatedUser(“test”);
Hope this sample helps.
Faking ModelState.IsValid–unit tests in Asp.Net Mvc
Posted: 2011/05/22 Filed under: Asp.Net MVC, UnitTests | Tags: asp.net mvc, NUnit Leave a commentAs a part of my thesis , I am creating web app in Asp.net MVC. I m using NHibernate , NUnit , RhinoMocks , WCF , Ninject , Glimpse and also Elmah . This is a quite big project with a lot of unit tests. I am treating it as a playground.
This is the the first post o of a series about using unit tests with MVC and WCF .
Create entity action scenario in my app is simple. First there is a get action which builds View and prepares model. Then this newly created model (filled with values from the view) is passed to action with [HttpPost] attribute. It is a good practice to if ModelState.IsValid before performing any DB operations.
I have a lot of tests testing controllers and their action. In this case on of the tests should check behaviour of the controller when the ModelState.IsValid value is false. I have tried different approaches : trying to mock controller , trying to mock its context , inspecting code with dotPeek (cool decompiler from the JetBrains) wasn’t helpfull. Then I realized that you can do something like this.
CourseController.ModelState.Add(“testError”, new ModelState());
CourseController.ModelState.AddModelError(“testError”, “test”);
Test:
public void Post_if_model_state_invalid_then_dont_add_course_and_return_error_view()
{
#region Arrange
//Faking ModelState.IsValid = false
CourseController.ModelState.Add(“testError”, new ModelState()); CourseController.ModelState.AddModelError(“testError”, “test”);
using (Mock.Record())
{
Expect.Call(CourseService.AddCourse(Course)).Repeat.Never();
}
#endregion
#region Act
ViewResult view;
using (Mock.Playback())
{
view = (ViewResult)CourseController.Create(Course);
}
#endregion
#region Assert
Assert.That(view.ViewName,Is.EqualTo(“Error”));
Assert.That(view.ViewBag.Error, Is.EqualTo(elearn.Common.ErrorMessages.Course.ModelUpdateError));
}
As you can see , I am modifying ModelState by injecting fake data that will result in IsValid property set to false.
Asp .Net Mvc [Authorize] over Wcf – Role Check
Posted: 2011/05/01 Filed under: Asp.Net MVC, WCF | Tags: asp.net mvc, wcf Leave a commentIn Asp.Net MVC you can attach various attributes to the controllers actions. One of them is Authorize which is used to managed access.
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 :
- Check if user is in list of users in the Authorize User parameter.
- you can set usernames parameter
- Check if the user is logged in.
- Check if user is atlest in one role definied in authorize parameters
- role check looks like this
{
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.
{
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
{
foreach (string s in roles)
{
if (Roles.IsUserInRole(userName,s))
{
return true;
}
}
return false;
}
FluentNHibernate–Testing
Posted: 2011/04/23 Filed under: NHibernate, UnitTests | Tags: FluentNHibernate, NHibernate Leave a commentFluentNHibernate
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,
{
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 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 :
.Database(() => SQLiteConfiguration.Standard.InMemory().ShowSql())
.Mappings(x => x.FluentMappings.AddFromAssembly(typeof(ProfileModel).Assembly))
.BuildConfiguration();
Then you can create session and use it for tests.
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
.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.
{
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
Posted: 2011/04/06 Filed under: UnitTests | Tags: NUnit, visual studio Leave a commentI am using NUnit framework to write Unit Tests. To simplify my work I have a simple snippet which generates test method.
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.
xmlns=“http://schemas.microsoft.com/VisualStudio/2010/CodeSnippet”>
<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>


