Add Code Behind to a Resource Dictionary

I recently used a Resource Dictionary and wanted to be able to tweak the xaml components on it behind the scenes. This can be accomplished fairly easily:

  1. In your project add a new class file. Give it the same name as the xaml.
  2. In the newly created file override the contents of the namespace with this code:
  3. Next, go to your <ResourceDictionary> tag in the xaml file. Add this property with the appropriate namespace and name: x:Class="namespace.classname"

Now the two should be linked up. In Visual Studio, however, they will not be nested like normal xaml files. This bugged me. I read online that the csproj file can be edited in notepad to accomplish this. I tried and for some reason I couldn’t get it to take. I did have success with VSCommands. It is an install that adds extra features to Visual Studio. Once installed select the xaml and cs with your mouse in the tree. Right-click and choose Group Items. Choose the xaml as the root item to be conventional. Now Solution Explorer should show them as paired.

Read More

Invert the Transparency in an Image with Gimp

You can easily invert the transparent parts of an image with Gimp. Gimp is an open source Photoshop alternative.

Follow these steps:
  1. Choose Colors -> Components -> Decompose from the menu and set Color model to RGBA.
  2. A new image is opened with all color channels (including alpha channel) decomposed as single layers.
  3. Select the layer alpha and choose Colors -> Invert from the menu.
  4. Choose Colors -> Components -> Compose from the menu, set Color model to RGBA and make sure the layers are correctly mapped to the channels (should default correctly if you did not reorder the layers)

It will open a few new Gimp tabs but it will, indeed, invert the transparent areas of the image. This worked well for me on an image of a single color with transparency.

Read More

How to Queue up Method Calls in C#

First you need to instantiate a List of type Action:

Next, we will add methods to the list. We do this through Lambda Expressions using a specific syntax: () => { TestFunc("data") };

With this technique local methods can be stored along with parameters for future execution. In the example below you can see two Console.WriteLine statements. But since the first method is housed in the expression it does not fire until executed later. However, the subsequent one will fire immediately and be listed first in the output tab of Visual Studio:

To fire off each method loop through and use function params to execute:

Chad

Read More

Perform Scheduled Table Maintenance in SQL Server

Have you ever had a need to do routine maintenance on your database tables? For instance, moving older records to history, fixing anomalies, removing bad/incomplete data, updating flags under certain conditions, etc. These types of recurrent tasks can be implemented easily within SQL Server Management Studio (SSMS). With an SSMS component known as SQL Server Agent you can execute T-SQL statements on a repetitive schedule.

SQL Server Agent can be found at the bottom of the Object Explorer pane. Right-click on it and select New > Job. A window pops up to specify the name of your job with some other defaults. Notice the options on the left-hand side. This tutorial touches on the Steps and Schedules options.

Click on Steps. In the window that appears click the New button. A dialog will appear as follows:

SQL Agent Steps New Dialog

In the dialog you can select your database and enter T-SQL statements to perform the job. For example:
or even a stored procedure:

I recently created a job to maintain several tables. Then for each step I provided the T-SQL needed to do my maintenance on each table. Steps can be deleted individually and re-ordered.

Next, you need to set the schedule. Click on Schedules and click the New button. There are many options here to customize the run time to your liking:

SQL Agent Schedule New Dialog

Finally, save the job to make it live. And that’s it. You have created a table in an environment that can perform further automation. There is obviously many more options to explore in SQL Agent. This is just a taste.

Read More

Better Image Previews in HTML5

When working with an uploader it’s nice to show image previews of files before the actual upload takes place. It looks nice and verifies to the user that the correct files have been selected from their computer. Since they are local files people expect them to render immediately. This article details how I accomplished this in HTML5 without the use of flash, silverlight or any other dependent technology.

Over the last several weeks I’ve been researching Plupload for image uploads. They have a nice, ready-made widget but it didn’t quite capture the look and feel that was requested of me. I opted to rely on their API and do the interfacing myself, which included developing my own image previews.

My main requirement was for them to render quick, even with 20MB files. My project was tailored to professional photographers so big files were expected. Searching the web I tried a few techniques that seemed to perform well with small files but would max out resources for larger ones. Things became choppy. A page quickly looks cheap when buttons don’t respond to clicks, content freezes intermediately, etc. I had to come up with a different solution. Along with speed, I also wanted to keep consistent thumbnail sizes and perform ideal cropping. Image quality had to be fair and recognizable as well.

The first function handles proportional resizing. I needed to be able to retrieve lower dimensions that didn’t skew or distort an image:
In most cases you’ll end up with one property that meets the max, but the other dimension will be much smaller than its max. For thumbnails to look clean you need a consistent width and height for every image. So that means you will likely need to crop. But you don’t necessarily want to perform that action on the entire image. Everything becomes so small it becomes hard to read. Rather grab a portion of the image as your scaling down. The following function utilizes proportionalResize as it determines the best coordinates for presenting your image:
Finally, we get to the meat of the process. This function returns the preview as a <canvas> element for your page. A <canvas> tag resembles an <img> tag with one big difference. Instead of loading the image from the network it’s drawn via JavaScript. It also has a built-in cropping mechanism. If using Plupload pass the result of file.getNative(). If not refer to this resource for getting a FileList of File objects to be passed in individually. This function calls the aforementioned centerCropFit function:
Originally, I tried Filereader.readAsDataURL() which converts the entire file into base64-encoded string. Whenever I assigned it to the src of an image it would cause a big memory hit for large files. Attempts to use window.setTimeout() to get around the heavy processing did not help. I also explored Web Workers to no avail. The URL.createObjectURL() method is the nitrous behind this process and allowed the tool to perform well for the user.

