Wednesday, 15 May 2013

Render partial view into string in controller



I have run into a situation where I would like to render a partial view to a string and then return it as part of a JSON response like so:

return Json(new {
 personHtml = RenderPartialViewToString("Person", person)
});
The ability to do something like this would open up a ton of amazing possibilities, so I really scoured the internet looking for a solution. Unfortunately, no one seems to have come up with a clean solution for it, so I dug into the MVC code and came up one…and because I’m such a nice guy, you get to copy it for free. ;)


public abstract class MyBaseController : Controller {

    protected string RenderPartialViewToString()
    {
        return RenderPartialViewToString(null, null);
    }

    protected string RenderPartialViewToString(string viewName)
    {
        return RenderPartialViewToString(viewName, null);
    }

    protected string RenderPartialViewToString(object model)
    {
        return RenderPartialViewToString(null, model);
    }

    protected string RenderPartialViewToString(string viewName, object model)
    {
        if (string.IsNullOrEmpty(viewName))
            viewName = ControllerContext.RouteData.GetRequiredString("action");

        ViewData.Model = model;

        using (StringWriter sw = new StringWriter()) {
            ViewEngineResult viewResult = ViewEngines.Engines.FindPartialView(ControllerContext, viewName);
            ViewContext viewContext = new ViewContext(ControllerContext, viewResult.View, ViewData, TempData, sw);
            viewResult.View.Render(viewContext, sw);

            return sw.GetStringBuilder().ToString();
        }
    }
}

Now you can simply do this:

public class MyController : MyBaseController {

    public ActionResult CreatePerson(Person p) {     
            return Json(new {
                    statusCode = 1,
                    statusMessage = "The person has been added!",
                    personHtml = RenderPartialViewToString("Person", p)
                });
    }
}
Also note that you can modify these functions to render a View (rather than a PartialView) with this small change:

ViewEngineResult viewResult = ViewEngines.Engines.FindView(ControllerContext, viewName);
Enjoy!

My final implementation is:

  /// <summary>
        /// Renders the partial view to string.
        /// </summary>
        /// <param name="viewName">Name of the view.</param>
        /// <param name="model">The model.</param>
        /// <param name="controllerContext">The controller context.</param>
        /// <param name="viewData">The view data.</param>
        /// <param name="tempData">The temp data.</param>
        /// <returns>Returns parsed view as string.</returns>
        /// <remarks>
        /// Used from page: http://craftycodeblog.com/2010/05/15/asp-net-mvc-render-partial-view-to-string/
        /// </remarks>
        public static string RenderPartialViewToString(string viewName, object model, ControllerContext controllerContext, ViewDataDictionary viewData, TempDataDictionary tempData)
        {
            viewData.Model = model;

            using (StringWriter sw = new StringWriter())
            {
                ViewEngineResult viewResult = ViewEngines.Engines.FindPartialView(controllerContext, viewName);
                ViewContext viewContext = new ViewContext(controllerContext, viewResult.View, viewData, tempData, sw);
                viewResult.View.Render(viewContext, sw);

                return sw.GetStringBuilder().ToString();
            }
        } 
My code is based on :
http://craftycodeblog.com/2010/05/15/asp-net-mvc-render-partial-view-to-string 

Locking thread singleton example

Example of implementing singleton.


 public class Settings
    {
        /// <summary>
        /// Private lock used while loading
        /// </summary>
        private Object setupLock = new Object();

        /// <summary>
        /// Container for settings loaded from web.config.
        /// </summary>
        private Dictionary<string, object> _settings { get; set; }

        /// <summary>
        /// While class is getting loading information from app.config, the object is locked.
        /// </summary>
        public Settings()
        {
            // Check if settings is null, othewise do not carry on with constructing settings.
            if (_settings == null)
            {
                // Add lock on the process inside
                lock (setupLock)
                {
                    // if this has been hit by 2 processes after each other, make sure that the value is still before start processing.
                    if (_settings == null)
                    {
                        var settings = new Dictionary<string, object>();
                        foreach (var key in ConfigurationManager.AppSettings.AllKeys)
                        {
                            settings.Add(key, ConfigurationManager.AppSettings[key].ToString(CultureInfo.InvariantCulture));
                        }
                        _settings = settings;
                    }
                }
            }
        }

    }
}

Thursday, 9 May 2013

Generate class from xml

Using XML Schema Definition Tool (Xsd.exe)

I needed to write code that maps data in xml to my cs file.
I know that that xsd can generate this.

Lets do it step by step.

Generate definition file


C:\test\1>xsd AttachFileHandler.xml
Microsoft (R) Xml Schemas/DataTypes support utility
[Microsoft (R) .NET Framework, Version 4.0.30319.17929]
Copyright (C) Microsoft Corporation. All rights reserved.
Writing file 'C:\test\1\AttachFileHandler.xsd'.




Generate class: 

c:\test\1>xsd /classes /language:CS AttachFileHandler.xsd
Microsoft (R) Xml Schemas/DataTypes support utility
[Microsoft (R) .NET Framework, Version 4.0.30319.17929]
Copyright (C) Microsoft Corporation. All rights reserved.
Writing file 'c:\test\1\AttachFileHandler.cs'.


Generate dataset

