:::: MENU ::::

Wednesday, February 8, 2012

This post will demonstrate how to do rock-solid phone number validation using the .NET port of Google'slibphonenumber. When validating phone numbers you tend to end up either frustrating users with strict input requirements or with complicated regexes to cover all the interesting ways that users input phone numbers. If you have to also check international numbers (as we do at AppHarbor) the task becomes almost impossible.

Enter libphonenumber, a library from Google containing years of accumulated wisdom on how to parse phone numbers from all over the world. Patrick Mézard has created a .NET port of the Java version and there is even a NuGet package.

This makes using libphonenumber for validation as easy as installing the NuGet package and wrapping it in aDataAnnotation attribute like the one below (or just use the library straight up). The Attribute below will parse US numbers with and without country code while international numbers require a country code. Example of use:

 using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using MyNamespace.DataAnnotations;

public class Address
{
   
[DisplayName("Phone number")]
   
[Editable(allowEdit: true)]
   
[PhoneNumberAttribute]
   
[Required]
   
public virtual string PhoneNumber
   
{
       
get;
       
set;
   
}
}

Attribute:

 using System.ComponentModel.DataAnnotations;
using PhoneNumbers;

namespace MyNamespace.DataAnnotations
{
   
public class PhoneNumberAttribute : ValidationAttribute
   
{
       
public override bool IsValid(object value)
       
{
           
var valueString = value as string;
           
if (string.IsNullOrEmpty(valueString))
           
{
               
return true;
           
}

           
var util = PhoneNumberUtil.GetInstance();
           
try
           
{
               
var number = util.Parse(valueString, "US");
               
return util.IsValidNumber(number);
           
}
           
catch (NumberParseException)
           
{
               
return false;
           
}
       
}
   
}
}

Unit tests for attribute:

 using MyNamespace.DataAnnotations;
using Xunit;
using Xunit.Extensions;

namespace MyNamespace.UnitTest.DataAnnotations
{
   
public class PhoneNumberAttributeTest
   
{
       
private readonly PhoneNumberAttribute _subjectUnderTest;

       
public PhoneNumberAttributeTest()
       
{
            _subjectUnderTest
= new PhoneNumberAttribute();
       
}

       
[Fact]
       
public void GivenNull_WhenValidate_ThenIsValid()
       
{
           
Assert.True(_subjectUnderTest.IsValid(null));
       
}

       
[Fact]
       
public void GivenEmptyString_WhenValidate_ThenIsValid()
       
{
           
Assert.True(_subjectUnderTest.IsValid(string.Empty));
       
}

       
[InlineData("+4527122799")]
       
[InlineData("6503181051")]
       
[InlineData("+16503181051")]
       
[InlineData("1-650-318-1051")]
       
[InlineData("+1-650-318-1051")]
       
[InlineData("+1650-318-1051")]
       
[Theory]
       
public void GivenValidPhoneNumber_WhenValidate_ThenIsValid(string phoneNumberString)
       
{
           
Assert.True(_subjectUnderTest.IsValid(phoneNumberString));
       
}

       
[InlineData("123")]
       
[InlineData("foo")]
       
[Theory]
       
public void GivenInValidPhoneNumber_WhenValidate_ThenIsNotValid(string phoneNumberString)
       
{
           
Assert.False(_subjectUnderTest.IsValid(phoneNumberString));
       
}
   
}
}
 More 

Thursday, November 10, 2011

As programmer's we know that if we create a temporary file during the running of our application we need to make sure it is removed when the application or process is complete. We do this, but why can't Microsoft do it? Visual Studio leaves tons of temporary files all over your hard drive. This is why, over time, your computer loses hard disk space. This blog post will show you some of the most common places where these files are left and which ones you can safely delete.

.NET Left Overs

Visual Studio is a great development environment for creating applications quickly. However, it will leave a lot of miscellaneous files all over your hard drive. There are a few locations on your hard drive that you should be checking to see if there are left-over folders or files that you can delete. I have attempted to gather as much data as I can about the various versions of .NET and operating systems. Of course, your mileage may vary on the folders and files I list here. In fact, this problem is so prevalent that PDSA has created a Computer Cleaner specifically for the Visual Studio developer.  Instructions for downloading our PDSA Developer Utilities (of which Computer Cleaner is one) are at the end of this blog entry.

Each version of Visual Studio will create "temporary" files in different folders. The problem is that the files created are not always "temporary". Most of the time these files do not get cleaned up like they should. Let's look at some of the folders that you should periodically review and delete files within these folders.

Temporary ASP.NET Files

