Automating KiGG Submission

by KodefuGuru 30. July 2009 18:35

This is part 3 of a series on KiGG Automation. Code in this article may be dependent on previous entries.

Part 1: Automating KiGG Publishing
Part 2: KiGG’s Story Summary 
Part 3: Automating KiGG Submission

When you’re first starting a KiGG site and your user base is low, creating a bot can ease the pain of obtaining content. However, in the default install of KiGG there is no way to automate this. You can search blogs and news sites, but submitting articles from those sites is a manual process; even for the sources you trust.

My goal in this article is to build off of the first article so that submission can be automated. There are many sources of content out there, and I may cover some aspects of retrieving this in future articles. But for now, that it is up to you to explore.

Finding the submit route is pretty simple: it is Submit and it is handled by the StoryController.

_routes.MapRoute("Submit", "Submit", 
    new { controller = "Story", action = "Submit" });

The method on the controller makes it clear what http method we must use and the parameters required.

[AcceptVerbs(HttpVerbs.Post), ValidateInput(false), Compress]
public ActionResult Submit(string url, 
    string title, string category, string description, string tags)

Analyzing this method shows that another JSON class can be used: JsonCreateViewData. We will need to add this to our bot’s codebase. It uses two properties already found on KiggResult, so we will call this KiggCreateResult and derive from the former class.

public class KiggCreateResult : KiggResult
{        
    [JsonProperty(PropertyName = "url")]
    public string Url { get; set; }

    public static KiggCreateResult Create(string json)
    {
        return JsonConvert.DeserializeObject<KiggCreateResult>(json);
    }
}

Now, inside KiggBot.cs, we will need to add our submit method. I think it may be better to return the url to the story here, but I’ll worry about refactoring this later. Remember that HttpDictionary will handle the form encoding for us.

public bool Submit(string storyUrl, string title, 
    string category, string description, string tags)
{
    HttpDictionary dictionary = new HttpDictionary { 
        {"url", storyUrl}, 
        {"title", title},
        {"category", category},
        {"description", description},
        {"tags", tags}
    };

    var result = KiggCreateResult.Create(
        session.Post(url + "Submit", dictionary));

    return result.IsSuccessful;
}

That seemed easy enough. Now, in the test program I will call this with a few parameters to see how it works.

KiggBot bot = new KiggBot("http://localhost:1736");
bot.Login("bee", "iambusy");
bot.Submit("http://example.com/", "Example", "Agile", 
    "This is a test", "Example, News");
bot.Logout();

No dice. I received an error that the user agent must be set. I think user agent should be configurable in our program, but for simplicity I will add a constant to WebSession for userAgent and set it on the request object in the Post method.

private const string userAgent = "Pigg";
public string Post(string url, string formData)
{
    var request = WebRequest.Create(url) as HttpWebRequest;
    request.UserAgent = userAgent;
    ...
}

I tried again, and it worked perfectly. The bot created an entry with two new tags: Example and News. Keep in mind that Category must match a valid category in your KiGG install.

If you’re following along, you can now automate KiGG publishing and article submission. You can also define what part of the html from which the story summary is retrieved. Leave a comment on what part of KiGG automation you would like me to look at next.

Tags: , ,

Free PowerShell EBook

by KodefuGuru 24. July 2009 16:23

Tags: ,

Kodefu

Basic Unit Testing Guidelines

by KodefuGuru 23. July 2009 16:26

When I recently started looking through a certain project’s tests, I was struck by how difficult it was for me to read and understand. The tests were laid out haphazardly, and the code contained enough logic to make me wonder if it would be easier to analyze the functional code. Tests don’t do anyone good if they require that much analysis. In contrast, one of my favorite open source projects contains tests that allow me to learn the functionality of the system without looking at any functional code.

The intent of this post isn’t to describe advanced unit testing techniques but to describe a few guidelines that I feel should be implemented regardless if you’re mocking objects, using test driven development, or just want to ensure your code works. I am using Microsoft’s unit testing framework, but these same guidelines apply in most other unit testing frameworks.

Name Code Files Sensibly