C:\test\1>xsd /dataset /language:CS AttachFileHandler.xsd
Microsoft (R) Xml Schemas/DataTypes support utility
[Microsoft (R) .NET Framework, Version 4.0.30319.17929]
Copyright (C) Microsoft Corporation. All rights reserved.
Writing file 'C:\test\1\AttachFileHandler.cs'.


 Final result



C:\test\1>dir

 Directory of C:\test\1

09/05/2013  12:11    <DIR>          .
09/05/2013  12:11    <DIR>          ..
09/05/2013  12:11           468,262 AttachFileHandler.cs
09/05/2013  12:05             2,746 AttachFileHandler.xml
09/05/2013  12:11             8,374 AttachFileHandler.xsd


Result => just extract of generated data

//------------------------------------------------------------------------------
// <auto-generated>
//     This code was generated by a tool.
//     Runtime Version:4.0.30319.18034
//
//     Changes to this file may cause incorrect behavior and will be lost if
//     the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------

using System.Xml.Serialization;

//
// This source code was auto-generated by xsd, Version=4.0.30319.17929.

//


/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.17929")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType=true)]
[System.Xml.Serialization.XmlRootAttribute(Namespace="", IsNullable=false)]
public partial class Statistics {
    }



For more help see following location:

http://msdn.microsoft.com/en-us/library/x6c1kb0s.aspx tool


Tuesday, 7 May 2013

TFS History command


Command to retrieve tfs history


Get me all things what we have worked on within last month.
I know that there is a command: "TF HISTORY"  with basic implementation below

tf history  $/Project/development /collection:http://tfs01:8080/tfs/DevelopmentServices/
Where:
1.      $/Project/development – Project against which you want to run report
2.      /collection:http://tfs01:8080/tfs/DevelopmentServices/ -  Tfs collection

Finally add options:

/noprompt
This option:
·         Suppresses the display of windows and dialog boxes (such as the History window) and redirects output data to the command prompt. See Team Foundation Version Control Command Reference.
·         Does not display the history of revisions that occurred before an item was moved, renamed, branched, or merged.

 tf history  $/Project/development /collection:http://tfs01:8080/tfs/DevelopmentServices/ /noprompt
This had disabled popups
  /user:username
Filters the historical data to show changes made by the specified user. An asterisk (*) symbol includes data on changes from all users (the default).
 tf history  $/Project/development /collection:http://tfs01:8080/tfs/DevelopmentServices/ /noprompt /user:*

This selected all users for history
/recursive
Recursively retrieves historical data on items in the specified directory and any sub directories.
 tf history  $/Project/development /collection:http://tfs01:8080/tfs/DevelopmentServices/ /noprompt /user:* /recursive
Suddenly I have all changesets
/format
Specifies how much detail to display about each changeset when the /noprompt option is specified:
·         Brief (default): Displays one line about each changeset that includes: ID number, changes made, user who made the changes, date, and comment. Some of the data may be truncated.
·         Detailed: Displays a full description of each changeset. In addition to the above information, this option displays additional data such as date with time, items changed, check-in notes, and check-in policy warnings.

 tf history  $/Project/development /collection:http://tfs01:8080/tfs/DevelopmentServices/ /noprompt /user:* /recursive /format:brief
This gets level of detail displayed about changesets

Final Command

tf history /noprompt $/Project/development /collection:http://tfs01:8080/tfs/DevelopmentServices/ /format:brief /v:D"01/05/2013"~D"05/08/2013" /user:*  /recursive

Resource for this article is of course MSDN

Monday, 22 April 2013

Mime type table to use for office documents

Mime table for office

after while trying to find right format I have found gold mine: here. Below is reference copy


Ext
MIME Type
.doc
application/msword
.dot
application/msword
.docx
application/vnd.openxmlformats-officedocument.wordprocessingml.document
.dotx
application/vnd.openxmlformats-officedocument.wordprocessingml.template
.docm
application/vnd.ms-word.document.macroEnabled.12
.dotm
application/vnd.ms-word.template.macroEnabled.12
.xls
application/vnd.ms-excel
.xlt
application/vnd.ms-excel
.xla
application/vnd.ms-excel
.xlsx
application/vnd.openxmlformats-officedocument.spreadsheetml.sheet
.xltx
application/vnd.openxmlformats-officedocument.spreadsheetml.template
.xlsm
application/vnd.ms-excel.sheet.macroEnabled.12
.xltm
application/vnd.ms-excel.template.macroEnabled.12
.xlam
application/vnd.ms-excel.addin.macroEnabled.12
.xlsb
application/vnd.ms-excel.sheet.binary.macroEnabled.12
.ppt
application/vnd.ms-powerpoint
.pot
application/vnd.ms-powerpoint
.pps
application/vnd.ms-powerpoint
.ppa
application/vnd.ms-powerpoint
.pptx
application/vnd.openxmlformats-officedocument.presentationml.presentation
.potx
application/vnd.openxmlformats-officedocument.presentationml.template
.ppsx
application/vnd.openxmlformats-officedocument.presentationml.slideshow
.ppam
application/vnd.ms-powerpoint.addin.macroEnabled.12
.pptm
application/vnd.ms-powerpoint.presentation.macroEnabled.12
.potm
application/vnd.ms-powerpoint.presentation.macroEnabled.12
.ppsm
application/vnd.ms-powerpoint.slideshow.macroEnabled.12