Showing posts with label C#. Show all posts
Showing posts with label C#. Show all posts

Tuesday, 13 April 2010

MVC DateTime Suffix HTMLHelper

Recently I have been working on an MVC Project, and tonight I got to the point where I wanted to output a date in a specific format, for example Tuesday 13th April 2010. Sadly DateTime formatting still doesn't allow you to specify output a suffix, you can do Tuesday 13 April 2010 but not what I wanted.


I decided that I could achieve what I wanted by writing a quick HTMLHelper, this would then allow me to specify a datetime format string with a magic / special character which I could then replace for the appropriate suffix.


Writing the helper was very quick and easy, if you want to learn about HTMLHelpers and how to write your own I recommend looking at Stephen Walther's Post on HTMLHelpers .

The code for my datetimehelper is below:


using System;
using System.Web.Mvc;

namespace mjjames.MVCHelpers
{
 public static class DateTimeExtensions
 {
  public static string DateTimeFormat(this HtmlHelper helper, string dateTimeFormat, DateTime dateTime){
            var dateTimeOutput = dateTime.ToString(dateTimeFormat);
            if (dateTimeFormat.Contains("~"))
            {
                dateTimeOutput = dateTimeOutput.Replace("~", GenerateDaySuffix(dateTime.Day));
            }
      return dateTimeOutput;
  }

        /// <summary>
        /// Generates a Day Suffix from the Day Number
        /// </summary>
        /// <param name="day">Day Number</param>
        /// <returns>Suffix String</returns>
     private static string GenerateDaySuffix(int day)
     {
         var suffix = "";
            //find out if the day matches a suffix which isn't th
         switch(day)
         {
             case 1:
                case 21:
                case 31:
                 suffix = "st";
                    break;
                case 2:
                case 22:
                 suffix = "nd";
                 break;
                case 3:
                case 23:
                 suffix = "rd";
                    break;
                default:
                 suffix = "th";
                 break;
         }
         return suffix;
     }
 }
}

Then to use it first include the namespace in your view:


<%@ Import Namespace="mjjames.MVCHelpers" %>

And then to use it call Html.DateTimeFormat passing the format string and the DateTime value. To use the day suffix include the ~ character. Note you can use it with.


<%= Html.DateTimeFormat("dddd d~ h", Model.StartDate) %>
<%= Html.DateTimeFormat("dddd d h", Model.EndDate) %>

There we go, nice and easy, if you want to use this feel free I hope it helps

Tuesday, 6 April 2010

Using DOTRas - An Overview and some things I've learnt

Yesterday I decided to starting knocking together a quick application to help me backup my server to some local storage. The idea being that at any point I have a local copy of my server setup a maximum of a day old. The point of this application and how I've gone about writing it, what libraries I'm using etc will be part of a future blog post.


I decided early on that I however I wanted to transfer files I wanted to do this over a VPN to the server. I had several reasons for this, being able to expose my files over a network share, more secure etc. My Application will be running on an old laptop, so I first thought about just always having it connected to a VPN using windows, and run the application as normal. However I then thought what if the VPN disconnects and I don't notice, how long would it take until I noticed etc. So I decided to make the application create a VPN Connection at start up and then disconnect from it upon completion.


I figured that there would be a good library that would help with this and it turns out there is. DotRAS provides remote access service (RAS) components for .NET languages , it's tag line is "WindowsRAS made easy" and I have to say so far it has lived up to that.


A quick example of how to open the computers RAS PhoneBook :


using(var phoneBook = new RasPhoneBook())
{
     phoneBook.Open();
}
You could then find an existing entry within the phonebook to make a connection too and open a connection:

