Lost in The GC

Sergio Tapia Gutierrez - Developer Blog

  • About
  • Portfolio

How to serialize a List<T> object into an XML string.

Posted by lostinthegc on April 20, 2012
Posted in: .NET, C#. Tagged: list c# .net serialization xml. 1 comment

I’m going to show you how to convert a List<T> object into a properly formatted XML string you can use to POST to a HTTP endpoint.

First, let me show you my C# POCO classes:

   1: [Serializable()]

   2: public class GameMatch

   3: {

   4:     public GameMatch()

   5:     {

   6:         Summoners = new List<Summoner>();

   7:     }

   8:  

   9:     public int GameId { get; set; }

  10:     public string MethodType { get; set; }

  11:     public int GameLength { get; set; }

  12:     public string GameMode { get; set; }

  13:     public string GameType { get; set; }

  14:     public int IpEarned { get; set; }

  15:     public int IpTotal { get; set; }

  16:  

  17:     public List<Summoner> Summoners { get; set; }

  18: }

  19:  

  20: [Serializable()]

  21: public class Summoner

  22: {

  23:     public Summoner()

  24:     {

  25:         Items = new List<Item>();

  26:     }

  27:  

  28:     public List<Item> Items { get; set; } //DONE

  29:  

  30:     public int ProfileIconId { get; set; } //DONE

  31:     public string SummonerName { get; set; } //DONE

  32:     public int Level { get; set; } //DONE

  33:     public int ChampionLevel { get; set; } //DONE

  34:     public bool BotPlayer { get; set; } //DONE

  35:         

  36:     public int Wins { get; set; } //DONE

  37:     public int Losses { get; set; } //DONE

  38:     public int Leaves { get; set; } //DONE

  39:  

  40:     public int NeutralCreepsKilled { get; set; } //DONE

  41:     public int MinionsKilled { get; set; } //DONE

  42:     public int ChampionsKilled { get; set; } //DONE

  43:     public int Assists { get; set; } //DONE

  44:     public int LargestMultiKill { get; set; } //DONE

  45:         

  46:     public string SkinName { get; set; } //DONE

  47:     public int SummonerSpell1Id { get; set; } //DONE

  48:     public int SummonerSpell2Id { get; set; } //DONE

  49:  

  50:     public int DamageDealt { get; set; } //DONE

  51:     public int PhysicalDamageDealt { get; set; } //DONE

  52:     public int MagicDamageDealt { get; set; } //DONE

  53:     public int LargestCriticalStrike { get; set; } //DONE

  54:     public int HealingDone { get; set; } //DONE

  55:  

  56:     public int PhysicalDamageTaken { get; set; } //DONE

  57:     public int DamageTaken { get; set; } //DONE

  58:     public int MagicDamageTaken { get; set; } //DONE

  59:  

  60:     public int GoldEarned { get; set; } //DONE

  61:     public int TimeSpentDead { get; set; } //DONE

  62:  

  63:         

  64:         

  65:     public int InhibitorsDestroyed { get; set; } //DONE

  66:     public int TurretsDestroyed { get; set; } //DONE

  67:         

  68:     public int Deaths { get; set; } //DONE

  69:     public int LargestKillingSpree { get; set; } //DONE

  70:     public int Lose { get; set; } // Maybe this means, 1 = lost; 0 = won? Look into it.

  71: }

  72:  

  73: [Serializable()]

  74: public class Item

  75: {

  76:     public int ItemId { get; set; }

  77: }

 

Simple easy to understand POCO classes with automatic properties.

Next, to serialize them all we need to do is use a XmlTextWriter and XmlSerialWriter

   1: List<GameMatch> parsedMatches = LogParser.Parse(path);

   2:  

   3: StringWriter stringWriter = new StringWriter();

   4: XmlDocument xmlDoc = new XmlDocument();

   5:  

   6: XmlTextWriter xmlWriter = new XmlTextWriter(stringWriter);

   7:  

   8: XmlSerializer serializer = new XmlSerializer(typeof(List<GameMatch>));

   9:  

  10: serializer.Serialize(xmlWriter, parsedMatches);

  11:  

  12: string xmlResult = stringWriter.ToString();

  13:  

  14: xmlDoc.LoadXml(xmlResult);

At this point stringWriter.ToString() will return a pure string of the XML representation of your List<T> object.

Hope this helps!

How to style the date html input type using CSS.

Posted by lostinthegc on April 17, 2012
Posted in: CSS, HTML, jQuery, jQueryUI. Tagged: input date html5 google chrome canary opera input type date. 2 comments

If you haven’t heard already there is a (no-so) new HTML input type used specifically for date inputs. The idea is that in the future instead of having to use a library such as jQuery, you can just invoke a simple HTML input:

   1: <input type="date" min="2010-08-14" max="2011-08-14" value="2010-08-14"/>

