• Web Service Factory for WCF (Part 2) - Creating CRUD Sprocs and Repositories

     

    Last time we created our business entities using the database, I probably should have created my stored procedures first, but I didn’t. We’re going to do that now.

     

    Go ahead an run the “Create CRUD stored procedures” recipe.

     

    Select everything (some stuff has incompatible types, I’m sure we’ll get to deal with those later).

    image001.jpg

     

    It gives you a chance to change the names and select/deselect any methods. I’m going to go with defaults and do everything.

    image002.jpg

    I hit Next.

     

    I get this window to name the stored procedures file.

    image003.jpg

     

    So now I’m going to try this out in Management Studio.

    image004.jpg

    It seemed to run, now to check programmability to see…

     

    WARNING! You have to add a line to the top of the sql to USE AdventureWorks, or  you’ll be adding all of thosed stored procedures to master, and have to remove them manually, NOT FUN. (I learned the hard way)

    image005.jpg

    Ok, they’re all in there now…

     

    Next recipe is “Create data repositories from business entities”

    image006.jpg

    Target the DataAccess project.

    Choose our AdventureWorks connection.

     

    Let’s do HR:

    image007.jpg

    This should give us enough to play with.

    image008.jpg

    You might want to go into each operation and peek at what’s going on here, basically every one of these methods maps to a stored procedure then every single parameter must map to a business entity property.

     

    HIT FINISH.

     

     

    It generates the repository objects. Explaining what the generics in this do is a topic for another blog(or series)

     

    Full story

    Comments (0)

  • Web Service Software Factory for WCF (Part 1)

    Before I can start doing some cool wpf smart client stuff, I’m going to need a service to give me data objects. I’m going to use WCF since it’s pretty flexible and it’s ‘hot’.

     

    image002.jpg

    I’m still crappy at naming these things… but I usually do <Company>.<Domain>.<Application>.<Component> with each solution being an application and component being an assembly (or subfolder within an assembly)

     

    Click Finish on the next window you see to accept the names… it should generate your projects and look like this:

    image004.jpg

     

    • BusinessEntitites is your Data objects, like employee, person, sale, etc
    • BusinessLogic is any operations you’re doing on the objects prior/after you get or send them to/from the data access layer.(like incrementing/decrementing vacation hours on an employee while you’re creating their paycheck)
    • DataAccess is a collection of repositories that can get your objects (we’ll look at this first)
    • We’ll worry about the projects in the ServiceInterface folder at a later time.

     

    I think in a normal development situation I would create my business logic first (or at least know which objects I’ll need in my business logic, so I can focus on just making those), BUT since I’m using the toolkit, we’re going to dump the whole AdventureWorks database into business entities automatically!

     

    First, let’s create a connection (they create it in a test host project, so all your future deployments will need the same named connection string in the app.config)

     

    In the automation window, choose Data access

    image006.jpg

    Then run the  add database connection recipe:

    image008.jpg

    They usually grey out any project you can’t use, we’re going to use the test project as our target for this database connection:

     

    image010.jpg

    Name it AdventureWorks and hit the “…” to create a connection string:

    Choose SqlServer .net provider and hit ok then go find your AdventureWorks database. NOTE: If your using sqlexpress you MUST use localhost as the servername. (orlocalhost\sqlexpress if you installed it on a separate instance)

     

    image012.jpg

     

    The guidance shows our history and it gives us recommended next steps:

    image014.jpg

    We’re going to create entities from database, and do them all to get that knocked out, then we never have to come back to it! J (unless our database changes, but let’s hope you’re far enough in your project to know your database won’t change, or it’s a vendor database that you’re adding functionality to via services)

     

    OK NEXT: click on “Create  Business entities from database”

    Target the business entities project and accept, then you get this:

    image016.jpg

    Choose your adventureworks connection and hit NEXT… now wait a long time(sometimes it appears to be locked up at this point)

     

    Let’s do them all (hell why not, right?)

    image018.jpg

    NOTE: after you select all, it pauses for a bit before the “next” button enables.

    Hit next.

    image020.jpg

    You can now rename them, I won’t because I don’t even know what they are!

    Hit Finish

     

    Now it goes and generates the entities. I ranbuild to see if it worked. Mine blew up with these errors:

    Error    1          The type 'AdventureWorks.Services.Internal.BusinessEntities.SalesvSalesPersonSalesByFiscalYears' already contains a definition for '_Field'c:\projects\AdventureWorks.Services.Internal\Source\Business Logic\AdventureWorks.Services.Internal.BusinessEntities\SalesvSalesPersonSalesByFiscalYears.cs      64        42            AdventureWorks.Services.Internal.BusinessEntities

     

    Looking at the database, it appears the 3 properties named _Field are 2001,2002,2003 respectively, You can't have variables with names starting with numbers... so that's why it bombed. 

    The fixed constructor:

            public SalesvSalesPersonSalesByFiscalYears(Nullable<System.Int32> salesPersonID, System.String fullName, System.String title, System.String salesTerritory, Nullable<System.Decimal> _y2002, Nullable<System.Decimal> _y2003, Nullable<System.Decimal> _y2004)

            {

                this.salesPersonIDField = salesPersonID;

                this.fullNameField = fullName;

                this.titleField = title;

                this.salesTerritoryField = salesTerritory;

                this.y2002_Field = _y2002;

                this.y2003_Field = _y2003;

                this.y2004_Field = _y2004;

            }

     

    The Fixed Properties:

            private Nullable<System.Decimal> y2002_Field;

     

            public Nullable<System.Decimal> Y2002

            {

                get { returnthis.y2002_Field; }

                set { this.y2002_Field = value; }

            }

     

            private Nullable<System.Decimal> y2003_Field;

     

            public Nullable<System.Decimal> Y2003

            {

                get { returnthis.y2003_Field; }

                set { this.y2003_Field = value; }

            }

     

            private Nullable<System.Decimal> y2004_Field;

     

            public Nullable<System.Decimal> Y2004

            {

                get { returnthis.y2004_Field; }

                set { this.y2004_Field = value; }

            }

     

    Ok, now it builds. I think that’s enough torture for one day. Next time we’ll figure out what we want to work with first, make stored procedures and data access CRUD commands.

    Full story

    Comments (0)

  • My Dev Environment

    I figure people might not be able to do stuff i do in my blog because they don't have their environment setup like mine.

    Let's first talk about what i needed.(this is all free except vs btw, if you got no money for VS you can use visual c# express but the automation extensions and factories won't work as far as i know)

    1. Visual Studio 2005 Pro (standard will do anything i do except windows services and deployment packages with windows installer)
    2. Sql express 2005 advanced and the Toolkit http://msdn.microsoft.com/vstudio/express/sql/download/
    3. Windows Vista and .Net 3.0 SDK http://www.microsoft.com/downloads/details.aspx?familyid=C2B1E300-F358-4523-B479-F53D234CDCCF&displaylang=en
    4. Visual Studio 2005 extensions for .NET Framework 3.0 (WCF & WPF), November 2006 CTP http://www.microsoft.com/downloads/details.aspx?FamilyID=f54f5537-cc86-4bf5-ae44-f5a1e805680d&DisplayLang=en
    5. Guidance Automation Extensions (GAX) And Guidance Automation Tookit (GAT) http://msdn2.microsoft.com/en-us/teamsystem/aa718949.aspx
    6. Enterprise library (i'm on 2.0 but will be trying 3.0) http://msdn2.microsoft.com/en-us/library/aa480453.aspx
    7. Webservice factory ( use the WCF c# one , december 2006)  http://msdn2.microsoft.com/en-us/library/aa480534.aspx

    That should give you a sane development environment to do the things I do in the future on this blog. Plus now you can reference this blog now anytime someone asks you where to get all the stuff above.

    You might want workflow, i'm going to explore it soon i just haven't yet.

    Full story

    Comments (0)

  • Clr Stored Procedures in Sql 2005

    Using Clr Stored Procedures in Sql Server 2005

    For this example you'll need adventure works database installed on your sql server instance AND you'll want a connection in your server pane of Visual Studio.(you can get adventure works database on msdn here: http://www.microsoft.com/downloads/details.aspx?familyid=e719ecf7-9f46-4312-af89-6ad8702e4e6e&displaylang=en )

    First problem I ran into was that my server was not configured to allow Clr procedures.

    This link (http://geekswithblogs.net/rasyadi/archive/2005/11/18/60459.aspx

    ) showed me how to enable it.

    exec sp_configure 'clr enabled', 1

    However, i got this error.

     ‘Ad hoc updates to system catalogs are not allowed.’

    Researching that I found this post: http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=89594&SiteID=1

     

    And used Zoulasc’s fix:

    sp_configure 'allow updates', 1

    reconfigure with override

    Then i ran the sp_configure 'clr enabled',1 query and ran reconfigure again.

    Now that I’m able to use clr on my sql server I started a new project:

    Create a new sql project under C# projects.

    image002.jpg

    Bind it to the Adventureworks database.

    Now, just add a class to the project, I prefer to keep my classes separated out by what they’re for. I’m going to make one to work with the adventure works Product table.

    image004.jpg

     

    You’ll need these three using (or “import”) statements added to the defaults.

     

    using System.Data;

    using System.Data.SqlClient;

    using Microsoft.SqlServer.Server;

     

    Modify the class to be public (sql only accepts public classes for procedures, it won’t even deploy with procedures within internal/private classes)

     

    Ok, so now I have this:

        public class ProductRepository

        {

            [Microsoft.SqlServer.Server.SqlProcedure]

            public static void sp_GetAllProducts()

            {

     

            }

        }

     

    Now we can write our code to read all of the products:

    First, let’s create a sqlconnection:

     

    Most people would do this:

    SqlConnection connection = newSqlConnection("Context Connection=true");

     

    But my biggest pet-peave is when people don’t dispose of their connection or close it,(or the command or the reader) we can do this automagically with the using() statement. So here's the final look at the function.

            public static void sp_GetAllProducts()

            {

                using(SqlConnection connection =

    new SqlConnection("Context Connection=true"))

                using (SqlCommand command =

    new SqlCommand("SELECT * from Production.Product", connection))

                {

                    connection.Open();

     

                    using (

    SqlDataReader reader = command.ExecuteReader())

                    {

                        SqlPipe pipe = SqlContext.Pipe;

                        pipe.Send(reader);

                    }

                }

              }

    image006.jpg

    Parameters are as simple as putting params on the function itself, then within your code creating instances of SqlParameter... let's say we wanted to get products by an id number:

     

    [Microsoft.SqlServer.Server.SqlProcedure]

    publicstaticvoid sp_GetProductsById(int id)

    {

    using(SqlConnection connection = newSqlConnection("Context Connection=true"))

    using (SqlCommand command = newSqlCommand("SELECT * from Production.Product WHERE ProductID = @ProductID ", connection))

    {

    connection.Open();

    SqlParameter param = newSqlParameter("@ProductID", id);

    param.Direction = ParameterDirection.Input;

    param.DbType = DbType.Int32;

    command.Parameters.Add(param);

    using (SqlDataReader reader = command.ExecuteReader())

    {

    SqlPipe pipe = SqlContext.Pipe;

    pipe.Send(reader);

    }//Automatically closes and disposes the objects

    }

     

    image008.jpg

     

    Full story

    Comments (0)

  • A little about me...

    I did a lot of C++ and Java in school back in 1997-1999, then got a band and quit school.

    Fast forward to spring 2006, I was working tech support at a major restaurant chain's  HQ and decided i need to make a change. Off of a suggestion from a couple of co-workers (thx Everett and Jim), i decided to pick up C# and re-hone my programming skills (which honestly i had kept up pretty well doing LPC on MudOS. )

    My thought was, make good with people at there and get into development. I studied the books hard (Eric gunnerson, Tom Miller, Graham Wihlidal, Karsten Thompsen, Ron Penton, MCTS Training kit for the 536..) Things were looking good but nothing was opening up, so i took a position as second level support when it was offered.

    Two weeks later one of the devs quit, and i was fishing pretty hard outside the company for a development job and had a few that i was to interview with soon so i asked to apply for the one at my work (even though i wasn't technically eligible my boss made an exception). I was disappointed to learn that they were only working with COM and VB 6 on Win2k and had no real plans to migrate towards .net development. I still wanted to stay with the company badly and did one of  my best interviews ever (or so i feel like).

    Unfortunately it wasn't meant to be, as they closed the position due to cutbacks. Luckily, one of my other interviews went really well and the project manager was totally into cutting edge technologies. He was doing ajax, asp.net 2.0, vs2005, sql2005, etc... so i said hell yea and got on board.

    That was october, and here i am... Since then he's pushed me really hard to learn Webservices, then WCF, and now WPF (and next is wss 3.0).

    As far as finished projects so far, i've written a WCF tcp service endpoint that is a data service for our temp agency (roughly 18 fox pro databases through OLE) I've written numerous SSRS reports tying into that service and a few reports that tie into sql databases directly (ones we don't have services for yet). I wrote a webservice that calls SSIS packages so we don't have to have ssis installed where the software is (saving on SQL licenses) and a few other small things here and there.

    The big project right now is automating our temp agency application process. Currently they take paper applications, they get  'filed' until they can be 'entered' into the database. This project is an XML browser application smart client (XBAP)(for ease of deployment to our offices). It will get it's lookup codes and other drop down info from FoxPro via the WCF service and will be writing to a holding tank database (SQL) and we're using SSIS(Sql Server Integration Services) to import people from it to VFP (FoxPRO). (because we aren't planning to have fox pro forever and most likely will do a slow roll out of whatever our next product is... )

    Full story

    Comments (0)