Saturday, December 21, 2013

Installing Amazon App-Store on Google Nexus 7

I wanted to use the Amazon app-store on my Google Nexus 7 tablet (mainly because I already have quite a few apps that I have bought for a previous Kindle Fire). So here is how to get the amazon app store on your Nexus device.

First, you need to enable installing of apps from stores other than the Google Play Store. To do this, go to Settings and  select Security. Under Device Administration, make sure “Unknown Sources” is selected.

Second, install the Amazon App Store. To do this, down the “apk” file from Amazon from: http://www.amazon.com/gp/mas/get-appstore/android/ (There is additional information on Amazon’s page).

Thursday, December 12, 2013

CRM 2011–MSCRMKeyGenerator– Key not being regenerated correctly

Recently in a dev environment, when I tried to bring up our CRM environment, I was getting the following error:

image

Not very helpful. But if I look at the URL:

http://xxxxx/orgname/_common/error/errorhandler.aspx?BackUri=&ErrorCode=0x8004A106&Parm0=CrmKey%28Id%3aaa{GUID}%2c%20ScaleGroupId%3a00000000-0000-0000-0000-000000000000%2c%20KeyType%3aCrmWRPCTokenKey%2c%20Expired%3aTrue……

So there is certainly something weird going on here.

Looking at the application logs in the event viewer I found the following error:

