Gunnar Peipman's ASP.NET blog

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

Sponsors

News

 
 
 
DZone MVB

Links

Social

November 2011 - Posts

Windows Azure Error: Failed to start Storage Emulator: the SQL Server instance ‘localhost\SQLExpress’ could not be found

When running some of your Windows Azure applications when storage emulator is not configured you may get the following error: "Windows Azure Tools: Failed to initialize Windows Azure storage emulator. Unable to start Development Storage. Failed to start Storage Emulator: the SQL Server instance ‘localhost\SQLExpress’ could not be found.   Please configure the SQL Server instance for Storage Emulator using the ‘DSInit’ utility in the Windows Azure SDK.". Here’s how to solve this problem.

You need to run DSInit utility to create database. For Windows Azure SDK 1.6 the location for DSInit utility is:

C:\Program Files\Windows Azure Emulator\emulator\devstore

By default DSInit expects that your database server is (local)\SQLEXPRESS but you can change it easily. If you have MSSQL instance called SQLEXPRESS then it is enough to just run DSInit. If you need some other instance then run the following command:

DSInit /sqlinstance:<instance name>

For default instance use “.” as instance name:

DSInit /sqlinstance:.

You can find more information about sqlinstance and other switches from DSInit documentation. If database was correctly created you should see dialog like this:

DSInit: Strorage databases are done

When storage database is ready you can run your application.

Making CopySourceAsHtml add-on work with VS2010

As there are still bloggers who use CopySourceAsHtml add-on for Visual Studio to get syntax highlighted code to their blog posts and there is no guidance in CSAH site how to make it work with Visual Studio 2010 I will give my guidance here. Almost all code in this blog is syntax highlighted by this add-on (read more from my post Visual Studio add-in: CopySourceAsHTML).

Last version of CSAH is available for VS2008 but it is easy to make it work with VS2010. Just follow these steps.

  1. Close VS2010 if it is opened.
  2. Goto folder MyDocuments\Visual Studio 2010.
  3. Move to AddIns subfolder (create it if there is no such subfolder).
  4. Create file called CopySourceAsHtml.AddIn and open it in text editor.
  5. Paste the following XML to editor:

     


    <?xml version="1.0" encoding="utf-8" standalone="no"?>

    <Extensibility xmlns="http://schemas.microsoft.com/AutomationExtensibility">

    <HostApplication>

    <Name>Microsoft Visual Studio Macros</Name>

    <Version>10.0</Version>

    </HostApplication>

    <HostApplication>

    <Name>Microsoft Visual Studio</Name>

    <Version>10.0</Version>

    </HostApplication>

    <Addin>

    <FriendlyName>CopySourceAsHtml</FriendlyName>

    <Description>Adds support to Microsoft Visual Studio 2010 for copying source code, syntax highlighting, and line numbers as HTML.</Description>

    <Assembly>JTLeigh.Tools.Development.CopySourceAsHtml, Version=3.0.3215.1, Culture=neutral, PublicKeyToken=bb2a58bdc03d2e14, processorArchitecture=MSIL</Assembly>

    <FullClassName>JTLeigh.Tools.Development.CopySourceAsHtml.Connect</FullClassName>

    <LoadBehavior>1</LoadBehavior>

    <CommandPreload>0</CommandPreload>

    <CommandLineSafe>0</CommandLineSafe>

    </Addin>

    </Extensibility>


  6. Save file and close it.
  7. Run VS2010 and activate add-on if it is not activated yet.

That’s it. If you are heavy user of CSAH then I recommend you to bookmark this post. :)

ASP.NET MVC: Simple view to display contents of DataTable

In one of my current projects I have to show reports based on SQL Server views. My code should be not aware of data it shows. It just asks data from view and displays it user. As WebGrid didn’t seem to work with DataTable (at least with no hocus-pocus) I wrote my own very simple view that shows contents of DataTable.

I don’t focus right now on data querying questions as this part of my simple generic reporting stuff is still under construction. If the final result is something good enough to share with wider audience I will blog about it for sure.