You should be able to find your test, which may be difficult to do if you name your file “MyTests.cs.” Naming the file after the class you’re testing is a guideline many people use. Alternatively, you can name it after a functional area if you have more than one fixture per file. Yes, generally speaking you should have one class per file, but I admit to relaxing this rule because you are going to experience class explosion if you’re striving for 100% coverage. I prefer to name my class files after the class just as I do in functional development.

Name Fixture After Scenario

Your test fixture should set up a scenario, and the name of the class should reflect that scenario. For example, if you’re testing what happens when a user activates an account, name the class “WhenUserActivatesAccount.”

[TestClass]
public class WhenUserActivatesAccount
{
}

Setup Code in Constructor

Usually, your constructor (or Setup method in some frameworks) should initialize the scenario that you’re testing. If external setup must be done, use the ClassInitializer attribute on a static method.

User user;
Account account;

public WhenUserActivatesAccount()
{
    user = new User("kodefuguru");
    account = user.Account;
    account.Activate();
}

If you expect exceptions with certain parameters in various, similar scenarios; it may be necessary to call the setup code from within the testing method. I prefer to refactor my tests so that the test for the expected exception is in a derived class that tweaks the modifications within its constructor before calling the base constructor… for example, “public class WhenInvalidUserActivatesAccount : WhenUserActivatesAccount.”

Name Test After Expected Result

Ideally, tests contain one Assert statement. You’re testing a specific condition that you expect to occur as a result of the scenario you’ve presented. When a user activates an account, you expect the account to activated. Therefore, your test should be named “AccountActivatedShouldBeTrue,” with the assertion “Assert.IsTrue(account.Activated).”

[TestMethod]
public void AccountActivatedShouldBeTrue()
{
    Assert.IsTrue(account.Activated);
}

No Conditionals Containing Assertions

If assertions are contained within a conditional statement, then you aren’t really ensuring that your code is running as expected. When you’re writing tests, you’re declaring the behavior of your system based upon certain conditions.

[TestMethod]
public void AccountActivatedShouldDependOnUserValid()
{
    if (user.Valid)
    {
        Assert.IsTrue(account.Activated);
    }
    else
    {
        Assert.IsFalse(account.Activated);
    }
}

If I have a test like this, I’m not really declaring a fact about the system. Instead, I’m declaring facts about two different situations, one of which will not occur. Whether user.Valid is true or not should depend on the setup of my test, and I should know what the value will be when this test runs.

Differentiate Between Unit Tests and Integration Tests

Unit tests are for testing an individual unit of code. Integration tests are for testing functionality between different systems. It is best to separate unit tests and integration tests by placing them in separate projects. If you’re not already doing so, at some point you may wish to automate your testing process. In a continuous integration environment, unit tests should be run with every build. Integration tests tend to be slower, and it is oftentimes not practical to automate them as frequently.

If you have trouble differentiating between unit tests and integration tests (i.e. everything you do connects to a service or persists to the database), it would be a good idea to look into mocking and inversion of control so that you can create tests for units of functionality.

---

There are many more things you can do to create effective unit tests, but if you follow the few guidelines I have listed you will benefit immediately. It is important that it is easy for anyone looking at your tests to know how the system is supposed to behave. There is additional benefit in that you can harvest fixture and test names to create functional documentation for your software.

Tags: ,

Kodefu

KiGG’s Story Summary

by KodefuGuru 20. July 2009 10:03

This is part 2 of a series on KiGG Automation.

Part 1: Automating KiGG Publishing
Part 2: KiGG’s Story Summary 
Part 3: Automating KiGG Submission

I noticed that sometimes when you submit a story to KiGG, the summary of the story looks rather garbled. Wishing to correct this, I explored what is actually happening when KiGG summarizes a url for you.

The first step in the process is to go to the submit new story page. When you enter a url into the url field, the site will perform an ajax call that suggests a title and summary. This call is defined by _urlChanged() in story.js. The ajax call is to /Retrieve. Here is the relevant code from New.aspx.

if (Model.AutoDiscover)
{
    scriptManager.RegisterOnReady("Story.set_retrieveStoryUrl('{0}');"
        .FormatWith(Url.RouteUrl("Retrieve")));
}