Read More

Ensuring Variable Integrity in Async Callback Functions

Callback functions to asynchronous requests may need to reference variables outside of itself. This can be problematic because those variables might not maintain the values you expect by the time the callback function fires. In the past I’ve dealt with this by writing my code as a string, concatenating my variable values, then using eval on it in the callback. I never liked this technique because it seemed amateur, risky and unreliable for complex scenarios. Recently I came across a clever solution that seems to work quite well:
Here we wrap a function around the code, and execute it immediately passing the target variables into it. In my example the variables are file and uploader. Next, we then have an inner function that keeps the meat of our code from being executed immediately. It will be executed in the callback of the asynchronous process…but can reference the variables passed to it’s wrapper function. In the example I have used the same variable names again (no need to change them). I believe the technique duplicates the variables into a local scope where its values can be maintained.

Here is a FIDDLE showcasing the technique. Enjoy.

Read More

Creating Animated Spinners with FontAwesome or Glyphicons

When creating JavaScript-rich applications an indicator is often used to give the user some certainty the page is working behind the scenes. If not present a user may question if the page has stalled or not. An animated GIF known as a spinner (or loader) is a common way to achieve this. An alternative to linking to a specific image is to use a popular font library that you may already be referencing by your application.

FontAwesome

The ability to create spinning icons in built into FontAwesome. Reference the library and create loaders easily:
The fa-spin class is what causes the rotation.

If you desire a different animation speed then you need a little CSS:
FYI: this CSS was constructed by studying the fa-spin class found in the FontAwesome stylesheet. Adjust the milliseconds (i.e., 1000ms) to alter the speed. Higher is slower, lower is faster. The default speed used by FontAwesome is 2000ms.

To use simply replace the fa-spin class with fa-spin-custom class that you have made:

Glyphicons

To use the font-library built into Bootstrap you will need to reference the above CSS as well:

That’s it. See a DEMO.
Enjoy.

Read More

Distinguish Between Posts & Pages in WordPress

Have you ever had a need to distinguish between pages and posts? At one time I had a request to show ads on all posts but to exclude pages. I’m sure if I dug deep enough I could find a plugin to do handle the cases, but it’s really not that hard to distinguish between the two.

If you prefer to do the checks in php you can reference some built in functions:
If you would rather use script then the following is what you need:

Read More

DataTable Fundamentals Part 2

Continuing from Part 1 of my study on the fundamentals of jQuery DataTables I wanted to discuss a few more topics. In these examples I’ll refer to the following DataTable object using DataTables version 1.10.0+:

Settings

At some point you may wish to retrieve your DataTable settings in a certain scenario or event. This can be done a couple different ways:
Simply loop through these setting objects to retrieve all properties and values

Custom Settings

The above methods will work fine to retrieve any official settings. But what if you want to set a custom setting that makes since only for your project? To get to the value of a custom attribute you must drill deeper into the settings object by viewing the oInit property:

Re-Retrieve DataTable Object

Depending on your scenario you may have lost or do not have access to the original DataTable object. You can re-retrieve it without interfering with the table:
Alternatively, if you don’t know the TABLE id either you can refer to a global variable. Then you can loop through them and re-retrieve the object like we did above:

Removing DataTables

Any good plugin that manipulates the DOM should have a way to remove all transformations and events it has made without removing the element itself. DataTables has this built in:
Note: I’ve also had success with jQuery’s $.empty function to remove all data and event handlers when called on the DataTable’s parent.

Search on Enter

One of my annoyances is how DataTables will search on every keystroke. This is great if you are dealing with local data but if you are relying on ajax requests for data then this can be a lot of strain on the server. To override this functionality do this:
Note: Bootstrap 3.0 seems to remove the clear button in the filter textbox

Read More

Floating Element that Scrolls with a Page

I occasionally have a need to show a note or message to a user that must remain in vision. When the page is scrolled vertically the message moves with the content. I usually want the message in the center of the window, to the right of my content. The movement must be fluid and responsive, not choppy like back in the early days. This can be accomplished with little effort:

We must add the markup that will be moved around. Of course, you can expand upon this however you see fit:
Now, with some CSS we style the element and set it’s position:
This will position the element at the middle, far-right of the page. Of course, this may look a little spaced-out if you have a high resolution. This bit of script will snug it up next to whatever element you wish:
This code does some adjustment based on resolution. It compares the browser’s viewport width to the space required to show your message next to the target element. If it exceeds then the message will just ride the right of your page, hovering any content it passes while scrolling. If it fits then it will be nestled next to it.

See a DEMO.

Thanks.

Read More