Subscribe: Paul Welter's Weblog
http://weblogs.asp.net/pwelter34/rss.aspx
Added By: Feedage Forager Feedage Grade B rated
Language: English
Tags:
community tasks  community  data  file  message  msbuild community  msbuild  new  package  project  property  queue  tasks 
Rate this Feed
Rate this feedRate this feedRate this feedRate this feedRate this feed
Rate this feed 1 starRate this feed 2 starRate this feed 3 starRate this feed 4 starRate this feed 5 star

Comments (0)

Feed Details and Statistics Feed Statistics
Preview: Paul Welter's Weblog

Paul Welter's Weblog



Coding Conundrums of a .NET Developer



 



MongoDB.Messaging - MongoDB Messaging Library

Tue, 07 Jun 2016 13:33:05 GMT

Overview The MongoDB Messaging library is a lightweight queue pub/sub processing library based on MongoDB data store. Features Easy to use Fluent API Self creating and cleaning of Queues Configurable message expiration Generic data payload Trigger processing from oplog change monitoring Configurable auto retry on error Message processing timeout Scalable via subscriber worker count Supports distributed locks Download The MongoDB.Messaging library is available on nuget.org via package name MongoDB.Messaging. To install MongoDB.Messaging, run the following command in the Package Manager Console PM> Install-Package MongoDB.Messaging NuGet: https://nuget.org/packages/MongoDB.Messaging Source: http://github.com/loresoft/MongoDB.Messaging Concepts Queue A queue is equivalent to a MongoDB collection. The name of the queue will match the MongoDB collection name. Queue names must be alphanumeric, without spaces or symbols. It is a good practice to suffix the queue name with Queue. Message A message is the high level object that is a generic definition of a messages. The message contains processing level information. The message object is automatically created and updated by the Fluent API and should not be updated directly by the publisher or subscriber. Data Data is the message payload to be processed with the message. Use data to pass information you need to process the message. The data object must be serializable by MongoDB driver. It is a good practice to have one queue per data object being passed to limit confusion and to maintain simplicity when subscribing to the queue. Publish Publishing a message adds the message with the corresponding data to a queue for processing. Subscribe In order to process a message on a queue, an application needs to subscribe to a queue. There can be many subscribers to a queue to scale the load across processes. A subscriber can also set the worker count to scale the number of processing threads for that subscriber. The framework ensures that only one subscriber can process a messages. Queue Configuration The queue configuration is used to set default values on messages published to a queue. An example of using the fluent api to configure the sleep queue. MessageQueue.Default.Configure(c => c .Connection("MongoMessaging") .Queue(s => s .Name(SleepMessage.QueueName) .Priority(MessagePriority.Normal) .ResponseQueue("ReplyQueueName") .Retry(5) ) ); Properties Connection is the app.config connection string name used to connect to MongoDB. Name is the name of the queue to configure. Retry is the number of times the message should be retried on error. Set to zero, default, to not retry. Priority is the default priority to publish the message with. ResponseQueue is the name of the queue where responses should be sent. Publish Message To publish a message to a queue, use the fluent api. var message = await MessageQueue.Default.Publish(m => m .Queue(SleepMessage.QueueName) .Data(sleepMessage) .Correlation("321B4671-3B4C-4B97-8E81-D6A8CF22D4F0") .Description("User friendly description of the message") .Priority(MessagePriority.Normal) .Retry(1) ); Properties Required Queue is the name of the queue to publish to. Data is the object to pass in the message. Used to process the message by the subscriber. Optional Correlation is an identifier used to link messages together. Description is a user friendly description of the message. Overrides Retry is the number of times the message should be retried on error. Priority is the default priority to publish the message with. ResponseQueue is the name of the queue where responses should be sent. Notes When setting the Data property, the message Name will be set to the Type name of the data object. When setting the Data property and Description hasn't been set, the data object ToString() value will be set as the description. If the underlying storage collection doesn't exist, it will be created on first publish[...]



DataGenerator - Generate Intelligent and Realistic Test Data

Tue, 12 Apr 2016 22:00:00 GMT