This will only work if AutoDiscover is set to true, and that is defined in the web.config.

After looking at our routes, we can tell that /Retrieve is calling the Retrieve method on the StoryController. It then returns a view with a StoryContent object after calling the Get method on the member _contentService. This member is set in the constructor. Since KiGG uses Unity, we will need to follow the trail in the web.config to determine which IContentService it’s using (or you can view all classes that implement IContentService and infer the correct choice).

Looking in the web.config, we find the tag: <type type=”StoryController”>. Within the constructor element, we find that contentService is defined as IContentService. Looking through the type elements, we discover that there are three IContentService types. Two of these are decorators (Logging and Caching), so the functionality we’re looking for must be in the one named Base. It maps to ContentService, which is defined in the typeAlias section as Kigg.Infrastructure.ContentService, Kigg.Core. The cool thing about Unity is that you can add your own ContentService decorators and use the web.config to decorate the class without changing any source code.

The content service retrieves the html from the url provided, then calls the converter (again defined by Unity).

string html = 
    _httpForm.Get(new HttpFormGetRequest{ Url = url }).Response;

return string.IsNullOrEmpty(html) ? 
    StoryContent.Empty : _converter.Convert(url, html);

The converter maps to HtmlToStoryContentConverter. Inside that class is the code that attempts to find the content.

private Node TryToFindContentNode(Node bodyNode)
{
    Node contentNode = null;

    foreach (string xPath in _xPaths)
    {
        contentNode = bodyNode.SelectSingleNode(xPath);

        if (contentNode != null)
        {
            break;
        }
    }

    return contentNode;
}

_xPaths is passed in a constructor which is called by another constructor which reads a file. Inside the web.config, we find that Unity has defined the location of the file.

<param name="fileName" parameterType="System.String">
    <value type="System.String" value="App_Data/contentNodes.txt"/>
</param>

Our content nodes are defined within App_Data/contentNodes.txt file. Using this file, we can add xpath style declarations to properly retrieve content from nonstandard articles. Further logic (ignoring h1s, etc) will require changes to the ContentService itself.

Tags: ,

Kodefu

2009 Silverlight Control Builder Contest

by KodefuGuru 15. July 2009 16:45

A week ago, I posted a few summer contests to partake in during those lazy weekends we all experience (yea right). Since that time, another contest was announced by Silverlight MVP, Page Brooks.

2009SilverlightControlBuilderContest

This contest is all about building a Silverlight control. The boundaries are rather loose. You can make it practical, you can make it cool, but most importantly have fun making it!

The deadline for the contest is September 19, leaving just 66 days to get your entry in. If you win, you’ll receive tons of goodies from Devexpress, Infragistics, Telerik, and the SilverlightShow.

Good luck… I will be competing in this one as well.

Tags: ,

General

Response to CRUD is bad for REST

by KodefuGuru 15. July 2009 12:30

Arnon Rotem-Gal-Oz wrote an article for Architect Zone where he makes the claim that CRUD is bad for REST. I couldn’t disagree more, so I felt it important to respond to his criticism.

CRUD which stands for Create, Read, Update and Delete, are the four basic database operations. Some of the  HTTP verbs, namely POST, GET, PUT and DELETE (there are others like OPTIONS or HEAD) seem to have a 1-1 mapping to CRUD. As I said earlier they don’t. The table below briefly contrast HTTP verbs and CRUD

Actually, they do map perfectly as CRUD itself is pretty simple (it’s literally create, retrieve, update, delete without caveats). The examples that are laid out in Arnon’s article are comparing REST directly to SQL Server commands. The question shouldn’t be do http verbs fit perfectly with SQL operations, but rather do they map to the four basic functions of persistent storage? I can say without any doubt that POST, GET, PUT, and DELETE map quite well, making it possible for REST useful for persistence.

The way I see it,  the HTTP verbs are more document oriented than database oriented (which is why document databases like CouchDB are seamlessly RESTful). In any event, what I tried to show here is that while you can update, delete and create new resources the way you do that is not exactly CRUD in the database sense of the word – at least when it comes to using the HTTP verbs.

