09 Nov 2010 @ 6:21 PM 

Here is a snippet for rendering a partial view to a string. After you make a string from the view, you can pass the html as a json result. This let’s you have more control over the actions you can take in your javascript when you receive your response.

        public string RenderPartialToString(string controlName, ViewDataDictionary viewDataDictionary)
        {
            var viewContext = new ViewContext();
            var urlHelper = new UrlHelper(this.ControllerContext.RequestContext);

            var viewPage = new ViewPage
            {
                ViewData = viewDataDictionary,
                ViewContext = viewContext,
                Url = urlHelper,
            };

            var control = viewPage.LoadControl(controlName);
            viewPage.Controls.Add(control);

            var sb = new StringBuilder();
            using (var sw = new StringWriter(sb))
            using (var tw = new HtmlTextWriter(sw))
            {
                viewPage.RenderControl(tw);
            }

            return sb.ToString();
        }

What’s important here is that I pass in the viewdatadictionary. I do this so that I can build the modelstate before passing it in to be rendered. In my particular use case I already had a form that was rendering a validation summary and I needed to keep this functionality. So I add my model errors to the new view data dictionary, and the erros render on the partial view. I then return a json result with a false success and the rendered html.

Here’s is an example of the controller action.

public ActionResult VerifyThisCode(string code)
        {
            var dataDictionary = new ViewDataDictionary();
            if(!ValidateCode(code, datadictionary))
            {
                        return Json(new { success = "false", view = RenderPartialToString("~/Views/Verify/BadCode.ascx", datadictionary) });
            }
            if(NotLoggedIn())
            {
                        dataDictionary.ModelState.AddModelError("NotLoggedIn", "Please, log in or sign up to redeem this code.");
                        dataDictionary.Model = Request.UrlReferrer.AbsolutePath.ToString();
                        return Json(new { success = "false", view = RenderPartialToString("~/Views/Shared/LoginSignup.ascx", dataDictionary) });
            }
            Code validCode = _codeRepository.GetCode(code);
            dataDictionary.Model = Code;
            return Json(new { success = "true", view = RenderPartialToString("~/Views/Verify/GoodCode.ascx", dataDictionary) });
}

I can change what model I set on the data dictionary depending on which view I want to use. Or set none at all. Now finally the javascript that uses this.

$('#validateCode').click(function(event) {
            event.preventDefault();
            $.ajax({
                url: path + 'Verify/VerifyThisCode',
                data: $('#code').val(),
                success: function(data) {
                    $('#codeContent').html('');
                    $('#codeContent').append(data.view);
                    $('#codeRedeemed').fadeIn();
                    if (data.success == 'true') {
                        RefreshMySelectionOfCodes();
                    }
                }

            });
        });

What this does is show a modal dialog with my partial view rendered into it. But only in the event of a success do I refresh the selection of codes.

Posted By: boyd21
Last Edit: 14 Apr 2011 @ 10:33 PM

EmailPermalinkComments Off
Tags
Tags: , , ,
Categories: .Net, Programming
 21 Oct 2010 @ 10:15 AM 

Here are a couple real handy enum exntensions to have around. This first one returns all the vaues of the enum in a list. This is perfect for generating dropdown lists or selections. The important aspect to note here is that the list will always contain the latest additions to the enum. So you don’t have to go back and rewrite your dropdowns for the enum, it does it for you.

public static IEnumerable<T> GetEnumValues<T>(this Enum obj)
{
        IList<T> values = new List<T>();
        foreach (var val in Enum.GetValues(typeof(T)).Cast<T>())
        {
                values.Add(val);
        }
        return values;
}

This next one turns the enum value into a more readable form. Automatically parsing out camel casing into spaces. This particular regex statement requires a preceeding and following lower case letter to space. The regex is followed by simple extension methods, for both string replacement and enum replacement.

private const string RegExEnglishPattern = "(?<!^)([A-Z][a-z]|(?<=[a-z])[A-Z])";