As you create and run ASP.NET applications from Visual Studio temporary files are placed into the <sysdrive>:\Windows\Microsoft.NET\Framework[64]\<vernum>\Temporary ASP.NET Files folder. The folders and files under this folder can be removed with no harm to your development computer. Do not remove the "Temporary ASP.NET Files" folder itself, just the folders underneath this folder. If you use IIS for ASP.NET development, you may need to run the iisreset.exe utility from the command prompt prior to deleting any files/folder under this folder. IIS will sometimes keep files in use in this folder and iisreset will release the locks so the files/folders can be deleted.

Website Cache

This folder is similar to the ASP.NET Temporary Files folder in that it contains files from ASP.NET applications run from Visual Studio. This folder is located in each users local settings folder. The location will be a little different on each operating system. For example on Windows Vista/Windows 7, the folder is located at <sysdrive>:\Users\<UserName>\AppData\Local\Microsoft\WebsiteCache. If you are running Windows XP this folder is located at <sysdrive>:\ Documents and Settings\<UserName>\Local Settings\Application Data\Microsoft\WebsiteCache. Check these locations periodically and delete all files and folders under this directory.

Visual Studio Backup

This backup folder is used by Visual Studio to store temporary files while you develop in Visual Studio. This folder never gets cleaned out, so you should periodically delete all files and folders under this directory. On Windows XP, this folder is located at <sysdrive>:\Documents and Settings\<UserName>\My Documents\Visual Studio 200[5|8]\Backup Files. On Windows Vista/Windows 7 this folder is located at <sysdrive>:\Users\<UserName>\Documents\Visual Studio 200[5|8]\.

Assembly Cache

No, this is not the global assembly cache (GAC). It appears that this cache is only created when doing WPF or Silverlight development with Visual Studio 2008 or Visual Studio 2010. This folder is located in <sysdrive>:\ Users\<UserName>\AppData\Local\assembly\dl3 on Windows Vista/Windows 7. On Windows XP this folder is located at <sysdrive>:\ Documents and Settings\<UserName>\Local Settings\Application Data\assembly. If you have not done any WPF or Silverlight development, you may not find this particular folder on your machine.

Project Assemblies

This is yet another folder where Visual Studio stores temporary files. You will find a folder for each project you have opened and worked on. This folder is located at <sysdrive>:\Documents and Settings\<UserName>Local Settings\Application Data\Microsoft\Visual Studio\[8|9].0\ProjectAssemblies on Windows XP. On Microsoft Vista/Windows 7 you will find this folder at <sysdrive>:\Users\<UserName>\AppData\Local\Microsoft\Visual Studio\[8|9].0\ProjectAssemblies.

Remember not all of these folders will appear on your particular machine. Which ones do show up will depend on what version of Visual Studio you are using, whether or not you are doing desktop or web development, and the operating system you are using.

Summary

Taking the time to periodically clean up after Visual Studio will aid in keeping your computer running quickly and increase the space on your hard drive. Another place to make sure you are cleaning up is your TEMP folder. Check your OS settings for the location of your particular TEMP folder and be sure to delete any files in here that are not in use. I routinely clean up the files and folders described in this blog post and I find that I actually eliminate errors in Visual Studio and I increase my hard disk space


more

Thursday, April 28, 2011

You can create an Automatic Logout user control by doing the following.

1. Create an automatic logout user control.
2. Add 1 RadAjaxPanel, 2 RadAjaxTimers (within the Panel), and 1 RadWindowManager.  Your ASPX will look something like this...

1

<radA:RadAjaxPanel ID="RadAjaxPanel1" runat="server" Height="1px" Width="1px">  

2

      <radA:RadAjaxTimer ID="RadAjaxTimer1" runat="server" AutoStart="False" /> 

3

      <radA:RadAjaxTimer ID="RadAjaxTimer2" runat="server" AutoStart="False" /> 

4

</radA:RadAjaxPanel> 

5

<radW:RadWindowManager ID="TimeoutWarningPopup" runat="server">  

6

</radW:RadWindowManager> 


3. Create a timeout message ASPX page.  This page will display 10 seconds before the user is logged out.  Mine says, "You will be logged out in 10 seconds."
4. In the user control code behind add the following code...

Imports Telerik.WebControls  

 

Partial Class includes_uc_telerik_ucAjaxTimer  

    Inherits System.Web.UI.UserControl

#Region "-- Members --"  

    Private m_blnTickEvent As Boolean = False

#End Region  

 

#Region "-- Properties --" 

    Public Property TickEvent() As Boolean 

        Get 

            Return m_blnTickEvent  

        End Get 

        Set(ByVal Value As Boolean)  

            m_blnTickEvent = Value  

        End Set 

    End Property