Features Generate intelligent test data based on property type and name Automatic discovery of data sources Fully customizable property data sources Realistic data sources Weighted value selection Easy fluent API Download The DataGenerator library is available on nuget.org via package name DataGenerator. To install DataGenerator, run the following command in the Package Manager Console PM> Install-Package DataGenerator NuGet: https://nuget.org/packages/DataGenerator Source: http://github.com/loresoft/DataGenerator Configuration Full class property configuration Generator.Default.Configure(c => c .Entity(e => { e.Property(p => p.FirstName).DataSource(); e.Property(p => p.LastName).DataSource(); e.Property(p => p.Address1).DataSource(); e.Property(p => p.City).DataSource(); e.Property(p => p.State).DataSource(); e.Property(p => p.Zip).DataSource(); e.Property(p => p.Note).DataSource(); e.Property(p => p.Password).DataSource(); // array of values e.Property(p => p.Status).DataSource(new[] { Status.New, Status.Verified }); // don't generate e.Property(p => p.Budget).Ignore(); // static value e.Property(p => p.IsActive).Value(true); // delegate value e.Property(p => p.Created).Value(() => DateTime.Now); }) ); Example of configuration for generating child classes Generator.Default.Configure(c => c .Entity(e => { e.AutoMap(); // generate a User instance e.Property(p => p.User).Single(); // generate list of OrderLine items e.Property(p => p.Items).List(2); }) .Entity(e => { e.AutoMap(); e.Property(p => p.Quantity).IntegerSource(1, 10); }) ); There are extension methods to configure properties as well Generator.Default.Configure(c => c .Entity(e => { // random number between 1 and 10 e.Property(p => p.Quantity).IntegerSource(1, 10); // between 100 and 1,000 e.Property(p => p.UnitAmount).DecimalSource(100, 1000); }) ); Profiles DataGenerator support class profiles to make configuration easier. To create a profile, inherit from the MappingProfile base class. Sample Profile for the User class public class UserProfile : MappingProfile { public override void Configure() { Property(p => p.FirstName).DataSource(); Property(p => p.LastName).DataSource(); Property(p => p.Address1).DataSource(); Property(p => p.City).DataSource(); Property(p => p.State).DataSource(); Property(p => p.Zip).DataSource(); Property(p => p.Note).DataSource(); Property(p => p.Password).DataSource(); // array of values Property(p => p.Status).DataSource(new[] { Status.New, Status.Verified }); // don't generate Property(p => p.Budget).Ignore(); // static value Property(p => p.IsActive).Value(true); // delegate value Property(p => p.Created).Value(() => DateTime.UtcNow); } } Register a profile in the configuration Generator.Default.Configure(c => c .Profile() ); Generation Generate test data // generate a user var instance = Generator.Default.Single(); // generate 10 users var users = Generator.Default.List(10) You can override the configuration var instance = Generator.Default.Single<[...]



FluentRest - Lightweight fluent wrapper over HttpClient

Mon, 10 Aug 2015 12:00:00 GMT

Features Fluent request building Fluent form building Automatic deserialization of response Plugin different serialization Fake HTTP responses Download The FluentRest library is available on nuget.org via package name FluentRest. To install FluentRest, run the following command in the Package Manager Console PM> Install-Package FluentRest NuGet: https://nuget.org/packages/FluentRest Source: http://github.com/loresoft/FluentRest Fluent Request Create a form post request var client = new FluentClient(); client.BaseUri = new Uri("http://echo.jpillora.com/", UriKind.Absolute); var result = await client.PostAsync(b => b .AppendPath("Project") .AppendPath("123") .FormValue("Test", "Value") .FormValue("key", "value") .QueryString("page", 10) ); Custom authorization header var client = new FluentClient(); client.BaseUri = new Uri("https://api.github.com/", UriKind.Absolute); var result = await client.GetAsync(b => b .AppendPath("repos") .AppendPath("loresoft") .AppendPath("FluentRest") .Header(h => h.Authorization("token", "7ca...")) ); Fake Response FluentRest has the ability to fake an HTTP responses by using a custom HttpClientHandler. Faking the HTTP response allows creating unit tests without having to make the actual HTTP call. Fake Response Stores Fake HTTP responses can be stored in the following message stores. To create your own message store, implement IFakeMessageStore. MemoryMessageStore The memory message store allows composing a JSON response in the unit test. Register the responses on the start of the unit test. Register a fake response by URL. MemoryMessageStore.Current.Register(b => b .Url("https://api.github.com/repos/loresoft/FluentRest") .StatusCode(HttpStatusCode.OK) .ReasonPhrase("OK") .Content(c => c .Header("Content-Type", "application/json; charset=utf-8") .Data(responseObject) // object to be JSON serialized ) ); Use the fake response in a unit test var serializer = new JsonContentSerializer(); // use memory store by default var fakeHttp = new FakeMessageHandler(); var client = new FluentClient(serializer, fakeHttp); client.BaseUri = new Uri("https://api.github.com/", UriKind.Absolute); // make HTTP call var result = await client.GetAsync(b => b .AppendPath("repos") .AppendPath("loresoft") .AppendPath("FluentRest") .Header(h => h.Authorization("token", "7ca...")) ); FileMessageStore The file message store allows saving an HTTP call response on the first use. You can then use that saved response for all future unit test runs. Configure the FluentRest to capture response. var serializer = new JsonContentSerializer(); // use file store to load from disk var fakeStore = new FileMessageStore(); fakeStore.StorePath = @".\GitHub\Responses"; var fakeHttp = new FakeMessageHandler(fakeStore, FakeResponseMode.Capture); var client = new FluentClient(serializer, fakeHttp); client.BaseUri = new Uri("https://api.github.com/", UriKind.Absolute); var result = await client.GetAsync(b => b .AppendPath("repos") .AppendPath("loresoft") .AppendPath("FluentRest") .Header(h => h.Authorization("token", "7ca...")) ); Use captured response var serializer = new JsonContentSerializer(); // use file store to load from disk var fakeStore = new FileMessageStore(); fakeStore.StorePath = @".\GitHub\Responses"; var fakeHttp = new FakeMessageHandler(fakeStore, FakeResponseMode.Fake); var client = new FluentClient(serializer, fakeHttp); client.BaseUri = new Uri("https://api.github.com/", UriKind.Absolute); var result = await client.GetAsync(b => b .AppendPath("repos") .AppendPath("loresoft") .AppendPath("FluentRest") .Header(h => h.Authorization("token", "7ca...")) ); [...]



