Could not load file or assembly Newtonsoft.Json

I’ve run into this problem a few times, usually when source control is involved. 

-Delete the package from you /packages folder

-open nuget package manager, it will notify that things are out of sync- click the resolve button. 

-if you have version conflicts, edit your dependentAssembly bindingRedirect so that the older version(s) are redirected to the newer. 

-You may also try uninstalling using nuget and reinstalling, but this usually doesn’t fix everything. 

Change brightness of web rgb colors

Recently needed to use an existing web color (like, the #rrggbb color definitions) and produce a “lighter” version of it. I found some javascript code to do this, which changed the “luminance” of a given web color, at this url: http://www.sitepoint.com/javascript-generate-lighter-darker-color/

So this is a .Net translation of this code: 

        public static string ColorLuminance(string hex, float lum)
        {

            // validate hex string
            hex = new Regex(@"[^0-9a-f]", RegexOptions.None).Replace(hex, "");
            //if abc, make aabbcc
            if (hex.Length < 6)
            {
                var hchr = hex.ToCharArray();
                hex = new string(new char[] { hchr[0], hchr[0], hchr[1], hchr[1], hchr[2], hchr[2] });
            }

            // convert to decimal and change luminosity
            string rgb = "#";
            for (int i = 0; i < 3; i++)
            {
                int c = Int32.Parse(hex.Substring(i * 2, 2), NumberStyles.HexNumber);
                string sc = Convert.ToInt32(Math.Round(Math.Min(Math.Max(0, c + (c * lum)), 255))).ToString("X2");
                rgb += sc; // ("00" + sc).Substring(sc.Length);
            }
            return rgb;
        }

Null propagating operator in C# 6.0

Something I’ve been wanting for years in .Net (c# specifically) is a cleaner way to detect null objects before trying to access properties or methonds on said objects. Just today I noticed that C# 6.0 (along with Visual Studio 2014) will finally make this a bit easier. 

In the past, before you access a property on an object, you would want to make sure it’s not null first. So instead of doing: 

var val = myobject.myValue; 

You would want to add null checking code like this: 

 

if(myObject != null){

   var val = myObject.myValue; 

}

Multiply this code by thousands of times, and it becomes a huge headache to look at, maintain, or even test. 

So: Null propagation operator (or, null propagating operator) to the rescue. We can replace the “.” with a “?.” operator to have the system check the object for null prior to accessing a property. So our c# 6.0 version of the above will now look like this: 

var val = myObject?.myValue; 

val will take on the type of myValue, or rather, a nullable version of the type of myValue. So if myValue is an int, val will be an int?. 

We can also combine this with the null coalescing operator to provide a default value, and keep val as a normal int:

var val = myObject?.myValue ?? 0; 

Looking forward to using this in future projects. 

EXI for .Net

EXI is a binary representation for xml data, and is a standard defined by the W3C. The name stands for “Efficient XML Interchange”, and apparently is the (semi?)new hot thing in making xml more compact and efficient.

Common approaches to compressing xml typically take the route of creating some non-standard method of compacting the data to remove or reduce the use of all those huge tags. For the uninitiated (not you!), here is a quick example:

<SomeReallyBigTag>
<NestedTagInside>
1.234
</NestTagInside>
</SomeReallyBigTag>

So all that extra beginning, ending, and nested tags really just contain a single little value of 1.234. Repeat this thousands or millions of times, and it’s easy to see how xml files are way larger than they need to be, often by an order of magnitude.

Many web-based systems nowdays just use gzip to compress xml data, and this works, but it requires a relatively large amount of cpu usage. Other approaches seek to reduce the size or usage of all the tags in xml, but result in some new proprietary format… getting rid of proprietary formats was the reason we went to xml in the first place!

In 2011, W3C released the final standard for EXI, so now there is a new standard which offers an open, highly optimized binary representation of XML data (see the spec here: http://www.w3.org/TR/exi/#encodingDatatypes ). Since it is a published and open standard, it doesn’t suffer from being proprietary. It is also fully compatible with the xml standard, so it directly converts from and to any xml file. But best of all- without requiring a cpu-intensive compression routine, it can often meet or surpass the level of compression offered by gzip in the past.

My own reason for being excited about this standard is, in the past I’d looked into using a relatively open binary serialization standard called protocol buffers as a candidate for efficiently storing application data files. These can (and do) work, but it would be much nicer to have the files also have a direct mapping to an xml equivalent and all the associated support for schemas, nested structures, validations, and interoperability.

So, my questions:

-.Net… where is the implementation for it? I’m looking forward to trying this on some xml based projects, but I have only seen one commercial implementation of EXI in .Net so far. I see a java one out there.

-HTML/SGML – can it be applied to these as well?

-support, best practices for webservices?

-can exi e used over ajax calls?

Update: skeletal project added here for a .net implementation- http://exi.codeplex.com/

Update 2: a .net and java exi project is on sourceforge here: https://sourceforge.net/projects/openexi/

 

DateTime and DateTimeOffset

The DateTime object is heavily used in .Net coding, and it includes a “Kind” property which basically indicates whether the object is representing a UTC datetime or one that is localized to the current timezone. But, suppose you want to store a DateTime that also keeps track of a different timezone- for instance, if you wanted to capture the “local time” of a remote user of your software, and it’s important to know that it was 6PM at their particular spot. This is where a traditional DateTime falls short- we cannot specify a specific timezone that is different from our own local one, and any attempt to do so just results in it being translated to our local zone.

What is a timezone anyway? Aside from the names and various daylight savings rules etc, a timezone is just a simple offset of the hours (and minutes) from the core UTC date.

.Net provides us with another class: The DateTimeOffset. We can use this to store normal Date and Time info, but also includes a TimeSpan property for the amount of offset, so now we can store that additional bit of information with our datetime objects and capture the remote users’ timezone offset info with each date.

The nice thing about DateTimeOffsets is you can still easily convert them back into normal DateTime’s- either to a localized date or a UTC one. Simply utilize the .DateTime or UtcDateTime propertys to access the converted DateTime objects.

Send email from .Net – MAPI

You need to send an email from your thick client .Net app (winforms or WPF), but don’t want to mess with using MailMessage and configuring it to use a remote server etc.

Instead, you can use MAPI and just pop open a new message using your default installed email client (often outlook, but any mapi compliant email client will work).

This article on codeproject gives excellent coverage of this topic http://www.codeproject.com/Articles/17561/Programmatically-adding-attachments-to-emails-in-C

Beware that this is a good thing to use for occasional emails, not for heavy sending. MAPI has some known issues with memory management when called via interop from .Net, so if you make heavy use of it you will likely crash.

Also, since MAPI only works with locally installed email clients, it will not work with a web based one (ie, gmail).

 

Open URL using LinkLabel

In Winforms, you have a LinkLabel control – which one might be interested in using to open a browser with a url (perhaps?).

One way to accomplish this is to add the LinkClicked event handler, and have it execute this:

System.Diagnostics.Process.Start(http://www.amazify.com/);  //Put your own URL in there

WPF uses a different control and method of handling links, I’ll add that content here once I go find it again.

 

 

WPF Printing Performance and PDF

Printing in WPF has been a big thorn for me over the last few years, it just feels like you have to learn everything the hard way through extensive trial and error… and better write it down or you’ll be re-learning it again later.

One hard lesson for me has been printing a lot of vector based graphics in a particular application. Early on the data would wind up rasterizing for various reasons and creating massive rasterized data pages, which when sent to the printer would cloe things way down and create ugly printouts (someone has a case of the jaggies). Even PDF printing suffered from this, so instead of a nice lightweight PDF with some lines and text drawn on the page, it would barf out a giant file with every page represented in ugly rasterized pixels.

The first thing to make sure of if you fighting this is to make sure any element you are printing doesnt use any form of transparency (opacity). I had an element sneak back into my app recently which had text printed with a background color with opacity set to 35%. Not sure if this is the fault of WPF, PDF, or the particular Acrobat software I’m using, but even a single element with this opacity setting on a page will cause the entire page to be rasterized… not just the element itself, as one might expect.

The other side effect of this rasterization is slow printing. Even printing to a local PDF file can take over a minute PER PAGE on my high-end laptop. So if your print times seem astronomical, you’re likely running into this same issue.

I recall a number of other weird issues encountered in the past, I’ll copy them here if I can find them again. But for now, note to self: NO opacity variations.

 

Update:

I found out today another item that can cause rasterization – if you have a canvas with clipping turned on, and items hanging out beyond the edge of the canvas. Doesnt seem to always do it though, it might only occur if the items clipped by the canvas extend beyond the edge of the printed page. I experienced this again today and now I’ll have to figure out yet another workaround for it.

screwturn wiki on .net 4 and extensionless urls

Screwturn wiki is (pretty) good software, but unfortunately seems to be mired in some of the older asp.net technologies. There are a LOT of moving parts under the hood, so trying to modernize it might be a challenge. I wanted to update it enough to run on .Net 4.0, and specifically to enable extensionless URL’s.. why have that silly ashx hanging off the end of each url nowdays? This has proven to be a bit of challenge due to the aformentioned many moving parts, so following is my current progress on this attempt-  the target website for this will remain nameless for now, to protect it from your prying eyes 😉

 

1. download the source version of screwturn

2. open it is visual studio 2010 and upgrade the project to .net 4.

3. when you try to compile, there’s a number of tests that fail and prevent compilation. they appear easy to fix, theyre all just parameter names that have changed, so update them to match.

4. compile and run the app. create a couple pages. notice when you go to the pages, they end in .ashx.

5. open the Core project, the Settings.cs file, and find the PageExtension propterty. edit it to return “” instead “.ashx”

6. open Core\ReverseFormatter.cs edit the Regex named PageLinkRegex to remove the \.ashx portion (verify this is needed)

7. open core\urltools.cs, RouteCurrentRequest() – change the line-

  if(ext != “ashx” && ext != “aspx”) return;

so that “ashx” is now “”

in the same method, find if(ext.Equals(“ashx”)) and change it to “”

 

It makes sense to remove the /MainPage url as well, since it is the same as / .

8. remove the static link to MainPage in /public/sidebar.cs, or just edit it out via the admin panel, find and edit the sidebar. any other places it shows up in static content can be edited this way.

9. dynamic links generated for the mainpage need to be fixed too. (I have not completed this yet, will update here when done. Add a comment if you find a quick way to do this)

 

x. You might need to backup the web.config and rename the web.release.config file to web.config instead, seems the 4.0 upgrade mixes things up a bit.

x. To enable .net 4.0, in the web.config, make sure the compilation tag has targetframework=”4.0″ and the provdierOption name=”CompilerVersion” = v4.0

x. Comment out (or delete) all the sectiongroups at the top of the web.config… these don’t like .net 4 for some reason.

x. enable “unsafe” posts of html – editing pages will blog up on save currently, due to XSS restrictions in 4.0.  Add requestValidationMode=”2.0″ to the httpRuntime tag in web.config

 

Many places in the web.config still reference 3.5 control versions, so I may try to upgrade some of these in the future, but things are running for now and that’s good enough.

 

 

Please add any feedback you have regarding this, thanks.  

 

Next episode: how to convert screwturn to mvc 3 and razor. I kid, i kid!

 

 

EF Code-First first look

Modifying a project built using EF Code First, and so far I like what I see. The whole POCO concept seems to work well, especially for a smaller simpler project. I learned a lot about it from this link: http://weblogs.asp.net/scottgu/archive/2010/07/16/code-first-development-with-entity-framework-4.aspx

I also like how you can eaisly define test data to use in place of the database, so that during testing and debugging you don’t have to mess around with a “real” database- you can launch from the same start data every time, or create custom test cases etc.