/// <summary>
/// Correctly spaces the enumeration value to make it english-like.
/// </summary>
/// <param name="e">The enumeration.</param>
/// <returns>The english-like form of the enumeration value.</returns>
public static string ToEnglish(this Enum e)
{
        return Regex.Replace(e.ToString(), RegExEnglishPattern, " $1");
}

public static string ToEnglish(this string value)
{
        return Regex.Replace(value, RegExEnglishPattern, " $1", RegexOptions.Compiled).Trim();
}
Posted By: boyd21
Last Edit: 14 Apr 2011 @ 09:54 PM

EmailPermalinkComments Off
Tags
Tags: , , ,
Categories: .Net, Programming
 25 Mar 2009 @ 9:14 PM 

Open your xps file or generate it to a memory stream.

private MemoryStream XPSFile;
private const string pack = "pack://temp.xps";
private Uri uri = new Uri(pack);

var pkg = Package.Open(XPSFile, FileMode.OpenOrCreate, FileAccess.ReadWrite);
PackageStore.AddPackage(uri, pkg);
var doc = new XpsDocument(pkg, CompressionOption.SuperFast, pack);

Now you have an xps document in memory. You can set it to view in the document viewer, or print it off, or what else you can think of.

Posted By: boyd21
Last Edit: 20 Jun 2009 @ 08:16 AM

EmailPermalinkComments Off
Tags
Tags: ,
Categories: .Net, Hardware Maintenance, Programming
 11 Mar 2009 @ 10:31 PM 

This is a simple extension method that can be added to retrieve a bitmap of any control. It can be as specific as a text box, or image viewer, or as general as your entire application.


public static Bitmap GetImage(this Control obj)
{
obj.CreateGraphics();
var bmp = new Bitmap(obj.Width, obj.Height);
obj.DrawToBitmap(bmp, new Rectangle(0, 0, obj.Width, obj.Height));
return bmp;
}

Posted By: boyd21
Last Edit: 11 Mar 2009 @ 10:31 PM

EmailPermalinkComments (699)
Tags
Tags: , , ,
Categories: .Net, Programming
 09 Mar 2009 @ 9:38 PM 

You can easily find the differences between datasets, dataviews, data tables or any collection using Linq and Enumerables. This is useful if you just want to view the changes that have been made, or if you want to determine if the two datasets match each other, say for testing purposes.

Our first example is a simple list. First convert both lists to enumerables. Then intersect the two.

Enumerable<SomeObject> diff = List<SomeObject>.AsEnumerable().Intersect(List<SomeObject>.AsEnumerable());

Our diff enumerable will contain all the elements that are different. If you already have enumerables, then this is as simple as calling intersect. Any elements in the diff list will be the elements that do not occur in both lists.

Assert.IsTrue(diff.Count() == 0);

If we have a count greater than zero, then our two lists do not contain the same elements. So if our resulting count is zero, our two enumerables are equal.

In order to do the same with datasets, dataviews and data tables we’ll first need to reference the DataTable Extensions methods library. This will open up extension methods to convert data tables to enumerables. Once we get our enumerable, we simply call intersect in the same manner as before.

var resultsDiff = DataSet.Tables[0].AsEnumerable().Intersect(DataSet.Tables[0].AsEnumerable());

Assert.IsTrue(resultsDiff.Count() == 0);

If you’re working with datasets or dataviews, you need to get to the underlying data table in order to use the extension method to convert it into an enumerable.

Posted By: boyd21
Last Edit: 10 Mar 2009 @ 10:53 PM

EmailPermalinkComments (3)
Tags
Tags: , , , , , ,
Categories: .Net

 Last 50 Posts
Change Theme...
  • Users » 3
  • Posts/Pages » 30
  • Comments » 0
Change Theme...
  • VoidVoid « Default
  • LifeLife
  • EarthEarth
  • WindWind
  • WaterWater
  • FireFire
  • LightLight

GeekPub



    No Child Pages.