What do you think? I think it’s a niiize. The timeline is very well designed and easy to use.
At the moment, the new profile is only available to developers.
What do you think? I think it’s a niiize. The timeline is very well designed and easy to use.
At the moment, the new profile is only available to developers.
ASP.NET MVC 3 introduced the concept of DependencyResolver, which enables us to inject our own types into controllers, action filters, view engines and so forth. Here is a implementation of DependencyResolver for Structuremap:
public class StructuremapDependencyResolver : IDependencyResolver { private readonly IContainer _container; public StructuremapDependencyResolver(IContainer container) { _container = container; } public object GetService(Type serviceType) { if (serviceType.IsAbstract || serviceType.IsInterface) { return _container.TryGetInstance(serviceType); } return _container.GetInstance(serviceType); } public IEnumerable<object> GetServices(Type serviceType) { return _container.GetAllInstances<object>().Where(x => x.GetType() == serviceType); } }
With our new DependencyResolver, a custom controller factory is no longer needed.
You tell MVC3 to use our DependencyResolver by registering it in Application_Start (in global.asax, of course):
protected void Application_Start() { ... var container = new Container(new DependencyRegistry()); DependencyResolver.SetResolver(new StructuremapDependencyResolver(container)); ... }
The actual container is set up as normal, with registries passed into it via the constructor.
Happy coding!
“Operation could destabilize the runtime” is an error i’ve been getting lately when working with both RavenDB and ncqrs. The problem is because of Json.NET and IntelliTrace (Visual Studio 2010 Ultimate) not working nice together. A solution is to disable IntelliTrace for all assemblies in the Json.NET. This is done by:
Debug -> Options and Settings -> IntelliTrace -> Modules -> Add *Newtonsoft*
While this solved my issues with RavenDB and ncqrs, i’m sure it applies to all libraries/applications using Json.NET.
Hope this helps.
Massive is a tiny, single-file, data access wrapper around SQL Server. It makes heavy use of System.Dynamic which means that it’s very flexible. It’s really a wrapper which does not get in your way. No extra assemblies, just as single file which you can drop in your solution.
Since Massive is SQL Server only and I work with MySQL, I’ve forked it to add MySQL support.
You can find the repository over at GitHub. There is also a NuGet package available, named Massive.MySQL which has MySQL.Data as a dependency. This means that you only need to do the following to get a working data access wrapper:
Install-Package Massive.MySQL
This will download Massive.MySQL, add it to your project, and download MySQL.Data (which is the only dependency).
I’m quoting the original readme for usage:
Let’s say we have a table named “Products”. You create a class like this:
public class Products:DynamicModel { public Products() : base("northwind") { PrimaryKeyField = "ProductID"; } }
Now you can query thus:
var table = new Products(); //grab all the products var products = table.All(); //just grab from category 4. This uses named parameters var productsFour = table.All(columns: "ProductName as Name", where: "WHERE categoryID=@0",args: 4);
You can also run ad-hoc queries as needed:
var result = tbl.Query("SELECT * FROM Categories");
Of course, Massive also supports updates and inserts:
var table = new Products(); var poopy = new {ProductName = "Chicken Fingers"}; //update Product with ProductID = 12 to have a ProductName of "Chicken Fingers" table.Update(poopy, 12);
//pretend we have a class like Products but it's called Categories var table = new Categories(); //do it up - the new ID will be returned from the query var newID = table.Insert(new {CategoryName = "Buck Fify Stuff", Description = "Things I like"});
For more information, please see the README file.
Thank you Rob for your efforts put into this, it’s a great tool.
This post is just a quick tip on how to serialize keys in lowercase using Json.NET. The secret is to use a custom ContractResolver. Definition:
public class LowercaseContractResolver : DefaultContractResolver { protected override string ResolvePropertyName(string propertyName) { return propertyName.ToLower(); } }
Usage:
var settings = new JsonSerializerSettings(); settings.ContractResolver = new LowercaseContractResolver(); var json = JsonConvert.SerializeObject(authority, Formatting.Indented, settings);
This will ensure that all keys are in lowercase, even when properties are camelCased etc.
Edit: I’m not satisfied at all by the API below. Hopefully i will find time to give it some love, perhaps using dynamics.
I’m not that fond of the official GData library and especially not the Analytics wrapper. Since i only needed a small subset of the function of all available features, i’ve developed my own library.
Let me introduce AnalyticsApi.
AnalyticsApi is still in a very early stage but it’s used in production in one of our projects at work. My goal is to create a easy to use, strongly typed library. It should be both unit- and integration testable.
It has a fluent, easy to use, interface:
var dashboard = new AnalyticsService(new AnalyticsDataProvider(HttpWrapper.Standard)) .Username("username@gmail.com") .Password("password") .Logon() .Profile(1312231) .GetDashboard("2011-01-01", "2011-01-30"); Console.WriteLine("PageViews: {0}", dashboard.PageViews); Console.WriteLine("Bouncrate: {0}", dashboard.Bouncrate); Console.WriteLine("Visits: {0}", dashboard.Visits);
The AnalyticsService has a dependency on a AnalyticsDataProvider which allows you to mock the results and test it in isolation.
Each request is defined as a request map, similar to FluentNHibernate. A request for dashboard data would be defined as the following:
class DashboardApiMap : ApiMap<DashboardRequest> { public DashboardApiMap() { Map(x => x.Visits, "ga:visits"); Map(x => x.PageViews, "ga:pageviews"); Map(x => x.Bounces, "ga:bounces"); Map(x => x.Entrances, "ga:entrances"); Map(x => x.TimeOnSite, "ga:timeonsite"); Map(x => x.NewVisits, "ga:newvisits"); Map(x => x.StartDate, "startDate", ElementLevel.FeedLevel); Map(x => x.EndDate, "endDate", ElementLevel.FeedLevel); } }
DashboardRequest is just a simple POCO with some methods for calculation for example calculating the bounce rate.
One thing i’m aming to fix pretty soon is rate limit checks and make it even easier to define new requests. I’m thinking about using extension methods for this. The AnalyticsService should also implicitly use the “live” AnalyticsDataProvider if nothing else is specified.
This library is far from finished, but i’m going to give it some love pretty soon.
Check out AnalyticsApi at GitHub.
Sometimes it’s useful to run PHP scripts via a CLI (mostly when doing long-running scripts). If you’re on Windows and using WAMP, you already have a CLI version available.
Just point your terminal to php.exe which is typically located under C:\wamp\bin\php\php-5.3.0\php.exe and use the -f flag to indicate that you want to run a file. So, to run PHP under CLI:
C:\wamp\bin\php\php-5.3.0\php.exe -f C:\wamp\www\index.php
Here’s a simple function that checks if PHP is running via CLI or web:
function is_cli() { return php_sapi_name() === 'cli' && empty($_SERVER['REMOTE_ADDR']); }
I’m in the process of creating a PHP wrapper/library around Twitters streaming API. The wrapper should be able to track a number of keywords or a user with as minimal effort as possible.
Tweetstream was made for this.
The current version works like this:
$streamer = new TweetStream(); $streamer->setCredentials('alexnyquist', 'password'); $streamer->setCallback(function($message) { $message = sprintf('%s says: %s', $message->user->screen_name, $message->text); file_put_contents('log.txt', $message . PHP_EOL, FILE_APPEND); // Write tweets to file }); $streamer->track('twitter', 'foobar');
This will track all tweets containing twitter or foobar and log the author and the full message to log.txt.
Tweetstream is still in a early stage but it’s actively developed. The next thing to do is to handle hits of rate limit.
I want to keep this really clean and simple. Currently, Tweetstream depends on PHP 5.3.
Tweetstream is completely open source and available at Tweetstream on GitHub.
My current project at work includes doing some extensive date and time computations in JavaScript. I need to add X days to a date, subtract a month, add an hour etc. Initially, I started out by extending the built in Date object.
It turned out i had reinvented the weel (once again).
I found a open-source library which does exactly what I want. I’m talking about Datejs. DateJs has actually been around for a while (it’s a shame i’ve never heard of it before) and it’s actively maintained.
DateJs has a nice fluent interface, this is straight from their homepage:
// What date is next thrusday? Date.today().next().thursday(); // Add 3 days to Today Date.today().add(3).days(); // Is today Friday? Date.today().is().friday(); // Number fun (3).days().ago(); // 6 months from now var n = 6; n.months().fromNow(); // Convert text into Date Date.parse('today'); Date.parse('t + 5 d'); // today + 5 days Date.parse('next thursday');
This is absolutely a library I recommend using if you need to work with date and time in JavaScript. Be sure to check out their getting started guide.
It’s no secret i spend a lot (probably too much) of my time over at StackOverflow.com. My favorite tags is C# and a question that pops up frequently is how to parse HTML in C#.
The recommended way to parse HTML in C# is to parse the DOM (document object model) and not use regular expressions. I’m not going to rant over why not to use regexp, there’s already too much of this out there.
My library of choice when it comes to parsing HTML in C# is HtmlAgilityPack.It allows you to query your document with XPATH or just traverse all elements.
I prefer querying by XPATH since it’s an efficent and maintainable method. Here’s an example of parsing all the links on stackoverflow.com:
class Program { static void Main(string[] args) { var web = new HtmlWeb(); var doc = web.Load("http://www.stackoverflow.com"); var nodes = doc.DocumentNode.SelectNodes("//a[@href]"); foreach (var node in nodes) { Console.WriteLine(node.InnerHtml); } } }
This is from a answer i posted at StackOverflow.
This is a clean and straight forward way to do it. First, we instantiate a HtmlWeb and load our URI. We then query the document for all elements satisfied by our XPATH “//a[@href]“. This XPATH will fetch all a element which is descendants of our root element and has a href attribute.
Finally we loop through our results and print out the anchor text of our liks.
One thing to look out for when parsing HTML with HtmlAgilityPack is that DocumentNode.SelectSingleNodes(“..”) returns null when no results are found. Personally, i think returning a empty list would be better. This means that you should always check nodes for null before iterating over it.
This is a simple way to parse HTML in C# using HtmlAgilityPack.