Gunnar Peipman's ASP.NET blog

ASP.NET, C#, SharePoint, SQL Server and general software development topics.

Sponsors

News

 
 
 
DZone MVB

Links

Social

July 2011 - Posts

Using Moq to mock ASP.NET MVC HttpContextBase

Here’s my little example about how to use Moq to mock HttpContextBase and it’s members to make controller tests pass. You can use this code when you are not allowed to use open-source or use-on-your-own-risk pieces of software that provide you this kind on initialization using built-in features. Also it is good exercise that introduces you how to solve mocking problems.

Here’s the simple example to get started.


var controller = new MyController();

 

var server = new Mock<HttpServerUtilityBase>(MockBehavior.Loose);

var response = new Mock<HttpResponseBase>(MockBehavior.Strict);

 

var request = new Mock<HttpRequestBase>(MockBehavior.Strict);            

request.Setup(r => r.UserHostAddress).Returns("127.0.0.1");

 

var session = new Mock<HttpSessionStateBase>();

session.Setup(s => s.SessionID).Returns(Guid.NewGuid().ToString());

 

var context = new Mock<HttpContextBase>();

context.SetupGet(c => c.Request).Returns(request.Object);

context.SetupGet(c => c.Response).Returns(response.Object);

context.SetupGet(c => c.Server).Returns(server.Object);

context.SetupGet(c => c.Session).Returns(session.Object);

 

controller.ControllerContext = new ControllerContext(context.Object,
                                  
new RouteData(), controller);


Same way you can also mock other members of HttpContextBase.

Posted: Jul 16 2011, 12:52 PM by DigiMortal | with 5 comment(s)
Filed under: , ,
Importing issues from Jira to database using C#

I am evaluating hosted Jira Studio and it likes me more and more when I’m using it. As hosted service is not in our premises and contains important information about our work I was asked to find out if there’s a way how to read data from Jira Studio and save it to our local data store. In this posting I will show you a simple way how to read issues from Jira Studio and save them to database.

Warning! The code shown here gives you idea how to communicate with Jira. If you want to use it in real scenarios then you have to modify it so there are less data asked from web service. Use this code as working base for your own integration layer with Jira but don’t forget to optimize it.

Adding service reference

I tried to add modern service reference to Jira web service in Visual Studio 2010 but it generated incorrect method calls that were impossible to use. The key is to add old-style reference to Jira web service.

To add reference to Jira web service follow these steps.

  1. Right click on your project and select Add service reference…
  2. Leave fields empty in this dialog and click button Advanced
  3. Leave values like they are and click button Add Web Reference…
  4. Insert URL of Jira and web reference name (example is shown on screenshot below)
  5. Click on green icon to load WSDL
  6. Click on Add Reference… button

Adding reference to Jira web service

If everything went fine then new web reference is added to your project and you can start communicating with Jira.

Creating database and data model

Now let’s create simple table for issues and add it to our application as ADO.NET entity data model. In this posting we have only one table and one class. Of course, you can read more data from Jira and also keep track of changes.

Table for Jira issuesClass for Jira issues

Now our data stuff is ready and it’s time to create connection with Jira.

Connecting to Jira

We can connect to Jira through web service client. Before calling any other methods we must log in and hold session token. This token is used by almost all web service methods to authenticate you. Simple code skeleton looks like this:


var client = new JiraService.JiraSoapServiceService();

var token = client.login("UserName", "Password");

 

// Read data from service or add new issues

 

client.Dispose();


If this code works for you then you are ready to communicate with Jira.

Importing issues

Importing issues means that we are reading issues from service, map these issues to our local issues and insert them to database. Copying values from web service issue to our model issue is not very good idea. We can use AutoMapper to ease our work. Just add NuGet package reference to project before adding the following code.


var client = new JiraService.JiraSoapServiceService();

var token = client.login("UserName", "Password");

 

var model = new JiraEntities();

 

var issues = client.getIssuesFromJqlSearch(token, "", 2);

 

Mapper.CreateMap<string, int>().ConvertUsing<IntTypeConverter>();

Mapper.CreateMap<JiraService.RemoteIssue, Issue>()

    .ForMember(p => p.ProjectKey, 
               d => d.MapFrom(dd => dd.key.Split(
'-')[0])
    );

 

foreach (var issue in issues)

{

    var modelIssue = new Issue();

    Mapper.Map(issue, modelIssue);

 

    model.Issues.AddObject(modelIssue);

    model.SaveChanges();

}

 

model.Dispose();

client.Dispose();


AutoMapper doesn’t make automatic conversions when one type needs to be parsed from another (like string => int). That’s why we are using IntTypeConverter class I found from stackoverflow thread AutoMapper: How to parse an Int from a String and possible to creating rules based on data type? You can find more conversion classes from this thread. Here is IntTypeConverter.


class IntTypeConverter : TypeConverter<string, int>

{

    protected override int ConvertCore(string source)

    {

        if (source == null)           

            throw new MappingException("Cannot convert null to int");

        return Int32.Parse(source);

    }

}


Running the code take some time, at least on my machine. But it imports issues to my database table.

Conclusion

Jira Studio is serious offer for software development companies. Besides professional level collaboration environment there are also web services available that let you integrate Jira Studio with other systems your company may use (time and resource planning etc). To get data from Jira we added old-style web service reference to our project and before communicating with web service we authenticated ourselves to get authentication token to use with calls to web service methods.

More Posts