WebApi POST needs a little help

Some of my web apps use ASP.Net WebApi Controllers. They work a lot like MVC Controllers but they’re limited to HTTP Verbs such as Get, Post, Put, Delete and instead of returning a View, they return Data formatted as XML or JSON, or they might perform data operations such as INSERT, UPDATE, DELETE. Usually you’d call these via HttpRequest, or AJAX, or whatever you want to use over HTTP, but sometimes I just want to call the ApiControllers directly from an MVC Controller, treating it like a DAL, and just skip the whole HTTP Request thing. (Not sure if that’s kosher, but it works. Let me know if you think calling ApiController methods directly from code is a bad idea).

Anyway, this works pretty good until you call a POST method, which has some standards and handling which, if not obliged, will throw errors when your HTTP Request is found to be null.

I found this article by Peter Provost on Unit Testing of ApiControllers, which addresses this problem and provides a nice solution.

Taking his advice, I wrote a an extension method for ApiController that seems to get me past any errors when calling Post() on my ApiControllers.

        public static void InitializePost(this ApiController controller)
        {
            var config = new HttpConfiguration();            
            var request = new HttpRequestMessage(HttpMethod.Post, "http://MOCKhost/api/MOCKController");
            var route = config.Routes.MapHttpRoute("DefaultApi", "api/{controller}/{id}");
            var routeData = new HttpRouteData(route, new HttpRouteValueDictionary { { "controller", "MOCK" } });
            
            controller.ControllerContext = new HttpControllerContext(config, routeData, request);
            controller.Request = request;
            controller.Request.Properties[HttpPropertyKeys.HttpConfigurationKey] = config;
            controller.Request.Properties[HttpPropertyKeys.HttpRouteDataKey] = routeData;
        }

Here is an example that shows how to initialize and call a Post method on an ApiController directly. In this case I’m calling it from within an MVC Controller.


  [HttpPost]
  public ActionResult Create(SomeViewModel viewModel)
  {
    var _api = new SomeApiControllerThatCanInsertObjectsIntoDB();
    _api.InitializePost();
    _api.Post(viewModel.SelectedObjectToInsertIntoDB);
    return RedirectToAction("Index");
  }

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Pair your laptop with YouTube

If you have a smart TV hooked up to the internet, chances are there’s a YouTube app installed. It’s cool until you have to enter a keyword search or do any kind of browsing that is awkward and error-prone on a TV remote. The YouTube app on my Samsung TV addresses this problem beautifully by providing a screen that allows you to “Pair” your TV with a “Mobile Device” (See How-To video). I have an iPhone, and this worked OK, but more often than not I’ll be sitting on the couch with my laptop on my knee (you thought I was gonna say “lap” didn’t you), wishing it was ‘pair-able’ with my TV’s YouTube somehow. Problem is, if you try to go to youtube.com/pair on your laptop, they simply don’t allow you to pair up with your TV. Rats.

(Side note… ultimately, what I REALLY want is wireless screen sharing with my TV, or a seamless solution that makes my computer treat my smart TV like a second monitor, but so far, there does not appear to be such a thing without investing in additional hardware or using a direct HDMI cable connection. Side-side note: it’s fairly easy to share media files with your smart TV wirelessly by running a DLNA Media Server on your computer).

So back to pairing a laptop with YouTube on TV…

Open Chrome on your computer, then open the Developer tool bar.

chromeDevMenu

When the Developer tools pane shows up, click on the little gear in the lower right hand corner:

chromeDevSettingsGear

The Settings pane will pop up, and you can click “Overrides” and check “User Agent”, setting the User Agent menu to something like “Android … Galaxy…” or some mobile device.

overrideUserAgent

Now when you navigate your browser to YouTube.com/Pair, they will allow you to enter the code to pair your ‘device’ to your TV.

3 Comments

  1. Your content contains truly nice and helpful info. I am very glad that you just shared this useful info with us. Please keep us informed when you create new post. If you have a couple of seconds, I would appreciate it if you could check out my blog on car history check, I really appreciate it!

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Turning off the Spigot on Vuze

I used  to use Vuze (sorry, reading that out loud just sounded like a tongue twister) to network my mac laptop media to my TV. It was kind of cool being able to get a video to play on my tv without connecting any cables, but the first draw back was that my tv (Samsung) couldn’t pause the video (seems like a HUGE oversight there).