var entry = phoneBook.Entries.FirstOrDefault(e => e.Name.Equals("mikes test entry");
if(entry != null){
    entry.Open();
}

Now there's obviously alot you can do with it, create and manage connections programatically etc, use phone dialers but so far I'm just tinkering with VPN's.


Tips and Tricks

Now to what I wanted to post about, tips and tricks. Sadly whilst working with DOTRas I found a few gotcha's that I wanted to post about. I will also update this list as I find more. It's worth noting that all of these apply to DotRAS 1.1 and I'm using the Win2k8 build, some of these I know also apply to the XPSP2 build. And my development machine is Windows 7 x64.

Invalid Default PhoneBook Location

The default phonebook location, which is called when you just do phonebook.Open(), is set to use RasPhoneBookType.AllUsers, now this maps to : C:\ProgramData\Microsoft\Network\Connections\Pbk\rasphone.pbk which for me doesn't exist. The folders exist up to connections, I have no Pbk folder.


I could obviously check for this and then create the phonebook entry but really you should always use RasPhoneBookType.User which uses the phonebook located within the current users AppData.

The entry is not associated with a phone book

Actually quite an obvious issue but worth commenting on, If you create a new phonebook entry


var entry = RasEntry.CreateVpnEntry(_connectionName, IPAddress.Loopback.ToString(), RasVpnStrategy.Default,                                 RasDevice.GetDeviceByName("(PPTP)", RasDeviceType.Vpn));

And then try to set the user's credentials without first adding the entry to the phonebook:


entry.UpdateCredentials(new NetworkCredential(authenticationDetails.UserName, authenticationDetails.Password));

Everything goes horribly wrong, instead add the entry to the phonebook and then set the credentials.


phoneBook.Entries.Add(entry);
entry.UpdateCredentials(new NetworkCredential(authenticationDetails.UserName, authenticationDetails.Password));

Keep an eye on this post, I'll update it as I continue to use DotRAS and then on a later date post about my application in full.

Friday, 20 March 2009

Book Review: C# 2008 and 2005 Threaded Programming

So last month Packt Publishing contacted me regarding sending me a promotional copy of C# 2008 and 2005 Threaded Programming to review. This is the first time I have been asked to do a book review and decided to take them up on the offer.


Now I have been using ASP.Net for around three years now but I've never had to or decided to look into writing multi-threaded apps so the fact that this book was aimed at beginners meant that I was an ideal target audience for this book. Packt shortly sent me the book and upon first looking at it thought it looked a bit ugly! I know you can't tell a book by its cover but this cover did put me off, the green and picture didn't do it for me but alas I carried on anyway.


The book is organised into several chapters and is example driven. What I mean by this is that it doesn't give you bags of theory and then an example, it takes the approach of you following along the code examples and then it has gaps explaining bits and pieces. More on this later.


The chapters within the book are organised in a way that as you progress each chapter delves into multi threading more. First of all it explains what multi threading is, then it looks as basic thread techniques, background workers, debugging multi threaded apps, thread pools all the way up to exploring the new future of multi threaded apps and new framework extensions to help with this. On the whole the chapter organisation made a lot of sense to me and allowed you to use what you had learnt before and build upon it. The one thing that struck me was that I expected ThreadPools to be talked about way before chapter 9 but that’s a minor thing.


One of the things I especially liked about this book is that at the end of each chapter you are given a quick pop quiz on the chapters content, this for me at least provided a quick way of ensuring I had understood the chapter and if I hadn't to go back and re read it, so this was good.


As I mentioned earlier the book is based on learning using examples and less about theory. Personally I'm not a huge fan of this technique; the writer Gastón C. Hillar does try to provide examples that are practical however I find that by simply following these you don't really learn what is going on; you learn how threading roughly works and that it’s there but when you need to use it in a real life application or you need to work out why something isn't working as expected you are left without the knowledge to solve these issues.


I do realise that this book is for beginners and is meant to get developers to look into and start writing multi-threaded apps and not be a complete resource, but personally I would prefer a touch more theory. In particular locking is over looked, what setting a WinForms app to [MTAThread] really means (you can't use dialogues for example). This was probably left out to try and keep things simple for beginners but not discussing locking or exceptions could mean bad practices are picked up and carried into production code.


It is worth mentioning that his book solely focuses on WinForm apps, it doesn't look into WPF or WebForms, and this is both a blessing and a curse in my eyes. With that said WinForms is simple to learn and the examples really do cover everything you need to get them working so if you have never used WinForms don't be put off reading this book, by the end of it you will not only know more about multi-threading but also how to write simple WinForm apps.
Also the book says that you can use Visual Studio 2008 Standard edition to debug multi threaded apps, I found out that sadly this isn't the case. In order to have the threads debug window you need the Pro edition or above version of Visual Studio.


Overall I find the book alright, personally the presentation of the book, colour schemes, internal typography could do with an improvement, the headings look like they are in Impact which is wrong on so many levels, and the examples can seem slightly farfetched but the book does cover a lot. As someone new to multi-threading by the end of it I felt confident enough in what I had learnt to write a simple multi threaded WinForm app for work to perform some tests.


Scores

Presentation - 6 / 10 - Although it’s clear to read the bulk of the content, the cover and headings for me let it down.
Code Examples – 7/10 – The code examples are clearly written and cover all the detail you need I feel that they aren’t as real life as they could be which hinders taking what they are meant to show you and apply it to real life scenarios.
Quality of Content – 7/10 – Overall I felt the quality content was quite good, potentially a bit over the top in places about being a “multi threaded guru” but overall OK. One down fall was to say that Visual Studio Standard edition can be used to debug multi threaded apps when it can’t.
Overall - 6.5 / 10 In light of everything I'm not going to suggest this is a book that everyone should read / own unlike over books like the pragmatic programmer etc. However if you are looking at learning about multi-threading and want something to ease you into it then this is for you, it will cover the basics of everything you need to know and what to expect in the future.

Sunday, 15 February 2009

Parsing an XML Boolean

Today I came across a situation where I was taking a value from an XML file which is a boolean. Now being me I knew that someone would either use 1 or true to indicate this boolean value, I for example always use 1 and 0 but I know people that prefer the "proper" way of saying true or false, especially if you don't have an XSD handy.


The XML itself is fine however once I had loaded this XML file into my .Net application I needed to parse the value as a boolean. This is where I hit a roadblock. Bool.Parse will only parse "true" or "false" string values not "1" or "0".


A quick explore through various sources led me to find XmlConvert.ToBoolean(), which is part of System.XML. XmlConvert allows you to convert from XML Data Types to .Net Data Types and in the case of Boolean can convert 1 to true.


This saved me loads of time so I thought I'd post it up here for others to find and hopefully enjoy.

Monday, 21 July 2008

System.Web.Query.Dynamic.ParseException: Digit expected

Today I wrote a quick piece of code using Linq to Sql that would pull out some records from a table given a provided where clause
To make my life easy, I used a LinqDataSource within a web form and then databound a form view to it, this was only a quick prototype of an idea so I felt these were appropriate.


The where clause for my LinqDataSource was being assigned programatically and consisted of a GUID value from a user object I had knocked together. Upon compiling and running the code though I got an odd error: System.Web.Query.Dynamic.ParseException: Digit expected


First thing to check was that the value I was giving the where clause was actually an GUID value, debugging showed this fine, I next looked at putting a hard coded GUID where clause in to see if it was some weirdness caused by my user object, but this wasn't the case. I finally googled the error message, and found 1 meesly result which pointed to the MSDN forums.


Here someone posted that you can convert to various types and to try explicitly converting to a GUID value


   lds.Where = string.Format("user_id == Guid({0})", user_id);

This worked fine, and it made sense too, as when you declare where parameters on the linqdatasource control you normally define its type, as I wasn't doing this nor programtically it was type casting by itself.

Monday, 23 April 2007

Code Snippet - Extracting Meta Descriptions

On Saturday I spent some time working on my new website, which will one day be finished, and decided that it needed to extract a Meta Description from the Database for each page, to help provide search engines with suitable descriptions. Now the easiest way is to just have a field in your database and admin / cms system for this, however when you don't want a specific description from the database it would be useful for the page to instead pull 20 words from the body text. So i decided to write myself a small function that would strip out any HTML and return a specified number of words from a string input. I have included it below with a possible use, in this case Meta Description.


   public string extractWords(string input, int wordNum)
   {
       string output = "";
       int i;
       int maxi;
       input = Regex.Replace(input, @"<[^>]*>", string.Empty);
       Array words = input.Split(new char[] {' '});
       if (words.Length < maxi =" words.Length;" maxi =" wordNum;" i =" 0;" output="" return="">
Example
       if (pageContent[0]["metadescription"].ToString() != ""){
           stringDescription = pageContent[0]["metadescription"].ToString();
       }
       else{
           stringDescription = extractWords(pageContent[0]["body"].ToString(), 20);
       }

Sunday, 3 December 2006

Four Geeks, a road trip and a conference

Well here I am writing my first post on my new blog. With any luck this new one will be kept upto date and be of use to the world. This weekend the Developer Developer Developer community was holding its fourth conference at Microsoft UK in Reading. 4 of us at New Mind went down on Friday night to be all ready for the conference on Saturday. After a grueling day in work the prospect of a long journey was not welcoming however everyone was in good spirit and after a hearty meal we set off. Now this is where the fun begins :D I brought the works tablet with me and Thom had his new SPV (which Derek was very excited about), a crazy idea of networking these two devices, bridging the SPV's odem to try to get on the net as well trying to access the SPV's built in web server suddenly semmed very appealing as we joined onto the M6. Now sadly after a good hour of faffing with the devices we could only get the wifi network up and access file shares and the tablets web server, tinkering with the SPV's webserver ended up being a no no :( There's always next time. The DDD4 conference was very good, it was my first time at Microsoft and I was very impressed, looks like a nice environment to work in. The hospitality provided by Microsoft was also very good, lots of refreshments and plenty to eat. I attended four sessions and listened to the lunch time grok talkros. Each session trigger some thought proccesses mainly ideas but beneficial none the less. The main thoughts from the sessions were: what an impact using string builder has on .Net performance, i knew it was better but had not seen examples. Ruby on rails is magic but probably not that exciting once you have seen the magic once. The main thing i like about rails is the Database migration stuff, that looked very good and something we could do with in the office. Sarah Blow's session on Web 2.0 although not bringing anything new did highlight how new tech should be used more, having a wiki, blog, podcasts etc should all be brought together and used together rather than a bit here and a bit there. Finally the javascript session clarified objects and how you can bodge namespaces. ! The groktalks were short bursts of interesting tidbits, the MCML stuff looked interesting, the vista speech recognition was very cool and although Thoms was unprepared did highlight a new avenue of web api i hadnt thought about. How jammy was he with winning the MSDN subscription! Overall a good weekend and am looking forward to attending barcamp and the next DDD. Hopefully tomorrow ill finish my template for this blog so it doesnt look so stadard and this week i will post about my recent and current developments with using Ajax in .Net and in more detail in PHP using SAJAX all good fun i can assure you :D