EstimatorX - Project Estimation Application

Thu, 26 Mar 2015 03:19:35 GMT

(image)

A simple project estimation application.
http://estimatorx.com

(image)

Features

Projects

A project contains all the details that make up an estimate. An estimate is broken down into Assumptions, Factors and Tasks. The estimate is padded with a contingency rate.

Assumptions

When making an estimate, there are assumptions the estimator makes to come up with the estimate. Document those assumptions to help raise the red flag in the future when an assumptions proves not to be true.

Factors

Factors are a type of task with hours associated with the complexity of that task. Factors allow the estimator to state hours based on a specific type of task, regardless of the project.

Tasks

Tasks are a specific item or feature of the project being estimated. A task is assigned a Factor. The estimator enters the number of tasks per complexity level.

Tasks are part of a Section. Sections are a way to group a set of common features. Tasks totals are also rolled up to the section level.

Reports

Project estimates can be displayed as a simple report. The estimator can create a public shared link to allow anonymous view access to the report. The report can also be downloaded as a PDF.

Contingency

Contingency percentage rate is the confidence level in the information used to create the estimate. The contingency percentage rate is used to padded the estimate with a percentage rate.

Complexity

Tasks and Factors use following complexity scale.

  • Very Simple - Task is trivial, owner knows how to solve the problem and can be done quickly.
  • Simple - Owner knows how to solve the problem.
  • Medium - Owner needs to do a little bit of research to solve the problem, but the resulting solution is not complex.
  • Complex - Task needs research and some clarification on details. Resulting solution is not trivial.
  • Very Complex - Task needs research and clarification. Resulting solution requires significant new work or change.

Organizations

Projects and Templates are placed in an organization. All members of the organization can edit the Project or Template.

Select 'Private' to make the Project or Template accessible by only you.

Templates

A template is a group of factors you can quickly add to a project. Templates allow reuse of common factors across projects.




FluentCommand - Fluent Wrapper for DbCommand

Wed, 04 Feb 2015 15:06:00 GMT

Fluent Wrapper for DbCommand

Features

  • Fluent wrapper over DbConnection and DbCommand
  • Callback for parameter return values
  • Automatic handling of connection state
  • Caching of results
  • Automatic creating of entity from DataReader
  • Create Dynamic objects from DataReader
  • Handles multiple result sets

Download

The FluentCommand library is available on nuget.org via package name FluentCommand.

To install FluentCommand, run the following command in the Package Manager Console

PM> Install-Package FluentCommand

Example

Query all users with email domain. Entity is automaticly created from DataReader.

string email = "%@battlestar.com";
string sql = "select * from [User] where EmailAddress like @EmailAddress";

List users;
using (var session = new DataSession("Tracker").Log(Console.WriteLine))
{
    users = session            
        .Sql(sql)
        .Parameter("@EmailAddress", email)
        .Query();
}

Execute a stored procedure with out parameters

Guid userId = Guid.Empty;
int errorCode = -1;

var username = "test." + DateTime.Now.Ticks;
var email = username + "@email.com";

int result;
using (var session = new DataSession("AspNet").Log(Console.WriteLine))
{
    result = session.StoredProcedure("[dbo].[aspnet_Membership_CreateUser]")
        .Parameter("@ApplicationName", "/")
        .Parameter("@UserName", username)
        .Parameter("@Password", "T@est" + DateTime.Now.Ticks)
        .Parameter("@Email", email)
        .Parameter("@PasswordSalt", "test salt")
        .Parameter("@PasswordQuestion", null)
        .Parameter("@PasswordAnswer", null)
        .Parameter("@IsApproved", true)
        .Parameter("@CurrentTimeUtc", DateTime.UtcNow)
        .Parameter("@UniqueEmail", 1)
        .Parameter("@PasswordFormat", 1)
        .ParameterOut("@UserId", p => userId = p)
        .Return(p => errorCode = p)
        .Execute();
}

Query for user by email address. Also return Role and Status entities.

string email = "kara.thrace@battlestar.com";
string sql = "select * from [User] where EmailAddress = @EmailAddress; " +
             "select * from [Status]; " +
             "select * from [Priority]; ";

User user = null;
List status = null;
List priorities = null;

using (var session = new DataSession("Tracker").Log(Console.WriteLine))
{
    session.Sql(sql)
        .Parameter("@EmailAddress", email)
        .QueryMultiple(q =>
        {
            user = q.QuerySingle();
            status = q.Query().ToList();
            priorities = q.Query().ToList();
        });
}



KickStart - Application Initialization Framework

Wed, 17 Dec 2014 14:48:00 GMT

