Tuesday, March 30, 2010

json2 date and function replacers

First off, you should probably visit Rick Strah's post here https://west-wind.com/Weblog/posts/729630.aspx#262650 first and then http://skysanders.net/subtext/archive/2010/02/18/wcf-to-json-dates-and-back-again.aspx because that is where I got this code, and idea from.

Like they state in their post, date serialization to and from from asmx or wcf services with json does not work right out of the box. Often times most developers will argue to just turn it into a string. Like so '20010/03/25' which works great if you are controlling both the client and the server code. Or if you are stubborn like me, and just want to pass native dates around without having to worry about converting them at the service level when you send data to the client or receive data.

Lastly I am using the json2 library from here http://www.json.org/ so I can get consistent results, regardless of browser. Using this code, you can easily pass native dates in and out of web services, and handle them as native js dates on the client.

I needed the function replacer to use with the jquery validate library http://bassistance.de/jquery-plugins/jquery-plugin-validation/ so that I could pass json objects to a web service using the validate remote rule. I will provide an example using this in a later post.

Example Usage:

var sd = new Date(2000, 1, 1);
var thing = {
plugin: 'json2',
version: 'tims hacked version',
customdata: function(bar) { return "foo"; },
startdate: sd
};
var encoded = JSON.stringifyAll(thing);
document.writeln(encoded);


This is what you should see in the browser: {"plugin":"json2","version":"tims hacked version","customdata":"foo","startdate":"/Date(949384800000-0000)/"}


(function json2Addons() {
// from https://west-wind.com/Weblog/posts/729630.aspx#262650
// with some fairly significant fixes by sky sanders
// http://skysanders.net/subtext/archive/2010/02/18/wcf-to-json-dates-and-back-again.aspx
//More code changes by Tim Cartwright - 3/25/2000, worked on the asmx date processing, also renamed the functions
//Tim Cartwright added new function replacer with new stringifyWithFuncs, and added stringifyAll
if (this.JSON && !this.JSON.parseWithDate) {

var reISO = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2}(?:\.\d*)?)Z$/;
//var reMsAjax = /^\/Date\((d|-|.*)\)[\/|\\]$/;
var reMsAjax = /Date\(([-+]?\d+[-+]?\d+)\)/;


JSON.parseWithDate = function(json) {
///
/// parses a JSON string and turns ISO or MSAJAX date strings
/// into native JS date objects
///

/// json with dates to parse
///
///

try {
var res = JSON.parse(json,
function(key, value) {
if (typeof value === 'string') {
var a = reISO.exec(value);
if (a) {
return new Date(Date.UTC(+a[1], +a[2] - 1, +a[3], +a[4], +a[5], +a[6]));
}
a = reMsAjax.exec(value);
if (a) {
//var b = a[1].split(/[-+,.]/);
//return new Date(b[0] ? +b[0] : 0 - +b[1]);
return new Date(eval(a[1]));
}
}
return value;
});
return res;
} catch (e) {
// orignal error thrown has no error message so rethrow with message
throw new Error("JSON content could not be parsed: " + e);
return null;
}
};
JSON.stringifyWithDate = function(json) {
///
/// Wcf specific stringify that encodes dates in the
/// a WCF compatible format ("/Date(9991231231)/")
/// Note: this format works ONLY with WCF.
/// ASMX can use ISO dates as of .NET 3.5 SP1
///

/// property name
/// value of the property

// choking on FF 3.6 date Wed Feb 24 2010 14:02:17 GMT-0700 (US Mountain Standard Time)
return JSON.stringify(json, DateReplacer)
};
JSON.stringifyWithFuncs = function(json) {
///
/// parses a JSON string and evaluates functions without passing any arguments.
/// !!WARNING!!: This has security risks. Do not run this on code you do not trust!
///

/// json with dates to parse
///
///
return JSON.stringify(json, FunctionReplacer);
};
JSON.stringifyAll = function(json) {
///
/// parses a JSON string and evaluates functions without passing any arguments also encodes
/// the date to a json compatible date format for the service.
/// !!WARNING!!: This has security risks. Do not run this on code you do not trust!
///
///

/// json with dates to parse
///
///
return JSON.stringify(json, AllReplacer);
};
JSON.jsonDateStringToDate = function(dtString) {
///
/// Converts a JSON ISO or MSAJAX string into a date object
///

/// Date String
///
var a = reISO.exec(dtString);
if (a)
return new Date(Date.UTC(+a[1], +a[2] - 1, +a[3], +a[4], +a[5], +a[6]));
a = reMsAjax.exec(dtString);
if (a) {
//var b = a[1].split(/[-,.]/);
//return new Date(+b[0]);
return new Date(eval(a[1]));
}
return null;
};

//tim c: created this to combine various replacers that I may come up with, so all can just call this one, and it forwards to the appropriates replacer
function AllReplacer(key, value) {
if (typeof value == "string") {
return DateReplacer(key, value);
} else if (typeof value == "function") {
return FunctionReplacer(key, value);
}
return value;
}

function DateReplacer(key, value) {
if (typeof value == "string") {
var a = reISO.exec(value);
if (a) {
// SKY: the '-0000' forces the serverside serializer into utc mode resulting in accurate dates.
var val = '/Date(' + new Date(Date.UTC(+a[1], +a[2] - 1, +a[3], +a[4], +a[5], +a[6])).getTime() + '-0000)/';

//SKY: rick, I don't think that asking for a JSON representation
// of an object should modify the state of the object. my 2 pesos.

//this[key] = val;

// this is the value that SHOULD be getting serialized but in the
// FF native JSON is ignoring this and serializing the member so I am guessing
// that is why rick is modifying the input object. gets the serialization job
// done properly but is a rather nasty undocumented side effect, in my opinion.
// I think it is probably better to overwrite native JSON with json2.js and
// get consistant results across platforms with out the need to modify the input
// UNLESS of course you are never going to need to use any of the objects that you
// serialize...
return val;
}
}
return value;
}

function FunctionReplacer(key, value) {
if (typeof value == "function") {
return value();
}
return value;
}
}
})();