#End Region  

 

    Protected Sub RadAjaxTimer1_Tick(ByVal sender As ObjectByVal e As Telerik.WebControls.TickEventArgs) Handles RadAjaxTimer1.Tick  

        RadAjaxPanel1.ResponseScripts.Add("radopen'../../web/telerik/ajax_timer_msg.aspx','RadWindow1');")  

        RadAjaxTimer1.Stop()  

        Me.TickEvent = True 

    End Sub 

 

    Protected Sub RadAjaxTimer2_Tick(ByVal sender As ObjectByVal e As Telerik.WebControls.TickEventArgs) Handles RadAjaxTimer2.Tick  

        Response.Redirect("../../web/security/login.aspx")  

    End Sub 

 

    Protected Sub Page_PreRender(ByVal sender As ObjectByVal e As System.EventArgs) Handles Me.PreRender  

        If Me.TickEvent = False Then 

           RadAjaxTimer1.Interval = 3600000 '1 hour  

           RadAjaxTimer1.Start()  

 

           RadAjaxTimer2.Interval = 3600000 + 12000 '1 hour + 12 seconds  

           RadAjaxTimer2.Start()  

        End If 

    End Sub 

      

End Class 

 


5. Place the user control inside a master page or any pages that needs a logout timer.

Okay...  Let's break this down.

When the master page loads the user control Page_PreRender event will fire during the order of operations.  The Page_PreRender will start both timers only if the TickEvent property is False (default).  The property is needed becuase the Page_PreRender will fire after the RadAjaxTimer1_Tick is fired - we don't want to restart the timer on this event.

After Timer1 interval is reached the RadAjaxTimer1_Tick event is fired.  This event opens the message window stating you will be logged out, and sets the TickEvent property (see above for the reason why).  

If the user does nothing...  RadAjaxTimer2_Tick event fires and the user is sent to the login screen.

If the user causes a postback (clicks a link, button, etc.) the timers start again and keep the user logged in.

I have set my SessionTimeout to 61 minutes.  The session also resets when the user causes a postback so I think I'm safe in both cases.

So...  If a user walk away from the machine for an hour or has an extended period of inactivity...  They get logged out.

I hope this helps someone that might need the same functionality.

Wednesday, April 27, 2011

A lot of people keep asking about a good list of .net libraries. Hence, we are building this list to save your time and to spread the knowledge.

Some of these libraries will definitely help us developing better solutions. We will do our best to keep updating this list, hope you find this list useful, here we go.

Ajax

  • Ajax Control Toolkit - Microsoft
  • AJAXNet Pro
  • ASP.NET MVC Project Awesome - a rich set of helpers (controls) that you can use to build highly responsive and interactive Ajax-enabled Web applications. These helpers include Autocomplete, AjaxDropdown, Lookup, Confirm Dialog, Popup Form and Pager. Thanks Omu (April 20, 2011)

Build Tools

  • Prebuild - Generate project files for all VS version, including major IDE's and tools like SharpDevelop, MonoDevelop, NAnt and Autotools
  • Genuilder - Precompiler which lets you transform your source code during the build. Thanks Harry McIntyre (April 13, 2011)

Charting/Graphics

Collections/Generics

  • PowerCollections - is a library that provides generic collection classes that are not available in the .NET framework. Some of the collections included are the Deque, MultiDictionary, Bag, OrderedBag, OrderedDictionary, Set, OrderedSet, and OrderedMultiDictionary. Thanks Adam Ralph (April 20, 2011)

Compression

Controls

  • Krypton - Free winform controls. Link fixed (April 14, 2011)
  • Source Grid - A Grid control
  • DevExpress - Over 60 Free Controls from DevExpress. Thanks Florian Standhartinger (April 20, 2011)
  • ObjectListView - is a C# wrapper around a .NET ListView. It makes the ListView much easier to use and provides some neat extra functionality. Thanks Florian Standhartinger (April 20, 2011)

Data Mapper

Dependency Injection/Inversion of Control

Design by Contract

IDE

  • SharpDevelop - is a free IDE for C#, VB.NET and Boo projects. Thanks Florian Standhartinger (April 20, 2011).

Logging

ORM

PDF Creators/Generators

Automated Web Testing

Misc Testing/Qualitysupport/Behavoir Driven Development (BDD)

URL Rewriting