And it looks and feels wonderful.

Let’s see what styling we can apply to this elegant input.

1. Applying the color rule.

You can apply the color rule to the input and it works as you would expect:

   1: input {

   2:   color:red;

   3: }

ss1

2. Applying the border rule.

You can also apply the border rule but it seems this only applies to the input, not the calendar widget that appears on focus.

   1: input {

   2:   border:1px solid red;

   3: }

ss2

3. Applying the padding rule.

Padding can also be used for this input, however the calendar widget remains untouched.

   1: input {

   2:   padding:10px;

   3: }

ss3

 

So we can’t customize the look and feel of the calendar widget?

After testing this new input it seems that the browsers that support it (Google Chrome Canary and the latest Opera) do not allow you to change how the calendar looks.

Google Chrome uses this stylesheet to apply design to the input, but you won’t get any changes on the other browsers.

This is bad news as sometimes we as web developers are asked to modify existing calendar widgets to match the look and feel of the website.

Hopefully this changes in the future, we’ll keep our eyes peeled.

The not-so-new HTML input date. So lean, so clean.

Posted by lostinthegc on April 17, 2012
Posted in: HTML, jQueryUI. Tagged: html input html5 date. Leave a Comment

When you’re a web developer, most companies ask you to create some input forms, and more often than not you’re required to ask the user for a date input.

The above element was created using the most excellent jQueryUI DatePicker widget. Usage is simple:

   1: $('input[name="dateofbirth"]').datepicker();

It’s small, lean and since you are probably already using jQuery the overhead is minimal. But still, this should be something that’s built in, correct?

And it turns out that there is in fact an HTML element that’s build for this purpose. Baked right into the browser!

Firefox users you’re out of luck as of 11.0
Google Chrome users you’re out of luck as of 18.0
Opera users, once again your browser of choice is a pioneer leading the way.

It’s a shame this browser isn’t getting more market share it’s blazing fast, very light and it has never once crashed on me in the 7 years I’ve been using it.

Let’s see the input type=”date” element in action:
http://dev.w3.org/html5/markup/input.date.html

   1: <input type="date" min="1989-08-09" max="2012-12-0" value="2010-05-15"/>

Save the markup in a regular html file and open it using the latest version of Opera.

Works exactly as you would expect from a modern calendar select widget and it’s very lightweight coming down the wire.

You can even style it as you please. (More or less, more on that later)

I would love to see more browsers update to implement correct standards, it would be so exciting! And in that regard, I applaud Chrome for automatically upgrading without letting users know what version they are running. Chrome users more often than not are just running the cutting edge latest version of their browsers whereas I know some people still rocking Firefox 3.

WinHost – MVC3 web application users are logged out / sessions lost.

Posted by lostinthegc on March 19, 2012
Posted in: .NET, C#, MVC3, Session, Software Development, WinHost. Tagged: app pool, log in, mvc3, recycle, session, winhost. Leave a Comment

I wrote this small tutorial on the WinHost forums because many people seem to face random logout and session wipes when hosting on a shared environment. This for an MVC3 web application, but should work across the board.

Here’s how I fixed this issue by switching over to SQL Session saving.

Basically the issue boils down to this:

WinHost recycles your web application whenever your web app reaches it’s memory pool limit. It also recycles it when there has been no HTTP activity for over 20 minutes.

When this happens, all information in session in lost. Since MVC3 uses InProc as the default for saving session information, this means logged in users are now logged out, every time your app pool recycles.

The fix is very simple, although I did have to hunt down some old forums posts and StackOverflow questions. Hopefully this saves some people some headaches.

Although not necessary, I recommend you give this article a read to get an overview of what it is we’re going to do to our web application.

1. Create a support ticket to request an installation of the SQL Server Session database.

While WinHost recommends you use a separate database for this, it works perfectly fine if you use only one. The downside is you’ll have three extra tables that aren’t related to the business end of the application. Not a problem though.

“Hello, please install the sql server session schema on my database: “foobarbaz”.

2. Add the relevant sessionState node to your web.config file.

   1: <system.web>

   2:     <sessionState mode="SQLServer"

   3:                   allowCustomSqlDatabase="true"                  

   4:                   cookieless="false"

   5:                   timeout="2880"

   6:                   sqlConnectionString="data Source='tcp:s027.winhost.com';database='DB_3347_mydb';user id='DB_23_my_user'; password='mypassword';" />

This is essentially changing the way MVC3 is saving our session information. From InProc to SQLServer.

3. Generate a machine key.

Generate a machine key using this online tool and copy it somewhere.

4. Paste the machine key inside your root web.config file.

   1: <machineKey validationKey="D87832412312312312332EB48DC12091C2A671F2B6BFB733E5C50179A875EE03902E0127A46D38" 

   2:             decryptionKey="0769851231231231231239F7" 

   3:             validation="SHA1" 

   4:             decryption="AES" />    

   5: <trust level="Full"/>