Thursday, January 7, 2010

Outlook macro - Empty selected folder

I wrote this short little macro to have the ability to empty out any folder that is selected of mail items, just like the deleted items folder. Works on search folders as well. I created a button for it on my toolbar to make it easily runnable.


Sub EmptySelectedFolder()
Dim objFolder As Outlook.MAPIFolder

Set objFolder = Application.ActiveExplorer.CurrentFolder

If objFolder Is Nothing Then
MsgBox "No folder selected.", vbCritical
Exit Sub
End If

'make no the default button in case they skip reading my warning, and hit enter or space
If MsgBox("Are you sure you want to empty out this folder, and permanently delete all the mail?", vbYesNo Or vbDefaultButton2 Or vbQuestion) = vbYes Then
For i = objFolder.Items.Count To 1 Step -1
If (TypeOf objFolder.Items.Item(1) Is Outlook.MailItem) Then
objFolder.Items.Remove i 'using .remove as it deletes perm

If (i Mod 100) = 0 Then
DoEvents
End If
End If
Next
End If
End Sub

Thursday, September 17, 2009

Streaming Radio Tool Tip browser

I am a fan of streaming radio, however one thing has always bugged me. The fact that you have to use a browser window to listen to the streams. I would often accidentally close the browser window while listening to the stream, only to have to browse back the to site to re-open the stream. So I decided to write a browser wrapper application that you could then minimize to your windows systray. It is not a browser replacement, it is mainly designed to listen to streaming radio.

1) It minimizes to your systray, so no more accidentally closing the browser window.

2) It auto starts back up with the last station you were listening to. So you can put a shortcut to it in your start up.

3) It remembers the url history like IE or FF, but uses its own list, so you can have a short list of stations you listen to.

4) You can use it to listen to streaming radio web sites or you can use it to listen to web casts or even pandora online. I know there is a pandora desktop, but this provides an alternative.

Easiest way to use it, is open a station you listen to normally using a regular browser, then just copy the url into the tooltip browser app.

http://www.streamingradioguide.com/streaming-radio.php?format=1&radio-format=News/Talk

NOTE: I do not have a place to upload a setup yet, but I will be looking for a way to upload it so that others can install it.
















Image:
Image of using it to listen / watch a web cast (The BCast):

Wednesday, August 12, 2009

We can't do ObamaCare, but we SHOULD do something

Obama's health care plan is atrocious. It is an evil thing that if given birth will go a long way towards stripping the rights of the individual away like layers of an onion. If we stop HR 3200, should we stop there? I along with many others think no. We should pass some sort of reform. Here are my ideas for reform. Jut throwing them out in the far off chance someone likes them. These are all pie in the sky ideas to me, and just seem to be common sense to me. But then again I am not a congressman.
  • Remove the restrictions on health care insurers that prevent them from selling out of state policies. This has been touted by many, and should lead to more competition, and the ability for people to purchase health care from many other sources.
  • Stop insurers from denying people based on pre-existing conditions. However, this is a two-way street. Why did the original insurance carrier all of a sudden dump someone who was in dire need of care? If they dumped them because of a developing condition, the old insurance company should be liable to pay a premium to their new carrier. Too many people have paid long and hard into insurance policies only to have the rug yanked out from underneath them as they developed a life threatening condition.
  • Tort reform. Yes, some lawsuits are legitimate. However many are not. Our doctors and hospitals are drowning in the costs of their own insurance protecting against lawsuits. We need to punish those who are in the practice of frivolous lawsuits.
  • Tax breaks for employers based upon the total number of employees they employ that are also insured.This could be percentage based. I believe this would not only help employers give employees insurance, but may help them hire more workers.
  • Employers should be liable to carry a persons insurance exactly the same as it was during their employ for a prorated amount of time, or until they find a new job if that employee is laid off. For each year of employ the employer should be responsible to carry that persons insurance for 1 month. Fully covered by the employer. This cost will be offset by tax breaks. This should help people who get laid off until they can get back on their feet. If the employee finds a new job with health care then the employer can at that time cancel the coverage.

    For example:
    less than 1 year work = 0 months
    1 year = 1 month
    2 years = 2 months
    etc...
  • Ability to cover ones parents under ones own insurance.I for one, want to take care of my parents. They took care of me for so long.