Anyway, I just downloaded an update to Vuze and suddenly I see that Yahoo is my search engine on all my browsers (Safari, Chrome, and Firefox), and there is a stupid Amazon and eBay button (provided by Spigot) on the browser tool bars too. I checked some online forums and found plenty of other folks in the same predicament.

I’m uninstalling Vuze and will never use it again. I will also avoid Yahoo and Ebay like the plague. Amazon… shoot, I love Amazon, so for now I’ll try to get in touch and let them know that Vuze and Spigot are messing with people’s browsers and tarnishing their brand in the process.

So weird that this happened right after I listened to Seth Godin talk about Permission Marketing.

2 Comments

  1. Pingback: Pair your laptop with YouTube | The Kitchen Sync

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

The free market at work

So I read this great blog post by David Heinemeier Hansson.

then I went out and immediately ordered the book. I found dozens under $15. Here’s my receipt for the one I picked:


Order #: 104-8101664-7051438
Shipping Method: Standard Shipping
Items: $7.49
Shipping & Handling: $3.99
——
Total before tax: $11.48
Estimated tax to be collected:* $0.00
——
Order Total: $11.48

Delivery estimate: Jan. 3, 2013 – Jan. 18, 2013

1 “Are Your Lights On?: How to Figure Out What the Problem Really Is”
Donald C. Gause; Gerald M. Weinberg; Paperback; $7.49
In Stock
Sold by: bordeebook


COOL!

Well, today I just got this cancellation:


We’re writing to inform you that your order from bordeebook has been canceled because the item you purchased is out of stock. Please return and place your order again at a later time. We’re sorry for the inconvenience this has caused. In most cases, you pay for items when we ship them to you, so you won’t be charged for items that are canceled.*

Order Details

Order #104-8101664-7051438

Placed on Wednesday, December 26, 2012

  • Are Your Lights On?: How to Figure Out What the Problem Really Is

Sold by bordeebook

Cancel Reason: Out of Stock


OK, no worries. I’ll just pop on over to Amazon and get one of the dozens of other copies available for roughly $10.

DOH!


Used

1-15 of 16 offers

Price + Shipping Condition
$25.08

+ $3.99shipping
Used – Very Good
$49.59

+ $3.99shipping
Used – Good
$49.61

+ $3.99shipping
Used – Very Good
$49.61

+ $3.99shipping
Used – Very Good
$52.58

+ $3.99shipping
Used – Like New
$52.60

+ $3.99shipping
Used – Like New
$53.53

+ $3.99shipping
Used – Good
$67.32

+ $3.99shipping
Used – Very Good
$68.70

+ $3.99shipping
Used – Like New
$99.75

+ $3.99shipping
Used – Acceptable
$108.70

+ $3.99shipping
Used – Good
$749.99

+ $3.99shipping
Used – Like New
$749.99

+ $3.99shipping
Used – Good
$749.99

+ $3.99shipping
Used – Acceptable
$999.00

+ $3.99shipping
Used – Like New

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Where is “Run Custom Tool”?

I’m working on some old stuff at work and ran across this problem. I was bringing in an XSD file (which is a definition of a strongly typed dataset). I right clicked on the file in VS2005 and expected to see “Run Custom Tool” in the context menu (which will instruct VS to use the definition to generate classes for your dataset, datatables, dataadapters). Nope. Not there. Hmmm.

This helped:

http://social.msdn.microsoft.com/Forums/en/csharpgeneral/thread/a8ae1fdc-44c4-4178-aeb4-4ed96cc554d6

(Thanks BonnieB!)

Click the XSD file in the Solution Explorer, and in properties. under “Custom Tool” enter “MSDataSetGenerator”.

Now “Run Custom Tool” is available in the context menu.

Sweet.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Logger doesn’t work in scheduled task?

It’s weird. I deployed a console application which has a logging feature that writes to a text file. By default, the log file is in the same directory as the executable. Ok, so if I remote to the server and double click the executable, everything works fine and a nice log file appears (with today’s date) and tracing information shows up in there and all is right with the world.