Notice that we’re also setting trust level to Full.

 

That’s all you need to fix this problem.

Now if your app pool is recycled, your users will no longer be logged out. As an example I’ll post two small code snippet below. One shows you how I log users into my web application. The other shows you how I check if a user is logged in.

Login example:

   1: [HttpPost]

   2: public ActionResult Login(LogOnModel model)

   3: {

   4:     using (EfAccountRepository accountRepository = new EfAccountRepository())

   5:     {

   6:         if (accountRepository.ValidateCredentials(model.Email, model.Password))

   7:         {

   8:             //THE IMPORTANT BIT IS THIS.

   9:             FormsAuthentication.SetAuthCookie(model.Email, true);

  10:             return RedirectToAction("Index", "Home");

  11:         }

  12:         ModelState.AddModelError("", "Your email or password is incorrect.");

  13:         return View(model);

  14:     }

  15: }

Logged in status verification:

   1: public static bool UserIsPartOfCompany(HttpContext context)

   2: {

   3:     if (!context.Request.IsAuthenticated)

   4:         return false;

   5:  

   6:     using (EfAccountRepository accountRepository = new EfAccountRepository())

   7:     {

   8:         var loggedInUser = accountRepository.FindByEmail(context.User.Identity.Name);

   9:         string[] userRoles = accountRepository.GetRolesForUser(loggedInUser.AccountId);

  10:  

  11:         return userRoles.Contains("Editor") || userRoles.Contains("Finance") || userRoles.Contains("Administrator");

  12:     }

  13: }

  14:  

 

That’s all there is to it! If you have any questions, please let me know.

ASP.Net MVC3 Custom Membership | AuthorizeAttribute Tutorial

Posted by lostinthegc on February 4, 2012
Posted in: Uncategorized. Leave a Comment

 

Using SquishIt in an ASP.Net MVC3 web application.

Posted by lostinthegc on January 14, 2012
Posted in: .NET, C#, HTML, javascript, MVC3. Tagged: asp.net, compress, css, minify, mvc3, squishit. 1 comment

SquishIt is a fantastic library that allows you to easily combines all of your CSS files into a single file and also minifies it to boot! It also does the same thing on your Javascript.

Check out the difference:

SquishIT comparison MVC3

Let’s see how to use it in an ASP.Net MVC3 application.

Continue Reading

How to make a category menu using jQuery UI’s Accordion and pure HTML.

Posted by lostinthegc on January 7, 2012
Posted in: HTML, javascript, jQuery, jQueryUI. Tagged: accordion, jquery, jquery-ui, nested category menu. Leave a Comment

Today I’ll show you how to make a nested category navigation menu.

It’s very lightweight and looks something like this:

The simple menu we're going to make.

We’re going to use jQuery UI’s Accordion widget to make the categories collapse and expand when necessary and we’ll use some clever javascript and HTML markup to make the menu look useful. To see the nested category menu example, follow the link at the end of this post to go to the JSFiddle example.

Continue Reading

Posts navigation

← Older Entries
  • Welcome to my blog!

    Hi and welcome to my little corner on the internet.

    I'm a software developer based in Bolivia, and I mostly program in C# or Ruby.

    You'll see me writing mostly about .NET things, Rails development and sometimes if I'm feeling particularly inspired some Unit Testing articles.


    profile for Sergio at Stack Overflow, Q&A for professional and enthusiast programmers
  • Recent Posts

    • How to serialize a List<T> object into an XML string.
    • How to style the date html input type using CSS.
    • The not-so-new HTML input date. So lean, so clean.
    • WinHost – MVC3 web application users are logged out / sessions lost.
    • ASP.Net MVC3 Custom Membership | AuthorizeAttribute Tutorial
  • Archives

    • April 2012
    • March 2012
    • February 2012
    • January 2012
    • September 2011
    • August 2011
    • May 2011
    • April 2011
    • March 2011
  • Categories

    • .NET
    • Ajax
    • API
    • Bitcoin
    • C#
    • CSS
    • Editor Templates
    • Freelancing
    • Gadget
    • HTML
    • IPhone
    • javascript
    • jQuery
    • jQueryUI
    • JSON
    • MVC3
    • Objective-C
    • P2P
    • Ruby
    • Security
    • Session
    • SignalR
    • Software Development
    • Uncategorized
    • Validation
    • VM
    • Windows Forms
    • WinHost
  • Meta

    • Register
    • Log in
    • Entries RSS
    • Comments RSS
    • WordPress.com
Blog at WordPress.com. Theme: Parament by Automattic.
Lost in The GC
Blog at WordPress.com. Theme: Parament.
Follow

Get every new post delivered to your Inbox.

Powered by WordPress.com
Cancel