Anyway, these are just a few of the ideas I have about reforming health care. None of them involve the government getting involved in telling you what or what isn't covered.

Update: I struggled for several days with the idea of #2. Just could not seem to come to grips with a good idea to alleviate this issue. Friend of mine said that he did not really care for the idea, and was going to suggest an alternative. I hope it is better than mine.

Thursday, August 6, 2009

Holy crap, this healthcare boondoggle is way worse than I thought

Liberty Council went through the health care bill with a fine tooth comb, and put together a very comprehensive overview of the changes you most likely will abhor. http://lc.org/index.cfm?PID=14102&AlertID=1015

Here is the full stomach turning, head exploding, blood shooting out of your eyes details:
http://www.lc.org/media/9980/attachments/healthcare_overview_obama_072909.pdf

How, HOW in their right minds can any congressman vote for this? It is insanity! It is a despicable grab for more power by the federal government. Forgive me, but I am going to go be sick. Hopefully I won't need a doctor.

EDIT: Friend of mine pointed out that the origins of this list came from the Freepers, then LC edited, and added to it. So H/T Freepers.

UPDATE: Here is the full text of the bill http://www.opencongress.org/bill/111-h3200/text read it, and make up your own mind.

Wednesday, August 5, 2009

"Flagged" Myself


Soooo... I "flagged" myself to the US Government. Not sure how smart I am sometimes. This may turn out to be one of my dumbest moves ever. But I am boiling mad. If you are unsure what this is about, read this: http://www.redstate.com/jeff_emanuel/2009/08/04/call-for-informants-if-you-oppose-obamacare-the-white-house-wants-to-know-about-it/

The government has basically asked for people to snitch on emails, and web sites that oppose ObamaCare. I believe reform IS needed, but not this massive piece of junk they are trying to speed through, and force us into.

http://www.brutallyhonest.org/brutally_honest/2009/08/white-house-asks-for-americans-to-turn-in-americans.html I used the template from this site, to "flag" myself. Sorry for the plagiarism, but it was better than anything I came up with ealier.

Sent the below email to flag@whitehouse.gov
Will continue to send ones like this until they stop calling for snitches, and this email is taken down.


From: **********
Sent: Wednesday, August 05, 2009 1:35 PM
Subject: Healthcare Opponent Flag

My name is Tim Cartwright. I am a citizen of the Untied States. I do not want the government to further insinuate itself into the our health care system. I demand the freedom of choice enter into arrangements with private insurers for me and my family. At every opportunity I am speaking against the president's plans to incrementally do away with private insurance and take over this country's medical system.

I am a vehement opponent of the president's "reforms." I am not a shill for the insurance companies, though I am thought to be shrill. I'm flagging myself to save others the trouble.

Shame on you all for asking that we tattle on one another.


Thursday, July 23, 2009

Senator DeMint: I'm Glad to See The President Out Taking Shots At Me!



He makes an excellent speech on health care. I highly recommend watching it.

Good Intentions: 1982 PBS Documentary Featuring Walter Williams




Good intentions do not always produce good results. Let's get this straight, I like many other conservatives feel empathy for the poor, and the downtrodden. Yet the leftist liberal will scream that we are heartless mean people who care about nothing except big business. Do not believe this lie.

The old saying is incredibly true: "Give a man a fish, you feed him for a day. Teach a man to fish, you feed him for a lifetime."

Giving someone everything they need or want does nothing more than make them a dependent upon handouts. When you help them get back on their feet you help them find their self respect, and independence. How many of you have seen a sign that says some one will work for food? Have you ever tried offering them a short job to help them out? Or do you just continue to give them money, enforcing their dependence on handouts?

Why do I bring this up? Because Barack Obama is trying to pull at your heart strings trying to ram nationalized health care down our throats. Sounds great right? Health care for everyone? Well, just like all the other programs that Walter Williams debunks as actually harmful nationalized health care is being done with nothing less than the best of intentions. Beware when the government is forcing you to do things for your own good.

The road to hell is paved with good intentions.

More on nationalized health care:
Undercover Exposé of Socialized Healthcare!

Nationalized Health Care in Form of Government-Run Restaurant

H/T Carpe Diem

Update: Minimum wage hike could threaten low earners' jobs

Tuesday, July 21, 2009

Chris "Tingles" Matthews is a complete idiot and utter tool


He sits there during this interview waving this Certificate of Live Birth around like its a flag, with no clue as to what it is. It is not the long form birth certificate that details the hospital, the doctor, and the time of birth. The document that Tingles is waving around like a baboon is not the real deal. Read more Tingles, and then do us all a favor and shut the hell up.

Personally I don't know whether or not he is a citizen. I do know that the law requires the president to be one. I also know that Barack Obama has spent a ton of money keeping these lawsuits from finding out the truth. If he is a citizen, he should just show the long form birth certificate to us, and this issue will go away. If he isn't... Well, we aren't going to drop this any time soon.

Friday, July 17, 2009