Then I schedule the console app to be run automatically every so often. It seems to run fine, I can even run the scheduled task manually from the Task Scheduler UI, but the log file NEVER appears (or if it exists it’s never updated). Hmmmmmm.

Finally I noticed a curious field on the Task Scheduler’s “Actions” tab. It’s a text box labeled, “Start in (optional):”

Well, don’t be fooled, it’s certainly NOT optional as far as getting my logger to work. I went ahead and filled that in with the path to my console app and now my log files are working.

So… what happened all those times the program was running and NO log file was being generated? Did they all end up in some weird ‘relative’ location (a quick search didn’t turn up anything)? And why didn’t the logger complain when it tried logging to… where? Anyway it’s working now, but the ignorance is gnawing at me.

One Comment

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Reset IE user/password for Intranet site

Ever waste a LOT of time on something you just KNOW is being controlled by some obscure little check box squirled away on some hidden dialog?

I logged into a local intranet site recently with some test credentials (don’t ask me how). From that point on I could NOT get the site to see me as anything but the test user. I tried resetting the browser, clearing the cache (including the settings that say “username/password”). Nothing worked.

God bless Stack overflow:

http://stackoverflow.com/questions/6451001/integrated-windows-authentication-showing-wrong-loggedin-user

It turned out to be in the windows control panel. Nothing to do with the browser really.

  1. Click Start, Settings, Control Panel, User Accounts.
  2. Click the Advanced tab.
  3. Click Manage Passwords.
  4. Find the entry in the list the corresponds to the site(s) where you’re seeing this behavior. Remove it

Back to work…

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Bob Dylan

I was watching No Direction Home last night. As we glide into the next political season, I found this quote of Bob’s really transcending:

There’s no black and white, left and right to me anymore; there’s only up and down and down is very close to the ground. And I’m trying to go up without thinking about anything trivial such as politics.

Out of context, these seem like wise words. But the amazing thing is, he was telling this to a bunch of progressive political activists who were hoping to associate him with their brand by presenting him with an award. That quote was the tamest thing he said that night. He also let them know he found them irrelevant. He went on to express empathy for Lee Harvey Oswald. E gad! The whole story (and after shock) is nicely documented on the Corliss Lamont Website. There’s a copy of the apology letter, where he really doubles down, bursting with so many befuddling and poetic pronouncements, it forces you to wonder if he isn’t either an old testament prophet, or a raving lunatic.

Anyway, I too have been struggling with the instinct to speak my wretched mind vs. hold my peace (hey check that out! I just equated myself with Bob Dylan!! Not to shabby… or humble). It kind of comes down to this for me… Every once in a while I have nagging regret, the kind of regret that keep me awake at night. It stems from conversations I have with people (usually at work) where I find myself being too agreeable, or being dishonest. The part that keeps me awake is playing the tapes back in my mind, and getting to the part in the conversation where I spin the truth, or fail to provide a persuasive argument, or cave in to pressure, or chicken out, or lie.

I’m getting too old for this kind of regret. I like peaceful sleep. I’m going to be more honest, and I’m going to be less agreeable, and I’m going to be less regretful (or discover some other kind of regret I can begin rooting out of my life).

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Walter Bagehot

I work in a bank. I was struggling to offer a pithy quote to a boss who is retiring soon. I came across this English chap, Walter Bagehot from the 1800s, whose ideas about banking endure to this day. He was also the editor for The Economist. Good stuff!

The greatest mistake is trying to be more agreeable than you can be.

The greatest pleasure in life is doing what people say you cannot do.

The real essence of work is concentrated energy.

You may talk of the tyranny of Nero and Tiberius; but the real tyranny is the tyranny of your next-door neighbor.

All the best stories in the world are but one story in reality – the story of escape. It is the only thing which interests us all and at all times, how to escape.

It is good to be without vices, but it is not good to be without temptations.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

My new favorite line of JQuery

//alternate row appearance
$(“table > tbody tr:odd”).addClass(“odd”);

A close runner-up is this:

//bump up the contents of cells by removing first BR
$(“td.list-of-stuff-delimited-with-br”).find(“br:first”).remove();

I normally would handle stuff like this on the server side, but these save me the trouble, and considering it’s a presentation layer thing, doing it on the client just feels right.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>