Wednesday, April 24, 2013

File Name and Directory Name Helper


Often times, I want to create folder or file names from some string but file and directory names need to be valid so I've created the following helper class to help me.

 public static class FilePathNameHelper
 {

  public static string GetValidPathName(string pathName, char goodCharReplacement)
  {
   return ReplaceBadWithGood(pathName, Path.GetInvalidPathChars(), goodCharReplacement); 
  }

  public static string GetValidFileName(string fileName, char goodCharReplacement)
  {
   return ReplaceBadWithGood(fileName, Path.GetInvalidFileNameChars(), goodCharReplacement);
  }

  private static string ReplaceBadWithGood(string subject, char[] badBoys, char good)
  {
   if (!string.IsNullOrWhiteSpace(subject)
    && subject.ToCharArray().Intersect(badBoys).Any())
   {
    subject = badBoys.Aggregate(subject, (current, bad) => current.Replace(bad, good));
   }
   return subject;
  }
 }
It's quite easy to use:
var goodFileName = FilePathNameHelper.GetValidFileName("some bad file name<>.txt",'-');

goodFileName should contain "some bad file name--.txt".

Saturday, October 6, 2012

Microsoft Web Matrix Rocks





It sounds like a commercial, doesn't it?  Well, it's not.  If you haven't gotten it, go get it.

I attended a Visual Studio 2012 training session at Head Spring's headquarter about a week ago and Jeffery Palermo (Author of MVC in Action) demoed features of Web Matrix 2.  I never had the need for it since I lived in Visual Studio, until recently when a good friend asked me to help her with a site purely build out of static html pages.  So I decided to give Web Matrix a try since I just learned about it.

It is awesome!


  • You can run a site from any folder
    • I got a copy of my friend's html site in a folder and committed a repo to track changes.  I was able to load the folder as a site in Web Matrix without doing any IIS configuration stuff.
  • When editing the pages, html, js, css, there is intellisence to help you and it makes page editing a breeze.
  • And it's absolutely free.
 There are many more features that you can explore once you get it.  Some of them are the ability to connect to a remote site and publish to it.  It allows you build PHP and node.js apps too.

But the above highlighted features are the that I'd use most frequently.

Thanks Microsoft!


Saturday, April 23, 2011

Validation: set maxlength of a text box using MVC validation

Given a view model as below:
public class EmployeeFormViewModel
{
[Required(ErrorMessage = "*")]
    [StringLength(20,ErrorMessage = "Max length 20 characters")]
    public string Name { getset; }
}
And when client validation and unobtrusive JavaScript are enabled in a MVC 3 app in web.config in the root directory:

  <appSettings>
    <add key="ClientValidationEnabled" value="true"/> 
    <add key="UnobtrusiveJavaScriptEnabled" value="true"/> 
  appSettings>



A view:

<h2>Employee Formh2>
@using (Html.BeginForm("Employee","SaveEmployeeForm","Home",FormMethod.Post)){
    @Html.TextBoxFor(model=>model.Name)
    <br />
    <input type="submit" value="Submit" />
}

renders into Html on the client side:



<form action="/SaveEmployeeForm/Home?Length=4" method="post">
 <input data-val="true" 
  data-val-length="Name must not be longer than 20 characters long" 
  data-val-length-max="20" 
  data-val-required="*" 
  id="Name" 
  name="Name" 
  type="text" 
  value="" />    
 <br />
    <input type="submit" value="Submit" />
form>


This works great: it shows the error message when the user types a name longer than 20 characters and leaves the text box.  But it still allows the user to type in more than 20 letters before the focus leaves the text box.
  
What if I want to keep the user from keying in 20 characters? 

Well, the maxlength attribute of the input tag is the answer.  When it is set to 20, the user is only allowed to type in 20 characters.  I really don't want to keep setting "maxlength" to every single text box that I create and more importantly I want validation attribute "StringLength" to control this value.  But the generated code does not set the "maxlength" attribute.  How do I set the value of maxlength attribute using the value of data-val-length-max attribute?
A little JQuery sweetness does the trick:
<script language="javascript" type="text/javascript">
    $(document).ready
    (
        function () {
            $('input[data-val-length-max]').each
            (
                function (index) {
                    $(this).attr('maxlength', $(this).attr('data-val-length-max'));
                })
        });
script>
What the code above says is that for every input tag with the attribute of "data-val-length-max", use the value of it to set the value of "maxlength" attribute.

Friday, April 22, 2011

Double Meaning or Entendre

Double Meaning or Double Entendre can be very funny when used in jokes.  Read the following jokes from this site:
Old Timer 1 : You know what I miss?
Old Timer 2 : And what might that be?
Old Timer 1 : Really small targets that are miles away.




Teacher 1 : You know what makes me mad?
Teacher 2 : What?
Teacher 1 : Changing the 'e' to an 'a' and adding a 'd'.



Ha-ha-ha, he-he-he, wasn't that funny!


In the first example above, "miss" could mean thinking of something sentimental wishing you still have it or could mean when I shoot a target I don't hit it.  Same thing in the second one where "me" could me myself or the word "me".  This is all funny and silly until you start coding that way.


During a recent design session, a team member suggested reusing existing properties for different purposes.  This reminded me of a story I heard some years back, during another design session,  a team discovered  that they needed a new field in the database for their application.  The app had been released and it was in production at a major client's site.  The client operated on 24/7 schedule, taking down the database would mean longer downtime therefore losing money.  So the team decided to use an existing field but use it differently depending the format of the value in the field.  It sounded like a good solution, all they had to do is re-deploy the application which took less then 5 minutes.  The client gets new features without much of downtime.  Great news, right?  

To the client, yes.  How about for the developers and the long term maintenance of the application?  Subsequently, the property of the class that the field was mapped to had to be handled differently. Wherever the property was used, a helper extension method was used to parse the value so the new value is can be put to work while making sure not to break the old code.  Suddenly, we created a lot of work for ourselves which meant higher cost to develop the feature.  More importantly, it had a long term implication for maintenance.  As we know people change jobs, developers come and go, now there was additional cost for maintenance because we had to document what the field really meant so we could educate new developers to use it properly.  In the end, it really wasn't worth saving the client's downtime of maybe 10 hours the most.

The moral of the story: do not give double meaning to a property, field.  Do it properly using S.O.L.I.D principles. 

About Cullen

My photo
Christian, Father, Software Developer/Architect who enjoys technology and using it to make people's lives easier!

Followers