I see http verbs as resource oriented, and data is just one type of resource. Of course, if I’m creating an ADO.NET Data Service, I want to expose my data as more useful resources (e.g. a useful representation of a Customer rather than just the customer data).

However, the main reason CRUD is wrong for REST is an architectural one. One of the base characteristics [1] of REST is using hypermedia to externalize the statemachine of the protocol (a.k.a. HATEOS– Hypertext as the engine of state). The URI to URI transition is what makes the protocol tick. […] If you are busy with inserting and updating (CRUDing) resources you are not, in fact, thinking about protocols or externalizing a State machine and, in my opinion, miss the whole point about REST.

I could think about protocols, but a useful one already exists (HTTP). I could think about externalizing my state machine, but that’s already taken care of when using a product like ADO.NET Data Services. If you are busy with inserting and updating resources, you probably have a resource oriented architecture which doesn’t miss the whole point of REST as it *is* an implementation of a REST architecture.

CRUD services leads and promoted to the database as a service kind of thinking (e.g. ADO.NET data services) which as I explained in another post last year is a bad idea since:

  1. It circumvents the whole idea about "Services" - there's no business logic.
  2. It is exposing internal database structure or data rather than a thought-out contract.
  3. It encourages bypassing real services and going straight to their data.
  4. It creates a blob service (the data source).
  5. It encourages minuscule demi-serices (the multiple "interfaces" of said blob) that disregard few of the fallacies of distributed computing.
  6. It is just client-server in sheep's clothing.

1. ADO.NET Data Services provides a standard ORM that can be consumed by any application. That in itself is useful as a service (retrieve entities rather than data, mapping is hidden). However, one can provide business logic in that tier if one chooses, but I think that’s bad design.

2. Even with the most direct ORM, you’re still providing mapped objects rather than an internal data structure. If you have a well-thought out map, then you will be providing that instead.

3. You aren’t going straight to the data, you are utilizing entities. The service exists and can act as a gate keeper.

4. I don’t understand this complaint… the data source is a binary large object service? If blob is meant in another sense, my answer is that you only expose what you want to expose with ADO.NET Data Services.

5. I suppose I’ve never thought about setting up multiple demi-services?

6. The problem with client-server is the disregard of object-relational mapping and business layers. Even in the worst case scenario with ADO.NET Data Services, you get object-relational mapping.

I don’t believe CRUD is bad for REST at all. In fact, I believe they perfectly complement each other in the construction of a resource oriented architecture.

Tags: , , , ,

Kodefu

Automating KiGG Publishing

by KodefuGuru 14. July 2009 19:17

This is part 1 of a series on KiGG Automation.

Part 1: Automating KiGG Publishing
Part 2: KiGG’s Story Summary 
Part 3: Automating KiGG Submission

When I set up my first KiGG site, I was surprised to discover that I had to manually publish articles. I assumed it would be an automated process that would run once a day. Since there are times I may not be able to log into my website, I set about figuring out how to automate the process.

I should note that during this process, I didn’t use best practices. I had one requirement: make a program that I can schedule to publish stories on KiGG. I wasn’t really sure what I would need to go about doing that. So, I did what I assume most developers do: create a console application prototype. I don’t claim this code is perfect, but if you want classes to automate publishing in KiGG (or control MVC applications), this will do the trick.

KiGG is an ASP.NET MVC application. This made it easy to figure out where to begin. I wanted to Publish, so I needed to find the admin link and see what it called. I guessed it would be something like, /Publish, and I was correct.

scriptManager.RegisterOnReady("Administration.set_publishUrl('{0}');"
    .FormatWith(Url.RouteUrl("Publish")));

set_publishUrl is simply a setter in the JavaScript to prevent a url from being hardcoded in script. Looking over the JavaScript I could tell there wasn’t much more needed than calling the proper url.

$.ajax(
    {
        url: Administration._publishUrl,
        type: 'POST',
        dataType: 'json',
        data : '__MVCASYNCPOST=true', // a fake param to fool iis for content-lenth,
        beforeSend: function()
        {
            $U.showProgress('Publishing stories...');
        },
        success: function(result)
        {
            $U.hideProgress();

            if (result.isSuccessful)
            {
                $U.messageBox('Success', 'Story publishing process completed.', false);
            }
            else
            {
                $U.messageBox('Error', result.errorMessage, true);
            }
        }
    }
);