Application start-up helper to initialize things like an IoC container, register mapping information or run a task. Features Run tasks on application start-up Extension model to add library specific start up tasks Common IoC container adaptor Sigleton instance of an application level IoC container Download The KickStart library is available on nuget.org via package name KickStart. To install KickStart, run the following command in the Package Manager Console PM> Install-Package KickStart NuGet: http://www.nuget.org/packages?q=KickStart Source: http://github.com/loresoft/KickStart Example This example will scan the assembly containing UserModule. Then it will find all Autofac modules and register them with Autofac. Then, all AutoMapper profiles will be registered with Automapper. Finally, it will find all classes that implement IStartupTask and run it. Kick.Start(config => config .IncludeAssemblyFor() .UseAutofac() .UseAutoMapper() .UseStartupTask() ); Extensions StartupTask - Run any class that implements IStartupTask Autofac - Registers all Autofac Module classes and creates the container AutoMapper - Registers all AutoMapper Profile classes log4net - Use log4net as a logger MongoDB - Registers all BsonClassMap classes with MongoDB serialization Ninject - Registers all NinjectModule classes and creates an IKernal NLog - Use NLog as a logger SimpleInjector - Run all ISimpleInjectorRegistration instances allowing container registration Unity - Run all IUnityRegistration instances allowing container registration StartupTask The StartupTask extension allows running code on application start-up. To use this extension, implement the IStartupTask interface. Use the Priority property to control the order of execution. Basic usage Kick.Start(config => config .IncludeAssemblyFor() // where to look for tasks .UseStartupTask() // include startup tasks in the Kick Start ); Use the Common Container to resolve startup tasks Kick.Start(config => config .IncludeAssemblyFor() .UseAutofac() // init Autofac or any other IoC as container .UseStartupTask(c => c.UseContainer()) // config to use the shared container ); Autofac The Autofac extension allows registration of types to be resolved. The extension also creates a default container and sets it to the Kick.Container singleton for access later. Basic usage Kick.Start(config => config .IncludeAssemblyFor() // where to look for tasks .UseAutofac() // initialize Autofac ); Use with ASP.NET MVC Kick.Start(c => c .IncludeAssemblyFor() .UseAutofac(a => a .Builder(b => b.RegisterControllers(typeof(MvcApplication).Assembly)) // register all controllers .Container(r => DependencyResolver.SetResolver(new AutofacDependencyResolver(r))) // set asp.net resolver ) .UseAutoMapper() .UseMongoDB() .UseStartupTask() ); To install Autofac extension, run the following command in the Package Manager Console PM> Install-Package KickStart.Autofac SimpleInjector The SimpleInjector extension allows registration of types to be resolved by running all instances of ISimpleInjectorRegistration. The extension also creates a default container and sets it to the Kick.Container singleton for access later. Basic usage Kick.Start(config => config .IncludeAssemblyFor() // where to look .UseSimpleInjector () // initialize SimpleInjector ); To install SimpleInjector extension, run the following command in the Package Manager Console PM> Install-Package KickStart.SimpleInjector Unity The Unity extension allows registration of types to be resolved by running all instances of IUnityRegistration. The extension also creates a default container and sets it to the [...]



Entity Framework Batch Update and Future Queries

Tue, 29 Nov 2011 16:24:00 GMT

Entity Framework Extended Library A library the extends the functionality of Entity Framework. Features Batch Update and Delete Future Queries Audit Log Project Package and Source NuGet Package PM> Install-Package EntityFramework.Extended NuGet: http://nuget.org/List/Packages/EntityFramework.Extended Source: http://github.com/loresoft/EntityFramework.Extended Batch Update and Delete A current limitations of the Entity Framework is that in order to update or delete an entity you have to first retrieve it into memory. Now in most scenarios this is just fine. There are however some senerios where performance would suffer. Also, for single deletes, the object must be retrieved before it can be deleted requiring two calls to the database. Batch update and delete eliminates the need to retrieve and load an entity before modifying it. Deleting //delete all users where FirstName matches context.Users.Delete(u => u.FirstName == "firstname"); Update //update all tasks with status of 1 to status of 2 context.Tasks.Update( t => t.StatusId == 1, t => new Task {StatusId = 2}); //example of using an IQueryable as the filter for the update var users = context.Users .Where(u => u.FirstName == "firstname"); context.Users.Update( users, u => new User {FirstName = "newfirstname"}); Future Queries Build up a list of queries for the data that you need and the first time any of the results are accessed, all the data will retrieved in one round trip to the database server. Reducing the number of trips to the database is a great. Using this feature is as simple as appending .Future() to the end of your queries. To use the Future Queries, make sure to import the EntityFramework.Extensions namespace. Future queries are created with the following extension methods... Future() FutureFirstOrDefault() FutureCount() Sample // build up queries var q1 = db.Users .Where(t => t.EmailAddress == "one@test.com") .Future(); var q2 = db.Tasks .Where(t => t.Summary == "Test") .Future(); // this triggers the loading of all the future queries var users = q1.ToList(); In the example above, there are 2 queries built up, as soon as one of the queries is enumerated, it triggers the batch load of both queries. // base query var q = db.Tasks.Where(t => t.Priority == 2); // get total count var q1 = q.FutureCount(); // get page var q2 = q.Skip(pageIndex).Take(pageSize).Future(); // triggers execute as a batch int total = q1.Value; var tasks = q2.ToList(); In this example, we have a common senerio where you want to page a list of tasks. In order for the GUI to setup the paging control, you need a total count. With Future, we can batch together the queries to get all the data in one database call. Future queries work by creating the appropriate IFutureQuery object that keeps the IQuerable. The IFutureQuery object is then stored in IFutureContext.FutureQueries list. Then, when one of the IFutureQuery objects is enumerated, it calls back to IFutureContext.ExecuteFutureQueries() via the LoadAction delegate. ExecuteFutureQueries builds a batch query from all the stored IFutureQuery objects. Finally, all the IFutureQuery objects are updated with the results from the query. Audit Log The Audit Log feature will capture the changes to entities anytime they are submitted to the database. The Audit Log captures only the entities that are changed and only the properties on those entities that were changed. The before and after values are recorded. AuditLogger.LastAudit is where this information is held and there is a ToXml() method that makes it easy to turn the AuditLog into xml for easy storage. The AuditLog can be customized via attributes on the entities or via a Fluent Configuration API. Fluent Configuration // config audit [...]



