Over the holiday I began to dive into WCF (Windows Communication Foundation). A few months ago, I created a simple Zip Code Lookup service using ThinkTecture's WSCF (Web Service Contract First add-in). The Zip Code Lookup service is the perfect project to upgrade to WCF.
One of the operations I added to the Zip Code Lookup service is called 'GetStateCodes'. The GetStateCodes operation retrieves a list of State Codes (ex: 'FL', 'Jacksonville') see code below. BTW, I'm also using SubSonic for the DAL.
Ok, I need a unit test as well and this is where I used List.Find to return an instance of StateCode from List<StateCode>. Normally, I'd write a ForEach statement in a separate method to find an object in a collection. However, now with Generics things are much easier.
Here is another reference from Developer Fusion that demonstrates sorting and searching a generic list.
1 2 3 4 5 6 7 8 9 10 11 12 13 |
[TestMethod()] public void SearchByState() { ZipCodeService svc = new ZipCodeService(); ZipCodeSearchRequest request = new ZipCodeSearchRequest();
List<StateCode> states = svc.GetStateCodes(); request.State = states.Find(delegate(StateCode state) { return state.StateAbbr == "FL"; });
List<ZipCodeInfo> actual = svc.ZipCodeSearch(request);
Assert.IsTrue(actual.Count > 0); } |
Operation Implementation Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
public List<StateCode> GetStateCodes() { // Execute search and load results Query qry = new Query(ZipCode.Schema); qry.SelectList = ZipCode.Columns.StateCode + ", " + ZipCode.Columns.StateName; qry.OrderBy = OrderBy.Asc(ZipCode.Columns.StateCode);
List<StateCode> stateInfo = null; using (IDataReader dr = qry.ExecuteReader()) { // Translate collection to WCF datacontract stateInfo = translate.StateInfo(dr); }
// Return results to happy consumer return stateInfo; } |
DataContract for StateCode:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
[DataContract(Namespace = Namespaces.ZipCodeNamespace)] public class StateCode { private string stateAbbrField; private string stateNameField;
public StateCode() {}
public StateCode(string stateAbbr, string stateName) { StateAbbr = stateAbbr; StateName = stateName; }
[DataMember(Order = 0)] public String StateAbbr { get { return stateAbbrField; } set { stateAbbrField = value; } }
[DataMember(Order = 1)] public string StateName { get { return stateNameField; } set { stateNameField = value; } } } |