The script is doing a POST on the /Publish url with fake data (to fool IIS?).

Next, it was time to check the routing for /Publish. Routing in KiGG is defined in Kigg.Web\BootstrapperTasks\RegisterRoutes.cs. It was done this way to be consistent with the Open Closed Principle.

_routes.MapRoute("Publish", "Publish", 
    new { controller = "Story", action = "Publish" });

Now we know the entry to this is in the story controller and that the method is Publish. The story controller being used is defined within the web.config file using Unity.

<typeAlias alias="StoryController" type="Kigg.Web.StoryController, Kigg.Web"/>

I set up a break point and wrote a quick routine to post to the publish url.

var request = WebRequest.Create(http://localhost:1736/Publish);
request.ContentType = "application/x-www-form-urlencoded"; request.Method = "POST"; var form = Encoding.ASCII.GetBytes("__MVCASYNCPOST=true"); using (Stream requestStream = request.GetRequestStream()) { requestStream.Write(form, 0, form.Length); requestStream.Close(); } var response = request.GetResponse(); using (StreamReader reader = new StreamReader(response.GetResponseStream())) { var responseText = reader.ReadToEnd(); Debug.WriteLine(responseText); reader.Close(); }

Everything executed fine, but the return message indicated something was wrong: “{"isSuccessful":false,"errorMessage":"You are currently not authenticated."}.” It’s pretty obvious that authentication would be necessary, otherwise I could publish DotNetShoutOut whenever I wanted. Unfortunately, the obvious way to authenticate does not work.

request.Credentials = new NetworkCredential("admin", "password");

Since it is a NetworkCredential, I assume this code would work with Windows authentication turned on. However, we’re using forms authentication. I looked at the routes and found one for Login and Logout. At this point it was clear that I would be calling post multiple times, so I moved the code to a method that would accept a url and formdata as a string.

Post("http://localhost:1736/Login", "userName=admin&password=password");
Post("http://localhost:1736/Publish", "__MVCASYNCPOST=true");
Post("http://localhost:1736/Logout", "__MVCASYNCPOST=true");

This returned the following results:

{"isSuccessful":true,"errorMessage":null}
{"isSuccessful":false,"errorMessage":"You are currently not authenticated."}
{"isSuccessful":false,"errorMessage":"You are currently not logged in."}

I put a breakpoint in the Login method of the MembershipController, and from there was able to see what was happening. Although it was a few levels deep, it was clear that FormsAuthentication.SetAuthCookie was the important piece of code; I needed a way to retain cookies between requests.

Cookies are only available by using HttpWebRequest and HttpWebReponse rather than their base classes. So, I cast my variables to the proper class. One odd thing I found was the cookies have to be retrieved from the request rather than the response after you have requested the response. I wrapped this functionality up in a WebSession class.

public class WebSession
{
    protected CookieCollection Cookies { get; set; }

    public WebSession()
    {
        Cookies = new CookieCollection();
    }

    public string Post(string url, HttpDictionary formData)
    {
        return Post(url, formData.ToString());
    }

    public string Post(string url, string formData)
    {            
        var request = WebRequest.Create(url) as HttpWebRequest;
        if (request == null)
        {
            throw new HttpException();
        }
        request.ContentType = "application/x-www-form-urlencoded";
        request.Method = "POST";
        request.CookieContainer = new CookieContainer();
        request.CookieContainer.Add(request.RequestUri, Cookies);

        var form = Encoding.ASCII.GetBytes(formData);
        WriteToRequest(request, form);

        var response = request.GetResponse() as HttpWebResponse;
        if (response == null)
        {
            throw new HttpException();
        }

        var responseText = ReadResponse(response);
        Cookies = request.CookieContainer.GetCookies(request.RequestUri);

        Debug.WriteLine(responseText);
        
        return responseText;
    }

    private static void WriteToRequest(WebRequest request, byte[] form)
    {
        using (Stream requestStream = request.GetRequestStream())
        {
            requestStream.Write(form, 0, form.Length);
            requestStream.Close();
        }
    }

    private string ReadResponse(WebResponse response)
    {
        using (StreamReader reader = 
            new StreamReader(response.GetResponseStream()))
        {
            var responseText = reader.ReadToEnd();
            reader.Close();
            return responseText;
        }
    }
}

If you look closely you’ll notice an HttpDictionary class. This is because I wanted to treat the form data as a dictionary rather than a string. I suppose this could be written as an extension method on Dictionary<string, string> instead.

public class HttpDictionary : Dictionary<string, string>
{
    public override string ToString()
    {
        return this.Select(q => EncodePair(q))
            .Aggregate((a, b) => a + "&" + b);
    }

    private string EncodePair(KeyValuePair<string, string> pair)
    {
        return HttpUtility.HtmlEncode(pair.Key) +
            "=" + HttpUtility.HtmlEncode(pair.Value);
    }
}

I also felt it necessary to wrap up the result received from KiGG in a class that can be used. Otherwise, it’s difficult to know whether or not the call was successful. To convert from Json, I used Json.NET.

public class KiggResult
{        
    [JsonProperty(PropertyName="isSuccessful")]
    public bool IsSuccessful{ get; set; }

    [JsonProperty(PropertyName = "errorMessage")]
    public string ErrorMessage { get; set; }

    public static KiggResult Create(string json)
    {
        return JsonConvert.DeserializeObject<KiggResult>(json);
    }
}

Finally, I made a KiggBot class to provide us an interface that makes sense for accessing a KiGG site. This can be changed to throw an exception if the result indicates the call was not successful.

public class KiggBot 
{
    private static readonly HttpDictionary mvcAsyncPost = new HttpDictionary
    {
        {"__MVCASYNCPOST", "true"}
    };

    private WebSession session;
    private string url;

    public KiggBot(string url)
    {
        if (!url.EndsWith("/"))
            url += "/";

        this.url = url;
        session = new WebSession();
    }

    public bool Login(string userName, string password)
    {
        HttpDictionary dictionary = new HttpDictionary { 
            {"userName", userName}, {"password", password}};

        var result = KiggResult.Create(
            session.Post(url + "Login", dictionary));
        
        return result.IsSuccessful;
    }

    public bool Logout()
    {
        var result = KiggResult.Create(
            session.Post(url + "Logout", mvcAsyncPost));

        return result.IsSuccessful;
    }

    public bool Publish()
    {
        var result = KiggResult.Create(
            session.Post(url + "Publish", mvcAsyncPost));

        return result.IsSuccessful;
    }
}

With these classes, it’s fairly easy to create an automated publishing program. At the very least, write a console app and use scheduler to fire it daily.

KiggBot bot = new KiggBot("http://localhost:1736");
bot.Login("admin", "password");
bot.Publish();
bot.Logout();
Hope that helps. If anyone makes a cool GUI for this and releases it, might I recommend PiGG?

Tags: , ,

Kodefu

WCF from CLR Functions

by KodefuGuru 13. July 2009 18:15

I don’t approve of calling a WCF server from SQL Server, but there was a business requirement that had to be met. It concerned regulations regarding the safeguarding of certain data elements. Due to performance issues and the application’s infrastructure, calling the service from the application itself wasn’t an option.

Coding the CLR functions were the easy part. To do this, reference the Microsoft.SqlServer.Server and System.Data.SqlTypes namespaces (contained in System.Data.dll) and set the appropriate attributes on static methods contained within a static class. Also, it is probably best if you use the SqlTypes (SqlString, SqlDateTime, etc) for parameters and return values rather than rely on Sql Server to convert the values for you. Be sure to enable CLR on your SQL Server.

using System.Data.SqlTypes;
using Microsoft.SqlServer.Server;

public static class SqlFunctions
{
    [SqlFunction(DataAccess = DataAccessKind.Read, IsDeterministic = true)]
    public static SqlString HelloWorld()
    {
        return new SqlString("Hello World!");
    }

}

I wanted to avoid pulling too many assemblies into SQL Server, so I limited my references to the bare essentials for working with WCF and Sql Server: System, System.Data, System.Runtime.Serialization, System.ServiceModel, and System.XML.

Here’s the script to drop the assemblies if they exist and add them back (double slashes are intentional to allow copy/paste with formatting to work). Because of dependencies, it is necessary to add more assemblies than directly referenced by the project. If you created this within a database project, you can deploy by right-clicking the project. I have previously posted instructions on how to convert a class library to a database project.

IF  EXISTS (SELECT * FROM sys.assemblies asms 
WHERE asms.name = N'Microsoft.Transactions.Bridge') 
    DROP ASSEMBLY [Microsoft.Transactions.Bridge]
GO

IF  EXISTS (SELECT * FROM sys.assemblies asms 
WHERE asms.name = N'System.IdentityModel.Selectors') 
    DROP ASSEMBLY [System.IdentityModel.Selectors]
GO

IF  EXISTS (SELECT * FROM sys.assemblies asms 
WHERE asms.name = N'System.IdentityModel') 
    DROP ASSEMBLY [System.IdentityModel]
GO

IF  EXISTS (SELECT * FROM sys.assemblies asms 
WHERE asms.name = N'System.Messaging') 
    DROP ASSEMBLY [System.Messaging]
GO

IF  EXISTS (SELECT * FROM sys.assemblies asms 
WHERE asms.name = N'System.Web') 
    DROP ASSEMBLY [System.Web]
GO

IF  EXISTS (SELECT * FROM sys.assemblies asms 
WHERE asms.name = N'SMDiagnostics')
    DROP ASSEMBLY [SMDiagnostics]
GO

CREATE ASSEMBLY 
SMDiagnostics from
'C:\Windows\Microsoft.NET\Framework\v3.0\
\Windows Communication Foundation\SMDiagnostics.dll'
with permission_set = UNSAFE
GO

CREATE ASSEMBLY 
[System.Web] from
'C:\Windows\Microsoft.NET\Framework\v2.0.50727\
\System.Web.dll'
with permission_set = UNSAFE
GO

CREATE ASSEMBLY 
[System.Messaging] from
'C:\Windows\Microsoft.NET\Framework\v2.0.50727\
\System.Messaging.dll'
with permission_set = UNSAFE
GO

CREATE ASSEMBLY  
[System.IdentityModel] from
'C:\Program Files\Reference Assemblies\Microsoft\
\Framework\v3.0\System.IdentityModel.dll'
with permission_set = UNSAFE
GO

CREATE ASSEMBLY  
[System.IdentityModel.Selectors] from
'C:\Program Files\Reference Assemblies\Microsoft\
\Framework\v3.0\System.IdentityModel.Selectors.dll'
with permission_set = UNSAFE
GO

CREATE ASSEMBLY  
[Microsoft.Transactions.Bridge] from
'C:\Windows\Microsoft.NET\Framework\v3.0\
\Windows Communication Foundation\Microsoft.Transactions.Bridge.dll'
with permission_set = UNSAFE
GO

You will need to add your own assembly to the list in a similar manner as the .NET assemblies. Notice that they are marked UNSAFE. This is a necessary evil if you wish to use WCF with SQL Server. Because of this, if you have not done so you will need to reconfigure your database to allow it.

ALTER DATABASE KodefuGuru SET TRUSTWORTHY ON
reconfigure

The interesting part about this is that more assemblies than those specified are pulled in. When you remove the ones you specifically added, these are removed as well. Here is the list of assemblies:

Accessibility
Microsoft.Transactions.Bridge
SMDiagnostics
System.Configuration.Install
System.Design
System.DirectoryServices
System.DirectoryServices.Protocols
System.Drawing
System.Drawing.Design
System.EnterpriseServices
System.IdentityModel
System.IdentityModel.Selectors
System.Messaging
System.Runtime.Remoting
System.Runtime.Serialization
System.Runtime.Serialization.Formatters.Soap
System.ServiceModel
System.ServiceProcess
System.Web
System.Web.RegularExpressions
System.Windows.Forms

System.Windows.Forms? What?! Some of the dependencies are truly mind boggling.

This should be just enough to allow you to put your service calls inside of CLR functions. I attempted to be as lightweight as possible and avoided pulling in extra libraries, though you certainly could pull in a massive programmatic infrastructure with this.

I only agreed to this because the service call was directly related to the integrity of the data and further restrictions prevented the use of a separate physical tier to handle it. If you’re in the same situation, I hope this helps.

Tags: , ,

Kodefu

Thrive For Developers

by KodefuGuru 9. July 2009 11:50

thriveMicrosoft has launched a one-stop shop for developers seeking to enhance their careers through skill-enhancement, community-involvement, or a new job. It’s called Thrive for Developers, and it appears to be an offshoot of another site of theirs geared toward IT and Business users called, predictably enough, Thrive.

Thrive is really just a collection of links to other resources. Being an active participant in the .net development community, I was already aware of these resources. However, It is really nice to have them in one place.

Next time a developer is asking you for help connecting to the community, skill improvement, or job hunting; you can send them to Thrive For Developers. It beats going through all your bookmarks to compile a list of links for an email.

Tags:

Supplies

4 Cool Summer Coding Competitions

by KodefuGuru 7. July 2009 13:21

I never seem to have the time to enter coding competitions. It’s a shame, because they look like a lot of fun! I do usually bookmark these contests just in case I find myself with a free weekend, and I want to share those with the community. It may mean more competition in case I do enter, but it also means more cool community applications that I get to play with. For example, Twtri is great for updating Twitter or Facebook with your flight status, and it won the grand prize in the new CloudApp() competition!

silverlightcompetitonthumbnailComponentArt is hosting the 2009 Summer Silverlight Coding Competition from June 22nd to September 22nd. The grand prize is $10,000 USD, and the authors of the top two runner-up apps each get a Component Art license. You must have designed the Silverlight 1, 2, or 3 application yourself, and use of ComponentArt products is not required.

 

willcodeforgreen Will Code For Green is sponsored by Bing and Gnomedex, and two grand prize winners will each receive $10,000 USD. The point of the contest is to design a web application or mashup that uses Bing services to help people in this bad global economy or to improve the ecology of our planet. Submission is open through August 12th. The winners will be announced at Gnomedex 2009.

 

ineta Win a trip to PDC 2009 with INETA Component Code Challenge. The goal of the competition is to mash together at least 2 components from 2 different approved vendors to create a .NET application. Then, you must create a 3-5 minute Camtasia video showing off your application and the components you used. Submissions must be received by August 25th, and winners will be announced on September 14th. The top 10 entries will receive prizes, but only the top 2 go to PDC.

 

dreambuildplay The deadline has passed to register for the Dream-Build-Play 2009 Challenge, but you can still enjoy the entries as they come in by visiting the gallery. What is Dream-Build-Play? Well, it’s a competition to create an XNA game. It also has the largest payouts of all the contests I’ve come across: $40,000 grand prize, $20,000 first prize, $10,000 second prize, and $5,000 third prize. Not only that, but the winning teams have an opportunity to potentially receive an Xbox LIVE Arcade Publishing Contract. If you were lucky enough to register in time, you have until August 6th to submit your entry.

 

I only support contests that I feel contribute back to the community, but I sometimes come across a contest that seems interesting, only to read the fine print and discover they claim sole rights to the application you enter. An example of this is the “Super Sexy” Mortgage Calculator Contest. I’m not sure how a mortgage calculator can be thought of as “sexy,” but it nevertheless seemed interesting to me. I tried to read their terms and conditions only to discover they linked to the terms and conditions of a mortgage rather than a contest. However, next to the link was the text, “Mortgage Loan Place will retain sole right to ownership of all submissions.” Dirty stuff.

I’m sure I missed a few contests out there. If you know of any, be sure to leave a comment.

Tags: , , , , ,

Kodefu

Powered by BlogEngine.NET 1.6.0.0
Theme by Mads Kristensen

Whois KodefuGuru

Chris Eargle

Chris Eargle
.NET Community Champion

LinkedIn Twitter Technorati Facebook

MVP - Visual C#

 

INETA Community Champions
Friend of RedGate
Telerik .NET Ninja
Community blogs & blog posts

I am a #52er


World Map

RecentComments

Comment RSS

Tag cloud

Disclaimer

The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.

© Copyright 2010