SvnBackup - Backup Tool For Subversion Repositories

Tue, 21 Jul 2009 17:04:00 GMT

 

Overview

The SvnBackup command line tool is used to create backup copies of your subversion repositories.  The source code is the life blood of your application.  Keeping the source repository backed up is major part in keeping your team going in case something goes wrong with your repository.

Features

  • Backup repository using hotcopy command
  • Backup folder management
  • Support repository parent directory
  • Keep x number of backups
  • Compress backups

Backup Process

SvnBackup follows the recommend way of backing up your subversion repository.  While you can xcopy your repository, it may not always be the safest.  SvnBackup automates the process by using svnadmin hotcopy command.  The hotcopy command is the only safe way to make a backup copy of your repository.

SvnBackup also support starting from a parent folder that has all your repositories.  The tool will loop through all the repositories in that folder backing each up. The following folder layout contains imaginary repositories: calculator, calendar, and spreadsheet.

repo/
calculator/
calendar/
spreadsheet/

The backups are stored in a root backup folder.  SvnBackup will create a subfolder for each repository.  Then it will create a folder for the current revision being backed up.  The hotcopy will be placed in the revision folder.  This allows you to keep multiple backup versions of your repository.  The following is an example of the backup folder structure created by SvnBackup.

backup/
calculator/
v0000001/
v0000008/
v0000017/
calendar/
v0000001/
v0000014/
v0000127/
spreadsheet/
v0000001/
v0000023/
v0000047/

SvnBackup supports pruning your backups to only keep so many.  For example, you can keep the last 10 backups.

Another feature of SvnBackup is to compress the backup.  If you have a lot of repositories, zipping up the backup can save a lot of space.

Command Line Options

SvnBackup.exe /r: /b: /c

- BACKUP OPTIONS -

/history: Number of backups to keep. (/n)
/compress Compress backup folders. (/c)
/repository: Repository root folder. (/r)
/backup: Backup root folder. (/b)
/svn: Path to subversion bin folder. (/s)

Project Page




Caching the results from LinqDataSource

Mon, 13 Aug 2007 20:24:00 GMT

I wanted to be able to cache the results of a query from the LinqDataSource that was used in multiple places on the page.  I whipped up this little class to do the work of caching for me.  The class, LinqCacheDataSource, handles the Selecting and Selected events.  The Selected handler inserts the result of the query into cache.  The Selecting handler gets the result from the cache.  If it doesn't find the result, the query runs as normal.  The caching will only work for selecting data.  It works great for dropdowns and other fairly static data. The Code ... /// /// A LinqDataSource that provides caching for Linq queries. /// public class LinqCacheDataSource : LinqDataSource {     ///     /// Initializes a new instance of the class.     ///     public LinqCacheDataSource()         : base()     {         this.Selecting += new EventHandler(OnSelecting);         this.Selected += new EventHandler(OnSelected);     }       private void OnSelecting(object sender, LinqDataSourceSelectEventArgs e)     {         if (!EnableCache)             return;           string key = GetKey();         object source = Context.Cache[key];         if (source == null)             return;           Debug.WriteLine("Cache Hit: " + key);         e.Result = source;     }       private void OnSelected(object sender, LinqDataSourceStatusEventArgs e)     {         if (!EnableCache)             return;           if (e.Exception != null || e.Result == null)             return;           string key = GetKey();         object source = Context.Cache[key];         if (source != null)             return;           Debug.WriteLine("Cache Insert: " + key);         Context.Cache.Insert(key, e.Result, null,             DateTime.Now.AddSeconds(Duration), Cache.NoSlidingExpiration);     }       private string GetKey()     {         StringBuilder sb = new StringBuilder();         sb.Append(this.ContextTypeName);         sb.Append(" from ");         sb.Append(this.TableName);           if (!string.IsNullOrEmpty(this.Select))         {             sb.Append(" select ");             sb.Append(this.Select);         }         if (!string.IsNullOrEmpty(this.Where))         {             sb.Append(" where ");            [...]



PLINQO - CodeSmith LINQ to SQL Templates

Fri, 10 Aug 2007 17:36:00 GMT

PLINQO, which stands for Professional LINQ to Objects, is a collection of CodeSmith templates that are meant to replace and extend the LINQ to SQL designers that are included with Visual Studio 2008.