MS Word/Excel Documents Manipulation

  • DocX to create, read, manipulate formatted word documents. Easy syntax, working nicely, actively developed. No Microsoft Office necessary.
  • Excel XML Writer allows creation of .XLS (Excel) files. No Microsoft Office necessary. Been a while since it has been updated. It also provides code generator to create code from already created XLS file (saved as xml). Haven't tested this but looks very promising. Too bad author is long time gone.
  • Excel Reader allows creation/reading of .XLS (Excel) files. No Microsoft Office necessary. Been a while since it has been updated.
  • Excel Package allows creation/reading of .XLSX (Excel 2007) files. No Microsoft Office necessary. Author is gone so it's out of date.
  • EPPlus is based on Excel Package and allows creation/reading of .XLSX (Excel 2007). It is actually the most advanced even comparing to NPOI.
  • NPOI is the .NET version of POI Java project at http://poi.apache.org/. POI is an open source project which can help you read/write xls, doc, ppt files.
  • sharp2word - a Word 2003 XML Documents Generator from C# code without any components or libraries. Thanks dublicator (April 20, 2011)
  • ClosedXML - an actively developed library for generating OpenXML Excel files. Thanks Joseph Robichaud (April 26, 2011)

Serialization

  • sharpserializer - xml/binary serializer for wpf, asp.net and silverlight
  • Protobuf.NET - fastest serialization port protobuf format into .NET platform. Thanks slava pocheptsov (April 26, 2011)

Silverlight

Social Media

  • LinqToTwitter - Linq-based wrapper for all Twitter API functionality in C#
  • Facebook C# SDK - A toolkit for creating facebook applications / integrating websites with Facebook using the new Graph API or the old rest API.

Package managers for external libraries

  • NuGet (formerly known as NuPack) - Microsoft (developer-focused package management system for the .NET platform intent on simplifying the process of incorporating third party libraries into a .NET application during development)
  • OpenWrap - Sebastien Lambla - Open Source Dependency Manager for .net applications

Unit Testing/Mocking

Validation

Threading

  • Smart Thread Pool - Thread Pool management library
  • Retlang - a high performance C# threading library. Thanks MarcBot (April 13, 2011)
  • bbv.Common - an open source library of software components that makes building multi-threaded, event-based and loosely coupled systems easy. Thanks Urs Enzler (April 14, 2011)
  • PowerThreading - a llibrary (DLL) containing many classes to help with threading and asynchronous programming. Thanks Adam Ralph (April 20, 2011)

Unclassified

  • CSLA Framework - Business Objects Framework
  • AForge.net - AI, computer vision, genetic algorithms, machine learning
  • Prism - Composit UI application block for WPF, Silverlight and WP7 - Microsoft patterns & practices
  • Enterprise Library 5.0 - Logging, Exception Management, Caching, Cryptography, Data Access, Validation, Security, Policy Injection - Microsoft patterns & practices
  • File helpers library
  • C5 Collections - Collections for .NET
  • Quartz.NET - Enterprise Job Scheduler for .NET Platform
  • MiscUtil - Utilities by Jon Skeet
  • Noda Time - DateTime replacement (idomatic port of Joda Time from Java)
  • Lucene.net - Text indexing and searching
  • Json.NET - Linq over JSON
  • Flee - expression evaluator
  • PostSharp - AOP
  • IKVM - brings the extensive world of Java libraries to .NET.
  • C# Webserver - Embeddable webserver
  • Long Path - Microsoft
  • .NET Engines for the GOLD Parsing System
  • NCQRS - library for event-driven architectures (CQRS).
  • Reactive Extensions for .NET - a library for composing asynchronous and event-based programs using observable collections. Thanks steve (April 14, 2011)
  • Mono.GameMath - a project to develop a highly-performant math library for games, based on XNA APIs. Thanks Alex Rønne Petersen (April 14, 2011)
  • SLSharp - a runtime IL-to-GLSL translation engine, allowing people to write GLSL shaders as C# code. Thanks Alex Rønne Petersen (April 14, 2011)
  • InfusionSoftDotNet - a dll to ease the pain for .Net developers to access the InfusionSoft API. Thanks Michael Gibbs (April 20, 2011)
  • re-mix - provides mixins for C# and Visual Basic .NET. Thanks Stefan Papp (April 20, 2011)
  • Mono.Cecil - a library written by Jb Evain to generate and inspect programs and libraries in the ECMA CIL format. It has full support for generics, and support some debugging symbol format. Thanks Florian Standhartinger (April 20, 2011)

more

Thursday, March 31, 2011

Under IIS on Windows 7 I was unable to access by WCF service, I was getting the below error.

 

The requested content appears to be script and will not be served by the static file handler.

 

You will need to run ServiceModelReg.exe -i from the "%windir%\Microsoft.NET\Framework\v3.0\Windows Communication Foundation" directory to register the script maps.

 

After this it all worked.