My view uses DataTable as model. It iterates through columns collection to get column names and then iterates through rows and writes out values of all columns. Nothing special, just simple generic view for DataTable.


@model System.Data.DataTable
@using
System.Data;

<h2>Report</h2>

<table>
    <thead>
    <tr>
    @foreach (DataColumn col in
Model.Columns)    
    {         
       
<th>@col.ColumnName</th>
    }    
   
</tr>
    </thead>
        
   
<tbody>
    @foreach (DataRow row in
Model.Rows)    
    {        
       
<tr>
        @foreach (DataColumn col in
Model.Columns)        
        {             
           
<td>@row[col.ColumnName]</td>
        }        
       
</tr>
    }    
   
</tbody>
</table
>

In my controller action I have code like this. GetParams() is simple function that reads parameter values from form. This part of my simple reporting system is still under construction but as you can see it will be easy to use for UI developers.


public ActionResult TasksByProjectReport()
{
    
var data = _reportService.GetReportData("MEMOS",
GetParams());
    
return View(data);
}

Before seeing next silver bullet in this example please calm down. It is just plain and simple stuff for simple needs. If you need advanced and powerful reporting system then better use existing components by some vendor.

Posted: Nov 19 2011, 01:46 PM by DigiMortal | with 3 comment(s) |
Filed under: ,
Using Lazy<T> and abstract wrapper class to lazy-load complex system parameters

.NET Framework 4.0 introduced new class called Lazy<T> and I wrote blog post about it: .Net Framework 4.0: Using System.Lazy<T>. One thing is annoying for me – we have to keep lazy loaded value and its value loader as separate things. In this posting I will introduce you my Lazy<T> wrapper for complex to get system parameters that uses template method to keep lazy value loader in parameter class.

 

NB! This blog is moved to gunnarpeipman.com

Click here to go to article

Solution to Jira web service getWorklogs method error: Object of type System.Xml.XmlNode[] cannot be stored in an array of this type

When using Jira web service methods that operate on work logs you may get the following error when running your .NET application: Object of type System.Xml.XmlNode[] cannot be stored in an array of this type. In this posting I will show you solution to this problem.

I don’t want to go to deep in details about this problem. I think it’s enough for this posting to mention that this problem is related to one small conflict between .NET web service support and Axis. Of course, Jira team is trying to solve it but until this problem is solved you can use solution provided here.

There is good solution to this problem given by Jira forum user Kostadin. You can find it from Jira forum thread RemoteWorkLog serialization from Soap Service in C#. Solution is simple – you have to use SOAP extension class to replace new class names with old ones that .NET found from WSDL. Here is the code by Kostadin.


public class JiraSoapExtensions : SoapExtension

{

    private Stream _streamIn;

    private Stream _streamOut;

 

    public override void ProcessMessage(SoapMessage message)

    {

        string messageAsString;

        StreamReader reader;

        StreamWriter writer;

 

        switch (message.Stage)

        {

            case SoapMessageStage.BeforeSerialize:

                break;

            case SoapMessageStage.AfterDeserialize:

                break;

            case SoapMessageStage.BeforeDeserialize:

                reader = new StreamReader(_streamOut);

                writer = new StreamWriter(_streamIn);

                messageAsString = reader.ReadToEnd();

                switch (message.MethodInfo.Name)

                {

                    case "getWorklogs":

                    case "addWorklogWithNewRemainingEstimate":

                    case "addWorklogAndAutoAdjustRemainingEstimate":

                    case "addWorklogAndRetainRemainingEstimate":

                        messageAsString = messageAsString.
                            .Replace(
"RemoteWorklogImpl", "RemoteWorklog")
                            .Replace(
"service", "beans");

                        break;

                }

                writer.Write(messageAsString);

                writer.Flush();

                _streamIn.Position = 0;

                break;

            case SoapMessageStage.AfterSerialize:

                _streamIn.Position = 0;

                reader = new StreamReader(_streamIn);

                writer = new StreamWriter(_streamOut);

                messageAsString = reader.ReadToEnd();

                writer.Write(messageAsString);

                writer.Flush(); break;

        }

    }

 