Features

  • Generate or update a LINQ to SQL dbml file from a database schema.
    • Includes all tables, stored procedures, functions, and views with the ability to exclude objects based on regex patterns.
    • Ability to automatically remove object prefix and suffixes (ie. tbl_ and usp_).
    • Dbml file can still be customized with the normal Visual Studio 2008 designer.
    • Dbml file can be refreshed based on the current database schema without losing customizations. (See Safe Attributes)
  • Generation of the LINQ to SQL DataContext class.
  • Generation of the LINQ to SQL entity classes.
    • Generates one file per entity instead of one massive file.
    • Generates partial classes where custom code can be written and won't be overwritten.
    • Generated entity files are added to the project as code behind files to their corresponding custom entity files.
  • Generation of entity manager classes.
    • Adds customizable business rules engine to enforce entity validation, business and security rules.
    • Provides access to common queries based on primary keys, foreign keys, and indexes.
    • Common queries are exposed as IQueryable so they can be extended.
  • All templates can be customized to meet your needs.

Read More

http://community.codesmithtools.com/blogs/pwelter/archive/2007/08/08/plinqo.aspx

Download 

http://www.codeplex.com/codesmith/Release/ProjectReleases.aspx 




Easier way to page Linq queries.

Thu, 31 May 2007 22:48:00 GMT

The following query extension will make paging a query more natural then skip and take.  Simply append Paginate(page, pageSize) to your query.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace System.Linq
{
    public static class PageQuery
    {
        public static IQueryable Paginate(
            this IQueryable query, int page, int pageSize)
        {
            int skip = Math.Max(pageSize * (page - 1), 0);
            return query.Skip(skip).Take(pageSize);
        }
    }
}




Calculator.NET - Calculator that evaluates math expressions

Sat, 05 May 2007 21:38:00 GMT

I'd like to announce the release of a little project I've been working on.  I call it Calculator.NET.  I started this project for a couple reasons.  First, I was annoyed that Windows Vista doesn't come with a better calculator.  Windows XP has Power Calculator, but that doesn't work on Vista.  Next, I was reading a blog about DynCalc by Bart De Smet on how to do mathematical calculations. That gave me the starting point on how to create Calculator.NET. 

As part of the project, I created a MathExpressions library that does the bulk of work.  The library supports math expressions, functions unit conversion and variables. Below are some examples of using the library directly.

MathEvaluator eval = new MathEvaluator();
//basic math
double result = eval.Evaluate("(2 + 1) * (1 + 2)");
//calling a function
result = eval.Evaluate("sqrt(4)");
//evaluate trigonometric
result = eval.Evaluate("cos(pi * 45 / 180.0)");
//convert inches to feet
result = eval.Evaluate("12 [in->ft]");
//use variable
result = eval.Evaluate("answer * 10");
//add variable
eval.Variables.Add("x", 10);
result = eval.Evaluate("x * 10");

Calculator that evaluates math expressions.
(image)

Calculator.NET Features

  • Evaluate math expressions including grouping
  • Support trigonometry and other function
  • Common unit conversion of the following types
    • Length
    • Mass
    • Speed
    • Temperature
    • Time
    • Volume
  • Variable support including last answer

Download Calculator.NET




CodeSmith 4.0 Public Beta Released

Thu, 19 Oct 2006 16:24:00 GMT

 

CodeSmith 4.0 Beta 2 has been released and is now available to the public.  Here are just a few the new capabilities in CodeSmith 4.0:

  • CodeSmith Projects (.csp) - This feature makes automating your code generation process really easy and consistent whether you are working from inside of Visual Studio 2005, MSBuild, Windows Explorer, a command line / batch file, or CodeSmith itself.
  • ActiveSnippets - Imagine Visual Studio 2005 snippets, but with the full power of CodeSmith available to execute any logic or access any complex metadata (including database schema and xml data) to control the output of your snippets.
  • CodeSmith Maps (.csmap) - This feature will allow you to create dictionary style maps of things like SQL to C# data type mappings.
  • .netTiers 2.0 - The .netTiers templates have been greatly enhanced and included with CodeSmith 4.0.
  • Extended Property Management - You can now edit and add new schema extended properties inside of CodeSmith Studio.
  • Property Persistence - CodeSmith now remembers the property values from the last time you executed a template.

You can read the announcement here.




XML Serializable Generic Dictionary

Wed, 03 May 2006 17:13:00 GMT