Current key (KeyType : CrmWRPCTokenKey) is expired.  This can indicate that a key is not being regenerated correctly.  Current Key : CrmKey(Id:GUID, ScaleGroupId:00000000-0000-0000-0000-000000000000, KeyType:CrmWRPCTokenKey, Expired:True, ValidOn:11/03/2013 17:47:19, ExpiresOn:12/06/2013 17:47:19, CreatedOn:11/03/2013 17:47:19, CreatedBy:NT AUTHORITY\NETWORK SERVICE.

After some googling, I found that the reason for this was that the “Microsoft Dynamics CRM Asynchronous Processing Service” may not be running. Which indeed was true in my case. But, after restarting the service, it still was not working.

The final thing that I had to do was issue an iisreset against the server hosting CRM.

Tuesday, December 10, 2013

Custom Rules in Fiddler

I needed to setup a filter in Fiddler so that I could view only JSON requests being made from my application. The default filter doesn’t allow for viewing only JSON requests. But luckily Fidller allows you to setup custom rules. Here is what I did:

Within the class “Handlers” add the following lines of code:

public static RulesOption("Display Only &Json Requests")
var m_bShowOnlyJsonRequests: boolean = false;

The above lines will add a Menu option under rules, that will easily allow you to turn on or off the JSON filtering.

image

Next, within the method: static function OnBeforeRequest(oSession: Session), add the following lines of code:

if (m_bShowOnlyJsonRequests && oSession.oRequest["Content-Type"] != "application/json"){
                oSession["ui-hide"] = "true";
          }

The above lines of code allow filters to display only those sessions that have a content-type header set to “application/json”.

As simple as that!

Notes:

1. The biggest problem that I have found is that there is hardly any documentation regarding the methods and properties available within the script file or off the oSession object (which is of type Session).

2. I think the script is based of JScript. I just wrote my code to resemble C# and it worked for my simple filter.

3. Samples from FiddlerBook site: http://fiddlerbook.com/Fiddler/dev/ScriptSamples.asp

4. Fiddler Script Editor is a pretty good tool that can help writing complex rules (it provides some documentation, though it wasn’t always helpful). http://fiddler2.com/fiddlerscript-editor

5. More Samples: http://fiddler2.com/documentation/KnowledgeBase/FiddlerScript/ModifyRequestOrResponse

6. Session object properties/flags: http://fiddler2.com/documentation/KnowledgeBase/SessionFlags

Tuesday, October 15, 2013

MSBUILD : error MSB1005: Specify a property and its value.

I was getting the following error from MS-Build:

MSBUILD : error MSB1005: Specify a property and its value.
Switch: /p:Deploy=true;DeployToEnvironment=es1ci;Configuration=Debug;UsingNUnit=true;

The problem turned out to be the last “;”. Apparently MsBuild doesn’t like it!. Took it out and MsBuild was able to run!

Thursday, October 10, 2013

Work Ethic–17 things you should never say to your boss

I came across this article on LinkedIn recently and found it interesting as, in a way, it kind of tells you what someone with good work ethics would not do or say at work. (its based on answers given by bosses at some new technology companies). I wish more people would read this.

Read it at: http://www.linkedin.com/today/post/article/20130923134035-15077789-17-things-you-should-never-say-to-your-boss

17 Things You Should Never Say to Your Boss

1. 'I Am Just Here for the Money'

In China, it is very common for a lot of employees to work just for the money. This means they will leave if you fail to give them a raise or if their peers start to make a lot more money than they do. Our interview process has filtered this as much as possible but if we hear through the "grapevine" that the person is just doing the job for the money we will let them go very quickly.

- Derek Capo, CEO and Founder, Next Step China

2. 'You Never Told Me to Do It'

When something important doesn't get done, the worst thing you can say is, "You never asked me to do it." There are few better ways to neglect yourself of that promotion, a raise, or even job security.

- Ken Cauley, President, Advanced Media

3. 'There's Something Wrong'

It's easy to complain about what's wrong. It's hard to come up with solutions to fix the problem. My former manager at LivingSocial said, "Be a problem solver, not spotter," and I've taken this advice to heart in my everyday life. If you see a problem, don't address the situation with what's wrong; address the situation with an answer. If you don't have a real solution, wait until you do.

- Sarah Ware, Markerly

4. 'I Want to Do What's Easiest'

We have a client who had an employee literally explain that he would rather do a particularly menial task than the task that the employer had assigned because it would be easier for him. We were shocked. This is the most explicit way to alert your boss that you don't care about improving your skill set without directly telling him. Never do this if you care about your career!

- Patrick Conley, Founder / CEO, Automation Heroes

5. 'That Takes Up Too Much Time'

Through the years, we have had many operational restructurings that have required large amounts of data to be filtered and edited or re-formatted in some manner. There's nothing worse than an employee who complains about the amount of time required to move the company to the next level.

- Laura Land, CFO / COO, Accessory Export, LLC

6. 'I Could Be Doing Other Things'

Bratty much? Don't complain about your job. If you hate it, quit. If there's something wrong with it, find a way to fix it. If someone or something is really ticking you off, don't project your anger onto others, especially not your boss. If it's a good job, be grateful for it. If you want more out of your job, make it happen. Be diplomatic about it and make it your dream job, or leave.

- Danny Wong, Co-founder, Blank Label

7. 'I Promise to Do That'

Don't ever tell your boss you're able to do something if you know you may not be able to deliver. It is better to be honest, ask for advice and have a proactive attitude. If you fail to deliver, then it has negative repercussions for the business, which is taken much more seriously.

- Christopher Pruijsen, Co-Founder / Partnerships, Afrostart.io

8. 'It's Too Difficult'

I get fired up when someone is paralyzed and doesn’t complete a task because it’s difficult or because few others have done it. We’re a disruptive company that has to innovate, that has to do things few have done before us. One of my advisors here has a quote: “If it were easy, everyone would be doing it.” We won’t win if we don’t think big.

- Marcos Cordero, Chief Gradsaver, GradSave, LLC

9. 'I Agree to Disagree'

Whether it is said explicitly or passive-aggressively, this mindset has no place in startup culture. Those who have this mindset should either found their own startups or go work in big corporate America where this goes unnoticed. At a startup, you're either all the way in or all the way out.

- Danny Boice, Co-Founder & CTO, Speek

10. 'I Don't Have an Opinion'

The people who just sit and nod their heads are the ones who are expendable. If you want to make an impression as a valuable member of the team, offer your insights. No one ever agrees with his boss 100 percent all the time, so make your opinion known if you have something worth saying.

- Nick Friedman, President, College Hunks Hauling Junk and College Hunks Moving

11. 'I Can't'

I don’t want to hear excuses ever! We focus on hiring can-do, positive, creative employees with passion, drive and determination.

- Kuba Jewgieniew, Founder and CEO, Realty ONE Group

12. 'I'm Not Optimistic'

The most important thing for any team member is to stay optimistic. Being a pessimist and doubting the future of the company is a real downer. There is nothing wrong with being realistic; however, people who are melancholy suck the life out of an early-stage company and cannot last long.

- Raoul Davis, CEO, Ascendant Group

13. 'I'm Clocked Out'

There is nothing more discouraging to an entrepreneur than when an employee says he is not willing to go the extra mile because he isn't "clocked in." We remind our employees that they work for a young company and they are in control of their own careers. Acting within the status quo never gets you to the top!

- Darren Solomon, President, Kid Ventures

14. 'That's Not My Responsibility'

It’s critical that everyone feels invested in the success of all areas of the business. Everyone should be willing to pitch in, even if what’s required isn’t part of their normal day-to-day activities.

- Robert J. Moore, Co-Founder and CEO, RJMetrics

15. 'That's Not My Job'

Your responsibilities aren't limited to what was listed in your original job description -- especially at a startup. Unless your boss is asking you to do something illegal or unethical, you should do it.

- Mary Ellen Slayter, Founder/Managing Director, Reputation Capital

16. 'I Don't Like Working for Other People'

An employee actually told me that he didn't like working for other people. That person doesn't work for me anymore!

- Andrew Angus, CEO, Switch Video

17. 'I'm Not Working Hard'

I never want to know that someone who works for me isn’t working hard. People can disagree with me, and I’m fine to hear criticism. I’ll never lose respect for anyone because he disagrees with me or because they failed. I don’t want to know if someone is giving less than their best effort or that someone lied. I have high expectations of people when it comes to their work ethic.

- Dries Buytaert, Co-founder and CTO, Drupal

Monday, September 16, 2013

CRM 2011–Plugin Registration Error: Assembly must be registered in isolation

While registering a CRM 2011 plugin I kept getting the following error in only one of our test environments.

Assembly must be registered in isolation

After a lot of searching I found out that the reason I was getting this error in only one environment was that I was not designated as a “Deployment Administrator”. Once I had that fixed, the error went away!

Unhandled Exception: System.ServiceModel.FaultException`1[[Microsoft.Xrm.Sdk.OrganizationServiceFault, Microsoft.Xrm.Sdk, Version=5.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35]]: Action failed for assembly xxxxxxxxx, Version=1.0.0.0, Culture=neutral, PublicKeyToken=yyyyyyy': Assembly must be registered in isolation.

Friday, September 06, 2013

What We Actually Know About Software Development, and Why We Believe It's True

A very good presentation on how we can make the field of software engineering better by Greg Wilson: http://vimeo.com/9270320. He also brings up some thought provoking data-points:

Greg Wilson - What We Actually Know About Software Development, and Why We Believe It's True from CUSEC on Vimeo.

From the slides in the presentation:

  • Most errors are introduced during requirements analysis and design. Not during writing and debugging. The later a bug is removed, the more it costs to remove. (Boehm (1975))
  • For every 25% increase in problem complexity, there is a 100% increase in solution complexity. It's non-linear because of interaction effects.  (Woodfield (1979))
  • The two biggest causes of project failure are poor estimation and unstable requirements, neither of which seem to be improving in the industry as a whole. (van Genuchten (1991))
  • If more than 20-25% of a component has to be revised, it's better to rewrite it from scratch. (Thomas et al. (1997))
  • Hour for hour, sitting down and reading the code is the most effective way to remove bugs. It's better than running the code and better than writing unit tests. 60-90% of all errors can be removed before the very first run of the program. BUT, all of that value comes from the first hour by the first reviewer. You can only read code for an hour before your brain is full - only a couple hundred lines of codes depending on skill / practice. This means we should have small patches and changes. (Fagan (1975))
  • The architecture of the system reflects the organizational structure that built it. (Herbsleb (1999))
  • Physical distance between a team of developers doesn't affect post release fault rate. Distance in the org chart does. Thus, it's fine to have people remote as long as they are on the same team, just don't put developers working under different people on the same project. (Nagappan (2007) & Bird (2009))
  • No code (or other) metrics that were published before 2001 have any correlation with post-release error rate beyond that predicted by source lines of code (SLOC). (El Emam (2001))
  • When estimating the time it will take to complete a project the only thing that matters in the spec for the project is how long the writer of the spec thinks it will take (ie. the anchoring effect from psychology). "All work done to date on software estimation is pretty much pointless. All the engineers are going to give us back is what we want to hear." (Aranda & Easterbrook (2005))

Monday, August 12, 2013

WPF–Creating a single instance application

I wanted to make my WPF application such that only a single instance of it could run at a time. I found that there were 2 main ways demonstrated on the internet:
1. Use “Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase” and setup the “OnStartupNextInstance” to activate the first instance of the application. or
2. Use Mutex to ensure only a single instance of a program can be run at time. (Which is the accepted answer on StackOverflow. http://stackoverflow.com/a/522874/44815).
I wanted to use the Mutex method, though the article referenced in the StackOverflow answer - “C# .Net Single Instance Application” does not give all the details that one has to implement for a WPF application, so here is some more detailed info:

1. Add a Mutex to the “App” class
/// <summary>
/// Interaction logic for App.xaml
/// </summary>
public partial class App
{
 /// <summary>
 /// This should be a unique name which is used to determine if another instance of app is running
 /// </summary>
 private const string APP_UNIQUE_NAME = "UNIQUENAME_FOR_MY_APP or use a GUID";
  /// <summary>
  /// Initializes the Mutex class and make the calling thread have initial ownership of the mutex
 /// and a string that is the name of the mutex.
 /// </summary>
 static readonly Mutex _mutex = new Mutex(true, APP_UNIQUE_NAME);


2. Add a Main method to the “App” class, which will act as the entry point for the application and will signal the mutex to wait until its released
[STAThread]
static void Main()
{
//using TimeSpan.Zero as we want the mutex to test state of wait handle and return immediately
 if (_mutex.WaitOne(TimeSpan.Zero, true))
 {
 //calling waitone stops everyone else from entering the code in this block until the mutex is released
  try
  {
   App app = new App();
   app.InitializeComponent();
   app.Run();
  }
  finally
  {
   _mutex.ReleaseMutex(); 
  }
 }
 else
 {
  MessageBox.Show("Only one instance of the app can be run!","App Name",MessageBoxButton.OK, MessageBoxImage.Exclamation);
 }
}
3. Setup the WPF application to use the “Main” method as its entry point
a. Right click on the application’s project file and select properties. On the tab “Application”, set the “Startup object” to the name of the “App” class we modified above.
b. Right click on the “App.xaml” file in your project and select properties. Change the “Build Action” to “Page” from “ApplicationDefinition
4. Build and test the application!

Sunday, July 28, 2013

How users see programmers and how programmers see users

Encountered on the InterWeb. Unfortunately this is often true and I see a lot of software engineers treat their users like cave-men. Its unfortunate, because it leads to software engineers not listening to their users or changing features as they (software engineers) think is the right way to implement it. Never a good idea.

Respect and trust between the 2 groups is important otherwise you  risk building the wrong things for the users.

How-users-see-programmers-and-how-programmers-see-users-575x503

Friday, July 12, 2013

Obi202 not ringing for incoming calls

I recently bought an Obi202 VOIP phone adapter so that I could receive calls on my Google Voice number on my land line phone. (Will post a review soon – but for now just know that I am amazed by this product. Love it).

Anyways, the device was working fine until this morning after which phone calls to my Google Voice number were not ringing on my land-line phone. After a lot of trouble shooting what I found out is that to received calls via the Obi VOPI adapter, you need to enable Google Chat as a forwarding phone. You do this by logging into Google Voice and click on the gear icon (upper right) and then choose “Settings”. Under the “Phone” tab, make sure “Google Chat” is checked.

image

Monday, July 01, 2013

NonSerializedAttribute cannot be applied to fields that are Events

I recently encountered a compiler error, where I could not apply the [NonSerialized] attribute on a field that was an event.

The error that I got was: Attribute 'NonSerialized' is not valid on this declaration type. It is only valid on 'field' declarations.   

I made the assumption that, the reason for that is that events are not serialized by the serializers and so went ahead and left the field without any serialization modification attribute. Alas, the next day, I got emails from a bunch of people at work that my checkin had broken the app! FIRE DRILL.

Apparently, on fields that are events, one needs to attribute them using [field:NonSerialized] attribute.That fixed the problem and life continued on as usual.

Friday, June 28, 2013

WCF Timeouts explained

Found this good explanation for the various timeouts in WCF and which ones get used on the client and which get used on server.

Brief summary of binding timeout knobs...

Client side:

  • SendTimeout is used to initialize the OperationTimeout, which governs the whole interaction for sending a message (including receiving a reply message in a request-reply case).  This timeout also applies when sending reply messages from a CallbackContract method.
  • OpenTimeout and CloseTimeout are used when opening and closing channels (when no explicit timeout value is passed).
  • ReceiveTimeout is not used.

Server side:

  • Send, Open, and Close Timeout same as on client (for Callbacks).
  • ReceiveTimeout is used by ServiceFramework layer to initialize the session-idle timeout.

From: http://social.msdn.microsoft.com/Forums/vstudio/en-US/84551e45-19a2-4d0d-bcc0-516a4041943d/explaination-of-different-timeout-types

Monday, June 24, 2013

Using the Adobe Pdf Reader control in WPF

Important: This will not work if your application targets 64 bit. It will only work as a 32bit app as the AcroPdf.dll is a 32 bit dll.

1. Create a WPF Control Library

2. Add a Windows Forms user control

3. Open the user-control form.

4. In the toolbox, right click and choose “Choose Items…”

5. On the “COM Components” tab, select “Adobe PDF Reader”

image

6. Drag the “Adobe PDF Reader” from the toolbox on the user-control.
Name the control that was added on to the form as "axAcroPdf”

7. Make sure the Anchors are set to “Top, Left” and that Dock is set to “Fill”
image

8. Add the following code to the code behind:

		private AxAcroPDFLib.AxAcroPDF AdobeAcrobatPDfControl
		{
			get
			{
				return this.axAcroPDF;
			}
		}
 
		public void LoadFile(string pdfFilePath)
		{
			AdobeAcrobatPDfControl.LoadFile(pdfFilePath);
		}

8. Create a WPF UserControl. Name it WpfAcrobatCtrl.

9. Drag a WindowsFormsHost WPF control onto the design surface.

10. Set the following properties on the WindowsFormsHost control:
Width and Height to Auto
HorizontalAlignment and VerticalAlignment to Stretch
Name: wpfWindowsFormsHostCtrl.

11. Add the following code to the code behind of the WPF control:

public static readonly DependencyProperty FilePathProperty
			= DependencyProperty.Register("FilePath", typeof(string), typeof(WpfAcrobatCtrl), (PropertyMetadata)new FrameworkPropertyMetadata((object)null, new PropertyChangedCallback(WpfAcrobatCtrl.FilePathChanged)));
 
 
		private string _filePath = string.Empty;
		private CustomAcrobatCtrl _customAcrobatCtrl;
	
		
		private static void FilePathChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
		{
			((WpfAcrobatCtrl)d).FilePathChanged((string)e.OldValue, (string)e.NewValue);
			CommandManager.InvalidateRequerySuggested();
		}
 
		public WpfAcrobatCtrl()
		{
			InitializeComponent();
			_customAcrobatCtrl = new CustomAcrobatCtrl();
			wpfWindowsFormsHostCtrl.Child = _customAcrobatCtrl;
 
		}
 
		public string FilePath
		{
			get
			{
				return _filePath;
			}
			set
			{
				this.SetValue(FilePathProperty, value);
			}
		}
 
 
		private void FilePathChanged(string oldFilePath, string newFilePath)
		{
			_filePath = newFilePath;
			_customAcrobatCtrl.LoadFile(_filePath);
		}

12. Create a new WPF Window.

13. Drag and drop the WpfAcrobatCtrl onto the design surface.

14. Set the file-path in XAML or code-behind.

Eg: wpfAcrobatCtrl.FilePath = "C:\\test.pdf";

or in XAML: <WpfAcrobat:WpfAcrobatCtrl x:Name="wpfAcrobatCtrl" Margin="0" FilePath="C:\\test.pdf"/>

That’s all!

Note: The above code adds a little extra stuff for the dependency property “FilePath”. This allows for setting the file path via XAML (which was important for me as I needed to be able bind to the property).

Note 2: If you try and use the AcroPdf.dll in a 64 bit app, you will get the following error: {"Class not registered (Exception from HRESULT: 0x80040154 (REGDB_E_CLASSNOTREG))"}

Tuesday, June 11, 2013

C# - Why you must never lock on this

You should never lock on “this” if this points to an instance of a publicly accessible class. The reason is that if the class is publicly accessible, then you have no control over whether someone else who uses your class, uses the instance for locking. And if they do lock an instance of your class, then you will end up in a dead-lock.

Here is some simple code to illustrate this:

using System.Threading.Tasks;

void Main()
{
    ClassTest test = new ClassTest();
    lock(test) //locking on the instance of ClassTest
    {
        Parallel.Invoke (new Action[]{() => test.DoWorkUsingThisLock(1)});
    }
}

public class ClassTest
{
    public void DoWorkUsingThisLock(int i)
    {
        Console.WriteLine("Before ClassTest.DoWorkUsingThisLock " + i);
        lock(this) //this is bad - this will never end - you have been deadlocked!
        {
            Console.WriteLine("ClassTest.DoWorkUsingThisLock " + i);
            Thread.Sleep(1000);
        }
        Console.WriteLine("ClassTest.DoWorkUsingThisLock Done " + i);
    }
}

From MSDN:

In general, avoid locking on a public type, or instances beyond your code's control. The common constructs lock (this), lock (typeof (MyType)), and lock ("myLock") violate this guideline:

  • lock (this) is a problem if the instance can be accessed publicly.

  • lock (typeof (MyType)) is a problem if MyType is publicly accessible.

  • lock("myLock") is a problem because any other code in the process using the same string, will share the same lock.

References:

Lock Statement (MSDN)

Monday, May 27, 2013

The 14 characters you meet as a coder–InfoWorld

Ran into this article on InfoWorld and it was too funny to not share:

http://www.infoworld.com/d/application-development/the-14-characters-you-meet-coder-218142?page=0,0

The Developer Diva. Great software is rarely a one-person effort. There are users, plus the testers, plus the crew who markets or sells the work. But the Developer Diva recognizes those efforts in the same way actors who win Oscars thank the "little people." Developer Divas are not satisfied with standard accommodations; they need to be pampered. In fact, someone in management needs to devote at least 50 percent of his or her time to listen to the diva's complaints and get the diva to produce. If that management load increases every time the Developer Diva acquires a new skill, perhaps it's time to send the diva packing, even if the replacement is a little less skilled.

The Rock Star. Generally this guy knows HTML and JavaScript or maybe PHP, but from the ego you'd think he just set down his Les Paul after headlining at Madison Square Garden. After his 15 minutes are up, the crashing ego isn't pretty.

The Reluctant Programmer. Rather than urge their kids to be doctors or lawyers, some parents push their progeny to go into software development. Sometimes it works out. And sometimes the poor, benighted offspring gaze out of the office window yearning for hard labor in the 95-degree heat -- anything except spending their lives doing something they don't want to do, whether or not they have the aptitude for it. Usually their work is mediocre, and they're out the door every day at 4:55 p.m. sharp.

The Holy Priest. This person revels in technology for its own sake and has no patience for the hapless techno weenies who don't spend their days chanting arcane invocations using terms like "regex," "SOAP," "asynchronous messaging," "n-tier architecture," and "CORBA." Holy Priests recognize opinions as valid only if they come from fellow clerics, and they express contempt for "lusers" at every opportunity. They may be brilliant coders, but keep them locked in the closet, far away from customers.

The Process Guru. You might wonder who would spend all their time reading books on the latest development methodologies. That would be the Process Guru, who knows more about Scrum, XP, RUP, Crystal, PSP, TSP, and COCOMO than the rest of your organization put together. The guru is interested only in the process of creating software and cares nothing about the output of said process. Consuming every minute of every meeting, the Process Guru likes to explain how "we're doing agile wrong" and pontificates about the need for more agile training. Usually, but not always, the Process Guru is recognizable by the Certified Scrum Master status.

The "Jeopardy" Champion. The expert on arcane trivia, this developer may or may not be generally productive, but stands as the one person on the team who always seems to possess some obscure bit of needed knowledge. Whether it's the details of how "volatile" works in Java, both before and after the changes to the memory model spec, or deep knowledge of tuning a JBoss AS 4.2.3 configuration, the "Jeopardy" Champion is a valuable asset (at least twice a year).

The Hipster Hacker from Hell. We really need to rewrite all of our software in Haskell because then our code will be beautiful. Never mind the costs! Did I say Haskell? Haskell was so last year. I mean Clojure because it will be simple! Bugs? Features? I have no time for such trivial matters. I have a whole new architecture to write in Ceylon!

The Architecture Astronaut. This developer loves complexity and never sees a problem too simple to deserve a multitier, distributed system using a Java application server, multiple message queues, SOAP-based Web services with distributed transactions, and native code in C++ for good measure. When not designing byzantine architectures, astronauts immerse themselves in the WS-* specs or CORBA manuals. They may be found associating with Hipster Hackers from Hell, scheming up a new distributed system built in a combination of Erlang, Scala + Akka, Node.js, and Haskell. The astronaut will try to spend at least half of the allocated time for the project drawing UML diagrams and "fleshing out the architecture." Mantra: "The project isn't done until it uses at least 7/8 of the patterns in the GoF book."

The Insecure Evangelist. This guy/gal designed the entire system, but is threatened by new suggestions from just about anybody. Basically, my ideas are good and yours are bad, unless I repackage them as my ideas.

The Code Poet. The poet's code is elegant and conforms beautifully to design patterns. On the other hand, the Code Poet holds you up in meetings forever and never notices the missed deadlines or the annoyed looks on other peoples' faces.

The Cloud Zealot. This character has never heard of (or doesn't believe in) the eight fallacies of distributed computing and couldn't spell "SLA" if you spotted him the "S," "L," and "A." However, they can leap on a trending buzzword like a lion stalking a gazelle on the savannah. The Cloud Zealot races to move everything "to the cloud" with no regard for security, latency, network outages, data interoperability, vendor lock-in, or the long-term viability of the SaaS vendor du jour. Secure in his knowledge that no fly-by-night SaaS offering has ever been hacked, leaking usernames, email addresses, and unencrypted passwords for every user account, the Cloud Zealot sleeps easy. Lucky for him, he'll have moved on to a new company before you discover that all of your employees identities are for sale by the Russian mafia.

The Traditionalist. "Why would you ever need anything other than Java and an Oracle DB?" "You should definitely run your application on WebSphere." "Oh, you want to send messages between nodes? Let me prepare the XML schema."

The Uber Traditionalist. This party thinks Java is too newfangled and unproven for production use, preferring to develop on an AS/400, in RPG, using the SEU. The UT spends most of his time regaling you with tales of his youth, when the VAX was still a technological marvel and the PC was yet to be born. He probably built his first computer from raw transistors on a breadboard and never hesitates to remind the Hipster Hacker from Hell (his mortal enemy) that "the ideas in Node.js were originally developed in SNOBOL in the '70s, you know" or "Haskell is just a less pure and inferior LISP in many ways."

The Proprietary Priest. Telltale signs: Insists that all solutions should use proprietary tools from a trusted name; Perforce, Websphere, AIX, Oracle -- you get the idea. If Microsoft, IBM, or some other corporation didn't write it, then it must be crap.

Monday, April 29, 2013

Controls that implement WPF Commanding

I was trying to find a quick list of the basic WPF controls that support commanding (so that I could expose a DelegateCommand from my ViewModel to which I could bind the view). What I found out was that “generally” commands that support commanding implement ICommandSource. Based on that info, I was able to generate the following list of controls that implement ICommandSource:

System.Windows.Input.InputBinding
System.Windows.Input.KeyBinding
System.Windows.Input.MouseBinding
System.Windows.Controls.MenuItem
System.Windows.Controls.Button
System.Windows.Controls.Primitives.ToggleButton
System.Windows.Controls.CheckBox
System.Windows.Controls.GridViewColumnHeader
System.Windows.Controls.Primitives.CalendarButton
System.Windows.Controls.Primitives.CalendarDayButton
System.Windows.Controls.Primitives.DataGridColumnHeader
System.Windows.Controls.Primitives.DataGridRowHeader
System.Windows.Controls.Primitives.RepeatButton
System.Windows.Controls.RadioButton
System.Windows.Documents.Hyperlink
System.Windows.Shell.ThumbButtonInfo

MS.Internal.Documents.DocumentGridContextMenu+EditorMenuItem
System.Windows.Documents.TextEditorContextMenu+EditorMenuItem
System.Windows.Documents.TextEditorContextMenu+ReconversionMenuItem

More info:

MSDN: commanding overview: http://msdn.microsoft.com/en-us/library/ms752308.aspx

Monday, March 18, 2013

Convert an Anonymous type object to a dictionary

I wanted to write a method that would take an anonymous object and have it spit out key,value pairs from the properties defined on that anonymous object.

For example:

new {j="j1",k="k1"}

Should create a dictionary with 2 keys (j,k) which have corresponding values of (j1,k1).

A while back I had written about an helper method that would convert all the properties on an object into a dictionary: http://blog.aggregatedintelligence.com/2013/01/convert-objects-property-values-to.html

It turns out that the same method can be used even for anonymous types!

Monday, March 11, 2013

Did you know–XOR swap algorithm?

Did you know that you can use the XOR operator to swap the values in 2 variables without the use of a 3rd variable?

Check it out:

int x = 111;
int y = 3333;

x ^= y;
y ^= x;
x ^= y;

x.Dump();
y.Dump();

Outputs:

3333
111

Sunday, March 10, 2013

MemoryStream exception–Memory stream is not expandable

Just got hit by this exception.

I was creating a memory stream from bytes that I had read from a file:

var fileBytes = File.ReadAllBytes(filePath);
MemoryStream ms = new MemoryStream(fileBytes, true);

The memory stream was then being used in a bunch of operations that could add data and when it did, it caused the “Memory stream is not expandable” exception to be thrown.

Found out that its because of the constructor that I was using. Because I was providing memory-stream the actual bytes, it was creating the memory stream as a non-expandable one. Instead, if you construct it and then write to it, the memory stream has no such restriction and it can expand.

MemoryStream ms = new MemoryStream();
ms.Write(fileBytes, 0, fileBytes.Length);

Monday, March 04, 2013

Dilbert–Gratuitous displays of mental superiority!

but I try not to frighten ordinary people with any gratuitous displays of mental superiority

UnityBootstrapper–Order in which methods are called

The MSDN documentation page “Initializing Prism Applications” shows the basic stages of the bootstrapping process, but it leaves out when some of the methods that can be overriden get called.

Process as defined in MSDN:

Gg430868.544A7BF3FF93BE95A370A3D97774244A(en-us,PandP.40).png

 

Here is the order in which all methods that can be overridden are called:

  1. Run (called typically when app is starting up)
  2. CreateLogger
  3. CreateModuleCatalog
  4. ConfigureModuleCatalog
  5. CreateContainer
  6. ConfigureContainer
  7. ConfigureServiceLocator
  8. ConfigureRegionAdapterMappings
  9. ConfigureDefaultRegionBehaviors
  10. RegisterFrameworkExceptionTypes
  11. Create Shell
  12. InitializeShell
  13. InitializeModules

And here is logging output of the Prism bootstrapper process (where UnityLoggerFacade is a logging class that I created):

UnityLoggerFacade              - Logger was created successfully.
UnityLoggerFacade              - Creating module catalog.
UnityLoggerFacade              - Configuring module catalog.
UnityLoggerFacade              - Creating Unity container.
UnityLoggerFacade              - Configuring the Unity container.
UnityLoggerFacade              - Adding UnityBootstrapperExtension to container.
UnityLoggerFacade              - Configuring ServiceLocator singleton.
UnityLoggerFacade              - Configuring region adapters.
UnityLoggerFacade              - Configuring default region behaviors.
UnityLoggerFacade              - Registering Framework Exception Types.
UnityLoggerFacade              - Creating the shell.
UnityLoggerFacade              - Setting the RegionManager.
UnityLoggerFacade              - Updating Regions.
UnityLoggerFacade              - Initializing the shell.
UnityLoggerFacade              - Initializing modules.
UnityLoggerFacade              - Bootstrapper sequence completed.

Wednesday, February 27, 2013

Telerik ASP.Net MVC Grid–Ajax binding boolean property

When you bind a collection of objects that have a boolean property on them and if you use server side binding, the columns are automatically rendered as check-boxes. But instead, if you use AJAX binding with the telerik MVC grid, they get rendered as literal texts (“true” or “false”). To fix it, what you need to do is to set the ClientTemplate. Here is an example:

grid.Columns(columns => {
columns.Bound(o => o.Value).ClientTemplate("<input type='checkbox' <#=Value?'checked':''#> disabled />");

Where the code that’s highlighted is the binding code and “Value” is the property to which I am binding. Also, I am using the ternary operator to output “checked:’’” if its true, else it outputs nothing.

  

Sunday, February 24, 2013

Javascript–Convert URLs in text to links

Was looking for some code to convert urls in strings to url anchors. Came across this post (JMRWare) and below is the extracted code for javascript:

Thursday, February 21, 2013

ASP.Net MVC–Authorize filter that loads users and roles from the application configuration file

I needed the ability to set the Authorization filter from a config file (instead of setting the roles and users directly on the controller). The main reason for this is that I needed different roles to be authorized to hit the action based on the environment to which it was deployed (dev,qa, prod).

Here is the code:

Saturday, February 16, 2013

C#–Determining if an object implements or derives from a generic class or interface

Imagine you have a generic class and interface that are defined as follows:

public abstract class MyGenericClass<T>
{
}
public interface IMyGenericInterface<T>
{
}

If you were to derive or implement from the above class/interface, you will find that you cannot use the “is” keyword to determine if that class implements or derives from the above interface. Here is what I mean: If I were to implement/derive from the base class like so:

public class MyInt:MyGenericClass<int>
{
}

public class MyInterfacedInt:IMyGenericInterface<int>
{
}

Then I can do the following: (code will run in LinqPad)

MyInt myInt = new MyInt();
MyInterfacedInt myIInt = new MyInterfacedInt();

(myInt is MyInt).Dump();//true
(myIInt is MyInterfacedInt).Dump();//true;

(myInt is MyGenericClass<int>).Dump();//true
(myIInt is IMyGenericInterface<int>).Dump();//true;

But I cannot do the following:

//Will not compile
//(myInt is MyGenericClass<>).Dump();
//(myInt is IMyGenericInterface<>).Dump();

Why is this important? If you plan on loading plugins at run time, then all you know is that they will implement an interface or a base class and you need to check that. One way around this would be to create a non-generic base class or interface and check against that. But that might not be a possibility if you are using a 3rd party API (eg: Prism and the CompositePresentationEvent<> type).

So here is a helper class that can do just that:

static class ReflectionHelper
{
    public static bool IsDerivedOrImplementedFrom<T>(this T objectToCheck, Type parentType) where T : class
    {
        if (objectToCheck == null)
            return false;
        if (parentType.IsInstanceOfType(objectToCheck))
            return true;

        bool checkingInterfaces = parentType.IsInterface;
        Type toCheck = objectToCheck.GetType();
        while (toCheck != null && toCheck != typeof(object)) {
            var cur = toCheck.IsGenericType ? toCheck.GetGenericTypeDefinition() : toCheck;
            if (checkingInterfaces)
            {
                bool implementsParentInterface = toCheck.GetInterfaces()
                                            .Any(ci => {
                                                return ci.IsGenericType ? ci.GetGenericTypeDefinition() == parentType :
                                                    ci == parentType;
                                            });
                if (implementsParentInterface)
                    return true;
            }
            else
            {
                if (parentType == cur)
                {
                    return true;
                }
            }
            toCheck = toCheck.BaseType;
        }
        return false;
    }

}

And here is how you call it:

static void Main(string[] args)
        {
            MyInt myInt = new MyInt();
            MyInterfacedInt myIInt = new MyInterfacedInt();

            "Using the \"is\" keyword".Dump();

            (myInt is MyInt).Dump();//true
            (myIInt is MyInterfacedInt).Dump();//true;

            (myInt is MyGenericClass<int>).Dump();//true
            (myIInt is IMyGenericInterface<int>).Dump();//true;

            //Will not compile
            //(myInt is MyGenericClass<>).Dump();
            //(myInt is IMyGenericInterface<>).Dump();

            "Using IsDerivedOrImplementedFrom".Dump();
           
            myInt.IsDerivedOrImplementedFrom(typeof(MyInt)).Dump(); //true
            myIInt.IsDerivedOrImplementedFrom(typeof(MyInterfacedInt)).Dump();//true
            myInt.IsDerivedOrImplementedFrom(typeof(MyGenericClass<int>)).Dump();//true
            myIInt.IsDerivedOrImplementedFrom(typeof(IMyGenericInterface<int>)).Dump();//true

            myInt.IsDerivedOrImplementedFrom(typeof(MyGenericClass<>)).Dump();//true
            myIInt.IsDerivedOrImplementedFrom(typeof(IMyGenericInterface<>)).Dump();//true

            "Negative tests Using IsDerivedOrImplementedFrom".Dump();

            myInt.IsDerivedOrImplementedFrom(typeof(MyInterfacedInt)).Dump(); //false
            myIInt.IsDerivedOrImplementedFrom(typeof(MyInt)).Dump();//false
            myInt.IsDerivedOrImplementedFrom(typeof(MyGenericClass<string>)).Dump();//false
            myIInt.IsDerivedOrImplementedFrom(typeof(IMyGenericInterface<string>)).Dump();//false

            myInt.IsDerivedOrImplementedFrom(typeof(IMyGenericInterface<>)).Dump();//false
            myIInt.IsDerivedOrImplementedFrom(typeof(MyGenericClass<>)).Dump();//false

            Console.ReadLine();
        }

Here is the full code: http://pastebin.com/raw.php?i=Y2nSQc7V

Thursday, February 07, 2013

Linqer–Sql to Linq tool

Came across Linqer, a Sql to LINQ conversion tool. From some preliminary tests, I found that it worked pretty well given some complex queries.

Unfortunately, there is no free version of the tool and it costs $60. This would be a fabulous tool within LinqPad. Hopefully someday LinqPad will include this functionality.

Syncfusion Succinctly Series of ebooks

I have been enjoying the SyncFusion suite of products for about 4 months now. Apart from a stellar set of UI tools, what I have liked about Syncfusion is the constant communication that they provide the developer community. One example of this is the Succintly series of e-books that they release periodically.

You can check out the list of books that they have at: http://www.syncfusion.com/resources/techportal

I found that the jQuery and Javascript books were useful for me as refreshers when I was getting back into Asp.Net MVC programming after spending a while in classic Asp.Net and Silverlight. In addition, I had provided the book on data-structures to a junior developer at work and he liked it very much (and actually noted that it better explained some concepts than his teacher did). I am also interested in looking at the books on Objective-C and GIS.

Just about the only thing I hate about the succintly series is that I need to enter my contact information each time I get download a book from the series. (especially since I have already logged into the site).

Oh! and while you are on their site, get their Metro Studio product for free. It’s the best free resource for metro style icons.

Disclaimer: I received a free copy of Syncfusion’s tools as a door prize at the Denver Visual Studio user group meeting and Syncfusion is also providing me a small cash compensation for this post. But, none of that influenced the comments in this post. I meant to post this as a resource long before I was contacted by Syncfusion.

Monday, January 28, 2013

Convert an object’s property values to a dictionary of string,object

Here is a simple helper function that converts any class object to a dictionary of string,object, where the key is the PropertyName:

public static class ReflectionHelper
{
    public static IDictionary<string, object> ToDictionary<TModel>(this TModel model)
   {
       BindingFlags publicAttributes = BindingFlags.Public | BindingFlags.Instance;
       Dictionary<string, object> dictionary = new Dictionary<string, object>();

       foreach (PropertyInfo property in model.GetType().GetProperties(publicAttributes))
       {
           if (property.CanRead)
               dictionary.Add(property.Name, property.GetValue(model, null));
       }

       return dictionary;
   }
}

public class Test
{
    public string Name{get;set;}
}

void Main()
{
    Test t = new Test{Name = "Raj Rao"};
    foreach(var v in t.ToDictionary())
    {
           Console.WriteLine(v.Key + ":" + v.Value);
    }

}

The output will be:

Name: Raj Rao

This again was inspired by some of the Helper functions available in Asp.Net’s MVC HTML helper class.

Getting rid of magic strings that point at PropertyNames

Often times, you end up with code that includes magic strings that point at property names of a class. I hate this, because it normally ends up causing runtime errors instead of compile time errors.

While working with Asp.Net MVC, I found that you could pass properties to helper methods (such as Html.TextBoxFor) and it would automagically figure out the name of the property and use it to build out the ID and Name fields of the html object. I wanted something similar to that and here is my code:

//The helper class that provides the “GetPropertyName” method
public static class ReflectionHelper
{
    public static string GetPropertyName<TModel, TProperty>(this TModel model, Expression<Func<TModel, TProperty>> expression)
    {
        MemberExpression body = (MemberExpression) expression.Body;
        return body.Member.Name;
    }
}

//A test class to test what we are doing
public class Test
{
    public string Name{get;set;}
}

//A simple test
void Main()
{
    Test t = new Test();
    Console.WriteLine(t.GetPropertyName(m => m.Name));
}