    public override Stream ChainStream(Stream stream)

    {

        _streamOut = stream;

        _streamIn = new MemoryStream();

        return _streamIn;

    }

 

    public override object GetInitializer(Type type)

    {

        return GetType();

    }

 

    public override object GetInitializer(LogicalMethodInfo info,
       
SoapExtensionAttribute attribute)

    {

        return null;

    }

 

    public override void Initialize(object initializer)

    {

    }

}


To get this extension work with Jira web service you have to add the following block to your application configuration file (under system.web section).


<webServices>
  <soapExtensionTypes>
   <add type="JiraStudioExperiments.JiraSoapExtensions,JiraStudioExperiments" 
        
priority="1"/>
  </soapExtensionTypes>
</webServices
>

Weird thing is that after successfully using this extension and disabling it everything still works.

ASP.NET MVC: Converting business objects to select list items

Some of our business classes are used to fill dropdown boxes or select lists. And often you have some base class for all your business classes. In this posting I will show you how to use base business class to write extension method that converts collection of business objects to ASP.NET MVC select list items without writing a lot of code.

BusinessBase, BaseEntity and other base classes

I prefer to have some base class for all my business classes so I can easily use them regardless of their type in contexts I need.

NB! Some guys say that it is good idea to have base class for all your business classes and they also suggest you to have mappings done same way in database. Other guys say that it is good to have base class but you don’t have to have one master table in database that contains identities of all your business objects. It is up to you how and what you prefer to do but whatever you do – think and analyze first, please. :)

To keep things maximally simple I will use very primitive base class in this example. This class has only Id property and that’s it.


public class BaseEntity

{

    public virtual long Id { get; set; }

}


Now we have Id in base class and we have one more question to solve – how to better visualize our business objects? To users ID is not enough, they want something more informative. We can define some abstract property that all classes must implement. But there is also another option we can use – overriding ToString() method in our business classes.


public class Product : BaseEntity

{

    public virtual string SKU { get; set; }

    public virtual string Name { get; set; }

 

    public override string ToString()

    {

        if (string.IsNullOrEmpty(Name))

            return base.ToString();

 

        return Name;

    }

}


Although you can add more functionality and properties to your base class we are at point where we have what we needed: identity and human readable presentation of business objects.

Writing list items converter

Now we can write method that creates list items for us.


public static class BaseEntityExtensions

{       

    public static IEnumerable<SelectListItem> ToSelectListItems<T>
        (
this IList<T> baseEntities) where T :
BaseEntity

    {

        return ToSelectListItems((IEnumerator<BaseEntity>)
                   baseEntities.GetEnumerator());

    }

 

    public static IEnumerable<SelectListItem> ToSelectListItems
        (
this IEnumerator<BaseEntity> baseEntities)

    {

        var items = new HashSet<SelectListItem>();

 

        while (baseEntities.MoveNext())

        {

            var item = new SelectListItem();

            var entity = baseEntities.Current;

 

            item.Value = entity.Id.ToString();

            item.Text = entity.ToString();

 

            items.Add(item);

        }

 

        return items;

    }

}


You can see here to overloads of same method. One works with List<T> and the other with IEnumerator<BaseEntity>. Although mostly my repositories return IList<T> when querying data there are always situations where I can use more abstract types and interfaces.

Using extension methods in code

In your code you can use ToSelectListItems() extension methods like shown on following code fragment.


...

var model = new MyFormModel();

model.Statuses = _myRepository.ListStatuses().ToSelectListItems();

...


You can call this method on all your business classes that extend your base entity. Wanna have some fun with this code? Write overload for extension method that accepts selected item ID.

Posted: Nov 10 2011, 11:10 AM by DigiMortal | with 4 comment(s)
Filed under: ,
More Posts