XML Serializable Generic Dictionary For some reason, the generic Dictionary in .net 2.0 is not XML serializable.  The following code snippet is a xml serializable generic dictionary.  The dictionary is serialzable by implementing the IXmlSerializable interface.      using System;     using System.Collections.Generic;     using System.Text;     using System.Xml.Serialization;       [XmlRoot("dictionary")]     public class SerializableDictionary         : Dictionary, IXmlSerializable     {         #region IXmlSerializable Members         public System.Xml.Schema.XmlSchema GetSchema()         {             return null;         }           public void ReadXml(System.Xml.XmlReader reader)         {             XmlSerializer keySerializer = new XmlSerializer(typeof(TKey));             XmlSerializer valueSerializer = new XmlSerializer(typeof(TValue));               bool wasEmpty = reader.IsEmptyElement;             reader.Read();               if (wasEmpty)                 return;               while (reader.NodeType != System.Xml.XmlNodeType.EndElement)             {                 reader.ReadStartElement("item");                   reader.ReadStartElement("key");                 TKey key = (TKey)keySerializer.Deserialize(reader);                 reader.ReadEndElement();                   reader.ReadStartElement("value");                 TValue value = (TValue)valueSerializer.Deserialize(reader);                 reader.ReadEndElement();                   this.Add(key, value);                   reader.ReadEndElement();                 reader.MoveToContent();             }             reader.ReadEndElement();         }           public void WriteXml(System.Xml.XmlWriter writer)         {             XmlSerializer keySerializer = new XmlSerializer(typeof(TKey));             XmlSerializer valueSerializer = new XmlSerializer(typeof(TValue));               foreach (TKey key in this.Keys)       [...]



MSBuild Community Tasks Project releases new version

Fri, 31 Mar 2006 20:15:00 GMT

Announcement The MSBuild Community Tasks Project releases version v1.1.0.145. There are many new tasks in this release.  Special thanks to all the contributors to the project. Current Community Tasks Task Description AppPoolController Allows control for an application pool on a local or remote machine with IIS installed. AppPoolCreate Creates a new application pool on a local or remote machine. AppPoolDelete Deletes an existing application pool on a local or remote machine. AssemblyInfo Generates an AssemblyInfo file using the attributes given. Attrib Changes the attributes of files and/or directories FileUpdate Replace text in file(s) using a Regular Expression. FtpUpload Uploads a file using File Transfer Protocol (FTP). FxCop Uses FxCop to analyze managed code assemblies and reports on their design best-practice compliance. Mail Sends an email message. Math.Add Add numbers. Math.Divide Divide numbers. Math.Multiple Multiple numbers. Math.Subtract Subtract numbers. Move Moves files on the filesystem to a new location. NDoc Runs NDoc to create documentation. NUnit Runs tests using the NUnit. RegistryRead Reads a value from the Registry. RegistryWrite Writes a value to the Registry. Script Executes code contained within the task. ServiceController Task that can control a Windows service. ServiceQuery Task that can determine the status of a service. Sleep A task for sleeping for a specified period of time. SqlExecute Executes a SQL command SvnCheckout Checkout files from Subversion SvnClient Subversion Client SvnCommit Commit files to Subversion SvnExport Export files from Subversion SvnInfo Get Subversion information for a file or directory. SvnUpdate Update files from Subversion SvnVersion Get Subversion revision number of a local copy TaskSchema Generates a XSD schema of the MSBuild tasks in an assembly. Time Gets the current date and time. Unzip Unzip a file to a target directory. Version Increments a four-part version number stored in a text file VssAdd Adds files to a Visual SourceSafe database. VssCheckin Checks in files to a Visual SourceSafe database. VssCheckout Checks out files from a Visual SourceSafe database. VssClean Removes Visual SourceSafe binding information and status files from a Visual Studio solution tree. VssDiff Generates a diff between two versions of an item in a Visual SourceSafe database. VssGet Gets the latest version of a file or project from a Visual SourceSafe database. VssHistory Generates an XML file containing the history of an item in a Visual SourceSafe database between two dates or labels. VssLabel Labels an item in a Visual SourceSafe database. VssUndoCheckout Cancels a checkout of an item from a Visual SourceSafe database. WebDirectoryCreate Creates a new web directory on a local or remote machine. WebDirectoryDelete Deletes a web directory on a local or remote machine WebDownload Downloads a resource with the specified URI to a local file. XmlRead Reads a value from a XML document using a XPath. XmlWrite Updates a XML document using a XPath. Xslt Merge and transform a set of xml files. Zip Create a zip file with the files specified. Join Project Please join the MSBuild Community Tasks Project and help contribute in building the tasks.  http://msbuildtasks.tigris.org/ Download The Latest Release The latest binaries, source and installer for Windows can be found in this directory of the Tigris file-sharing area. MSBuild.Community.Tasks.msi - MSBuild Community Tasks Setup MSBuild.Community.Tasks.v1.1.0.145.zip - MSBuild Community Tasks v1.1.0.145 Source [...]



Create a Relative path code snippet

Wed, 08 Feb 2006 07:38:00 GMT

Here is a code snippet that is equivalent to the windows API PathRelativePathTo as native c#. The function creates a relative path from one file or folder to another. public class PathUtil {     ///     /// Creates a relative path from one file     /// or folder to another.     ///     ///     /// Contains the directory that defines the     /// start of the relative path.     ///     ///     /// Contains the path that defines the     /// endpoint of the relative path.     ///     ///     /// The relative path from the start     /// directory to the end path.     ///     ///     public static string RelativePathTo(         string fromDirectory, string toPath)     {         if (fromDirectory == null)             throw new ArgumentNullException("fromDirectory");           if (toPath == null)             throw new ArgumentNullException("toPath");           bool isRooted = Path.IsPathRooted(fromDirectory)             && Path.IsPathRooted(toPath);           if (isRooted)         {             bool isDifferentRoot = string.Compare(                 Path.GetPathRoot(fromDirectory),                 Path.GetPathRoot(toPath), true) != 0;               if (isDifferentRoot)                 return toPath;                                  }                          StringCollection relativePath = new StringCollection();         string[] fromDirectories = fromDirectory.Split(             Path.DirectorySeparatorChar);           string[] toDirectories = toPath.Split(             Path.DirectorySeparatorChar);           int length = Math.Min(             fromDirectories.Length,             toDirectories.Length);           int lastCommonRoot = -1;           // find common root         for (int x = 0; x < length; x++)         {             if (string.Compare(fromDirectories[x],                 toDirectori[...]



Draco.NET version 1.6.4.0 Released

Thu, 05 Jan 2006 19:28:00 GMT

 I’ve update and released a new version of Draco.NET.  This release is mainly to make it compatible with Visual Studio 2005 and MSBuild.  The following is a list of changes …

1.6-release-2 (1.6.4.0)
  • Added MSBuild support
  • Added Visual Studio 2005 support
  • Added manual build (no polling) support
  • Improved project config web page
  • Fixed bug where error emails were sent repeatedly

What is Draco.NET?

Draco.NET is a Windows service application designed to facilitate continuous integration. Draco.NET monitors your source code repository, automatically rebuilds your project when changes are detected and then emails you the build result along with a list of changes since the last build.

Get the latest

http://sourceforge.net/project/showfiles.php?group_id=66880

~ Paul

 

 




Sample build file using MSBuild Community Tasks

Mon, 05 Dec 2005 18:27:00 GMT

The MSBuild Community Tasks Project has released the first version of tasks.  The following is a sample build project that uses the SvnVersion, AssemblyInfo, NDoc and Zip tasks to create a release.   Import Targets   The first thing that needs to be done in the build file is to import the MSBuild.Community.Tasks.Targets file that defines the available tasks.  If you use the msi installer to install the MSBuild Community Tasks, you can use the path "$(MSBuildExtensionsPath)\MSBuildCommunityTasks\MSBuild.Community.Tasks.Targets".    Version Target   The first target in the sample file is the Version target.  The version target is used to update the latest version number.  First the SvnVersion task is used to get the latest Revision number from the local working subversion repository.  SvnVersion outputs the Revision to the Revision property.   Next the target uses the AssemblyInfo task to generate an AssemblyInfo.cs file with the attributes specified.   Compile Target   The compile target calls msbuild to compile the solution in release mode.  The MSBuild target will compile the solution the exact same way Visual Studio will.   Documentation Target   To create help for the project, there is the documentation target.  In the documentation target, the NDoc task is used to compile a HTML Help project.  To use the NDoc task, you must have NDoc 1.3.1 installed.   The generated HTML Help file is then moved to the documentation folder and the temp files are cleaned up.   Zip Target   The zip target is used to package up the whole project into a zip file.  Zip target uses the Zip task to create the zip.  The files included in the zip are selected by the ItemGroup ZipFiles.      Sample Master.proj File             1     0     0     0                                                                                         &n[...]



MSBuild Community Tasks Project releases version v1.0.0.29

Sat, 03 Dec 2005 07:35:00 GMT

Announcement

The MSBuild Community Tasks Project releases version v1.0.0.29. The following is a list of tasks.

Current Community Tasks

Task Description
AssemblyInfo Generates an AssemblyInfo file using the attributes given.
FtpUpload Uploads a file using File Transfer Protocol (FTP).
Mail Sends an email message.
Math.Add Add numbers.
Math.Divide Divide numbers.
Math.Multiple Multiple numbers.
Math.Subtract Subtract numbers.
NDoc Runs NDoc V1.3.1 to create documentation.
NUnit Runs tests using the NUnit V2.2 framework.
RegistryRead Reads a value from the Registry.
RegistryWrite Writes a value to the Registry.
SvnCheckout Checkout files from Subversion
SvnClient Subversion Client
SvnCommit Commit files to Subversion
SvnExport Export files from Subversion
SvnUpdate Update files from Subversion
SvnVersion Get Subversion revision number of a local copy
Unzip Unzip a file to a target directory.
Version Increments a four-part version number stored in a text file
XmlRead Reads a value from a XML document using a XPath.
XmlWrite Updates a XML document using a XPath.
Zip Create a zip file with the files specified.

Join Project

Please join the MSBuild Community Tasks Project and help contribute in building the tasks. 

http://msbuildtasks.tigris.org/

Get The Source

You can get a local copy of the repository for MSBuild Community Tasks via Subversion. The following command will do the trick:

svn checkout http://msbuildtasks.tigris.org/svn/msbuildtasks/trunk

Download The Latest

The latest binaries, source and installer for Windows can be found in this directory of the Tigris file-sharing area.




MSBuild Community Task Collaboration Project

Mon, 21 Nov 2005 23:29:00 GMT

I’d like to announce the MSBuild Community Task Collaboration Project.  The project was started by me to form a directory of MSBuild Tasks for use in your build scripts.  The project is also an open source collection of tasks.  The project is broke into 2 web sites. 

The first is http://msbuildtasks.com/ which is a community server install with forums and a directory of MSBuild tasks.  The goal of msbuildtasks.com is to provide a common place to find tasks.  Please help improve this directory by adding links to tasks that you know about. 

The second site is an open source project hosted at http://msbuildtasks.tigris.org/.  The goal of this site is to build a collection of tasks that is open source for the community.  Please create an account on Tigris.org and join the project to help build out the tasks.

Thanks for contributing to the MSBuild community.

~ Paul