XYZPDQ

3/27/2009

Response.Redirect inside of a Try/Catch

Ok, first off, let me state, that I am not entirely certain WHY I did this in the first place.  I am going to say I was rushed and wasn’t thinking clearly.  However, I glazed over it and moved on and when it came time to test, I was getting bizarre behavior that didn’t throw an error.

Session[“var”] = “”; 

try 
{ 
    Session[“var”] = “Good Value”;

    Response.Redirect(“newpage.html”); 
} 
catch(Exception ex) 
{ 
    Session[“var”] = “Bad Value”; 
}

In the code above, Session[“var”] will ALWAYS equal “Bad Value”.  Why you may ask?

Response.Redirect throws a ThreadAbortException.  … Fun, no?

If you are building a URL inside of a try block that you want to then redirect to, declare a string, build your url, and then pass that on to the Response.Redirect statement. 

For Example:

string _url;

try 
{ 
    _url = “yourpage.aspx?var=” + iffyMethodCall(); 
} 
catch(InvalidOperationException ex) 
{ 
    _url = “error.html”; 
}

Response.Redirect(url);

So, If you ever run into odd behavior in a site you are working on and when debugging, your code goes straight past your Response.Redirect and into the catch block and the debugger starts giving you cryptic messages, this may be what you’re seeing.

12/7/2008

IIS Worker Process Fail 503 Error

Helping a friend to configure his new Win2k8 Server with IIS7 this weekend we ran into an issue where IIS kept returning 503 errors.

Examining the Application Event log I saw that  IISW3SVC-WP was quitting due to application errors. "The error is the data".  How helpful.

After a considerable amount of digging I discovered that in the Microsoft.Net/Framework/ folder, there was a beta version of v2 of the framework.  The only version that *should* be there is v2.0.50727. 

I deleted the beta version of the framework and restarted the IIS worker processes that were causing problems and everything immediately burst to life!

I've no clue what installed the beta version of the framework, but it is a definite lesson to make sure that when distributing a framework to be 100% certain that you are always including the latest "release" version... oh yeah, and perhaps doing a check for an existing version of said framework before installing.

At any rate, hope this helps somebody.

12/4/2008

Useless entry #268

While in a chat today, the following conversation occurred...

After I stopped laughing I had to post it.

A : I had a mouse in my well the other day. I shop-vac-d it out.
B : lol, I can hear it now... "whrrrrrrrrr, ssshhTHUNK"
C : *phoomp*
D : and forever after the other mice tell tales of abduction from above
D : "seriously, it was like some kind of tractor beam!"
B : But is derided as a crazy mouse.


9/8/2008

Whedon Quote

I am not sure how many of you are Whedon fans like myself.  I came across this today and I'm posting it in part because it is, in my opinion, phenomenal, and also so that I have an easy place to look it up in the future.

Passion, it lies in all of us, sleeping... waiting... and though unwanted... unbidden... it will stir... open its jaws and howl. It speaks to us... guides us... passion rules us all, and we obey. What other choice do we have? Passion is the source of our finest moments. The joy of love... the clarity of hatred... and the ecstasy of grief. It hurts sometimes more than we can bear. If we could live without passion maybe we'd know some kind of peace... but we would be hollow... Empty rooms shuttered and dank. Without passion we'd be truly dead.

-- Joss Whedon

8/25/2008

Why I am a Republican - Kinda

I normally abhore forwards.  However, I recently received one that I thought was magnificent.

....................................................................................

FATHER AND DAUGHTER

A young woman was about to finish her first year of college. Like so many others her age, she considered herself to be a very liberal Democrat, and among other liberal ideals, was very much in favor of higher taxes to support more government programs, in other words redistribution of wealth.

She was deeply ashamed that her father was a rather staunch Republican, a feeling she openly expressed. Based on the lectures that she had participated in, and the occasional chat with a professor, she felt that her father had for years harbored an evil, selfish desire to keep what he thought should be his.

One day she was challenging her father on his opposition to higher taxes on the rich and the need for more government programs. The self- professed objectivity proclaimed by her professors had to be the truth and she indicated so to her father. He responded by asking how she was doing in school.

Taken aback, she answered rather haughtily that she had a 4.0 GPA, and let him know that it was tough to maintain, insisting that she was taking a very difficult course load and was constantly studying, which left her no time to go out and party like other people she knew. She didn't even have time for a boyfriend, and didn't really have many college friends  because she spent all her time studying.

Her father listened and then asked, 'How is your friend Audrey doing?' She replied, 'Audrey is barely getting by. All she takes are easy classes, she never studies, and she barely has a 2.0 GPA. She is so popular on campus; college for her is a blast. She's always invited to all the parties and lots of times she doesn't even show up for classes because she's too hung over.'

Her wise father asked his daughter,

'Why don't you go to the Dean's office and ask him to deduct 1.0 off your GPA and give it to your friend who only has a 2.0. That way you  will both have a 3.0 GPA and certainly that would be a fair and equal distribution of GPA.'

The daughter, visibly shocked by her father's suggestion, angrily fired back, 'That's a crazy idea, how would that be fair! I've worked really hard for my grades! I've invested a lot of time, and a lot of hard work! Audrey has done next to nothing toward her degree. She played while I worked my tail off!'

The father slowly smiled, winked and said gently, 'Welcome to the Republican party.'

....................................................................................

If anyone has a better explanation of the difference between Republican and Democrat I'm all ears.

*UPDATE*

Ok. So, after a day of politically inspired tweets & conversations with friends, I don't think that I am really a republican per se.  I am conservative no doubt, but I honestly don't think I am as staunch as some of the card carying republicans out there like my father.

I recieved the following from a good friend (who was apparently unable to post a comment to my blog... I need to investigate that)

...........................................


The largest logical problem with that post, and coincidentally one of the most fundamental problems both parties have with complicated issues like welfare, is that it breaks down such a complicated issue into a simple moral dilemma.  Welfare isn't about morality, though its implementation may be immoral.  Whether a child has enough to eat isn't the same as whether you get a good grade in school.  In fact, to suggest such is quite insulting, though I'm sure that wasn't the intent by the OP.  Welfare, fundamentally, is disaster insurance.  You pay into a group fund when you can, and when you need it, the fund is available to you.
 
A far more appropriate comparison would be the following discussion between the same father and daughter.  We pick up the story where she's talking about her friend.  She's the same party girl as before, but this time, instead of the discussion pointing out that her grades were low due to her lifestyle choice, she had instead been assaulted at such a party.  When asked by her father how she handled herself at parties, she responds that she would never go to such places and if she did she'd mace a guy trying anything like that.  When asked if she'd give up her mace to her friend, she replies in the same way as before: why would I suffer because I am prepared, she deserved it since she didn't prepare, etc.  Of course, her father replies, "Welcome to the Republican Party".
 
The point is that both parties indicate that you don't know how to run your life.  Democrats want to provide for those who can't provide for themselves.  Republicans want to act as examples for those who have fallen.
 
I have a different view, and, yes, I'm a libertarian.  There should be no welfare, nor any judgement - at least not by the state.  When a wealthy democrat was told the libertarian ideal, he replied, "Who will care for the homeless."  "You will," came the response.  "You mean, people with money will get together and..." he was cut off.  "No, YOU will."  There is no welfare in a libertarian state, just concerned citizens.
 
This country has never been libertarian, and likely never will be.  We're far too full of ourselves to accept responsibility without structure or recognition.

...........................................

A good point that is going to lead me off on a tangent.  I believe that as a general rule, people should not be given hand-outs.  However, if you are making an effort to get ahead in the world and are simply not able to do it, no matter how hard you are trying, then I will give you my assistance.  I am not heartless, but I do think that people who make no effort whatsoever to better their situation and similarly do nothing but sit and complain about it, are not deserving of my sympathy.  Personal accountability is becoming more and more infrequent in today's world.  There is a definite sense of entitlement.  News flash people. Nobody OWES you anything.  If you want something, go out there and bust your butt.  99 times out of 100, if you try hard enough, you are going to succeed.  On some level, life is fair.  The people who say that life isn't fair simply stopped trying and let their gaurd down.   There is a saying, "you get out of life what you put into it".  If you keep a positive attitude and give every day your best, then you are going to live a happy and successful life.  Just don't blame anyone else for your choices.

I realize that this post started off one way and has devolved into something COMPLETELY different.  This is my blog though.  If you do not like my chain of conciousness, then go read somebody elses blog.

8/2/2008

Vista…My Take

Alright.  It's time to weigh in. 

I have been using Vista for quite a while now, and while it does have its shortcomings, it is a dramatic improvment over XP.

I've listened to a lot of the reasons that Vista = FAIL, but I think a lot of them boil down to the requirements that the OS takes to run properly.  Let's face it, as computers have gotten faster and RAM more abundant, EVERY operating system out there has gone out of its way to take advantage of the extra resources.  Some more than others, but they've all adapted.

So, let's examine some of these requirements for "Windows" past.

Released Processor Speed RAM (MB) HDD (MB)
Windows 95 Aug-95 20 Mhz 4 MB 50 MB
Windows 98 Jun-98 66 Mhz 16 MB 210 MB
Windows 2000 Feb-00 133 Mhz 32 MB 700 MB
Windows XP Oct-01 233 Mhz 64 MB 1.5 GB
Windows Vista Januery 2007 800 Mhz 512 MB 15 GB

If we were to graph this, we would see that with the exception of storage, the requirements have risen at a fairly constant rate over the years.

Requirements.JPG

The most important thing that I see here is that big gap between 2001 and 2007.  From my perspective, what has occured is that there are a considerable amount of computers out there dating back to the turn of the millenium that were more than capable of running XP and still are, but are simply not powerful enough to meet Vista's minimum requirements.  This is also a large reason that business and corporations are not jumping on the upgrade.  It would mean purchasing a whole stock of new computers.

That large gap was Microsoft's biggest mistake.  By sticking to a more frequent release schedule they not only minimize the gossip of issues, but also minimize the whollop of new system requirements.

The other major reason that a lot of people are griping about Vista is program compatibility.  A lot of programs simply will not run on Vista.  Especially if you are running 64-bit.  While Microsoft has gone out of its way to ensure backward compatibility, they should not be responsible for making a program that was written in 1995 work on a modern OS, that is the job of the software manufacturer/developer.   I would also stipulate that if you are a company using a program that old, and the manufacturer has not released an update to allow it to run on today's more modern systems, then you should seriously investigate newer options.  Other OS's don't even bother with backwards compatibility, leaving it entirely the problem of hte developer to release an update...those of you using an Apple product will know what I'm talking about.

Regardless, it has been a year and a half now, SP1 has been released and there are very few remaining glitches.  If you haven't tried Vista yet, give it a try... an honest try.  If after a few weeks, you are still dissatisfied and agree with the naysayers, then by all means, downgrade to XP and continue griping.

5/11/2008

SQL Injection Attacks

Some of you may have noticed (hopefully not) that your sites or sites you visit have been victims of a SQL Injection attack that is referring to scripts at either wowyeye.cn or direct84.com.  It primarily works against sites that have SQL Server as a database and seems to be targeting primarily ASP and ASP.Net sites.  I have seen a few references to PHP sites and the like, but not many.

There is not a lot of information out there about this, but the best page I have found describing the problem is here: http://hackademix.net/2008/04/26.  I am not going to rehash everything on that page, but if you are uncertain if you have been hacked, I have taken the script that is behind this and modified it for the powers of Good.

DROP TABLE #SCRIPTTABLE
GO

CREATE TABLE #SCRIPTTABLE (TABLENAME VARCHAR(200), COLUMNNAME VARCHAR(200),RECORDCOUNT INT)

DECLARE @T VARCHAR(255), @C VARCHAR(255);
DECLARE TABLE_CURSOR CURSOR FOR
SELECT A.NAME, B.NAME
FROM SYSOBJECTS A, SYSCOLUMNS B
WHERE A.ID = B.ID AND A.XTYPE = 'U' AND
(B.XTYPE = 99 OR
B.XTYPE = 35 OR
B.XTYPE = 231 OR
B.XTYPE = 167);


OPEN TABLE_CURSOR;
FETCH NEXT FROM TABLE_CURSOR INTO @T, @C;
WHILE (@@FETCH_STATUS = 0) BEGIN
PRINT @T + ' ' + @C
EXEC(
'INSERT INTO #SCRIPTTABLE SELECT ''' + @T + ''',''' + @C + ''', COUNT(*) FROM [' + @T + '] WHERE [' + @C + '] LIKE ''% 0

I hope this can be of use to somebody.  I encourage you to check your database to see if you have been attacked and are not aware.  I also encourage you to use the best practices out there and make sure that your code is as protected against these kinds of attacks as you are able. 

Good Night, and Good Luck.

*UPDATE: http://www.0x000000.com/?i=556 has a lot of good information regarding this attack. 600,000+ sites have been hit now.

4/4/2008

Exploring WCF

I have been learning Windows Communication Foundation (WCF) recently.  While there are a LOT of frustrations involved with it, it is leaps and bounds better than what was previously available in the .Net world.

One thing I have discovered about WCF though is that there is precious little information about it available (in comparison to other .Net related topics) .  With that in mind, I thought I would start sharing some of the things that I am learning.

First of all WCF does its work through contracts.  The two main types of contracts that we'll focus on here are Service Contracts, Operation Contracts, and Data Contracts.  A Service Contract describes which operations the client can perform on the service. Operation Contracts expose a method as a operation to perform as part of the service. Data Contracts define which data types are passed to and from the service.

The contracts are applied to your classes, methods, variables as attributes.
For instance:

[ServiceContract]
interface ISample
{
//Will be included in the  service
[OperationContract]
string  SayHelloSample(string name);

//Not included as part of  the service
string SayGoodbyeSample(string  name);
}

In the above example, we are defining an interface for a service and exposing SayHelloSample as a operation for that service.  Only classes/interfaces with the ServiceContract attribute and methods with OperationContract will be recognized by WCF.

So, now that we've covered some of the basics, let's jump into a project...

Using Visual Studio Click on File > New Project
Choose your favorite language and the Select Web in the tree and select WCF Service Application
Visual Studio will stub out a service for you automatically. 

You will have 3 files for each service you create.

  • An Interface for the service - ISample.cs
    It is generally considered best practice (and in fact WCF was designed with this in mind) to define your contracts in a separate interface that you then use to implement your service in a separate class.
  • The Service file itself - Sample.svc
    The "visible" file people will connect to when calling your service
  • The Code-Behind for the Service - Sample.svc.cs
    This is where you will code the behavior for the operations defined in the contract interface.

Visual Studio implements the infamous "Hello World" to lay out a simple service for you to start from.

Let's start by examining the interface.  The first thing to notice will be the namespaces that are imported to support WCF ( System.Runtime.Serialization and System.ServiceModel).  If you are going to add contracts to any existing classes or objects you may have, then you will need to make sure these two namespaces are included in your using/imports.

The interface defined here will have two methods: GetData and GetDataUsingDataContract.  Given the similarity to the previous interface sample I have already shown, I won't write out the code here, but notice that the Service and Operation contract attributes are on the interface and methods.

Under the interface you should see a class defined called CompositeType.  Here is an example of a Data Contract. 

[DataContract]
public class CompositeType
{
bool boolValue = true;
string stringValue = "Hello ";
[DataMember]
public bool BoolValue
{
get { return boolValue; }
set { boolValue = value; }
}
[DataMember]
public string StringValue
{
get {  return stringValue; }
set { stringValue = value; }
}
}

You will notice the DataContract attribute applied to the class.  This is telling WCF that we want this class/struct to be part of our service contract and to serialize it for incoming/outgoing messages. Inside the class/struct itself, for each property / variable that we would like WCF to take not of and serialize, we decorate it with the DataMember attribute.  Much like with the OperationContracts, anything that does NOT have the DataMember attribute will be ignored by WCF.

Looking at the code behind that was generated for our service, we will see that it is inheriting from the contract interface.  Notice here that because the contracts were already specified in the interface, we do not specify them here on the class itself.

public class Sample : ISample
{
public string GetData(int value)
{
return string.Format("You  entered: {0}", value);
}
public  CompositeType GetDataUsingDataContract(CompositeType composite)
{
if (composite.BoolValue)
{
composite.StringValue +=  "Suffix";
}
return composite;
}
}

When GetDataUsingDataContract is called, WCF will take care of serializing the CompositeType class to the appropriate format depending on what kind of service you are developing.  In this case, XML. Also, be sure to open the web.config and look at the new system.ServiceModel section at the bottom.  This is where the service gets exposed/defined and will be where you will configure the security and accessibility of your service.  I will be writing more on this in the future.

As you can imagine, if you have existing code already written with custom objects / methods, by simply adding the appropriate attributes, it becomes very simple to expose them via WCF.

I highly encourage everyone to dig into WCF and poke around.  It is an incredibly robust and powerful framework and is a definite step forward for .Net based services.

3/23/2008

Spaghetti with Meat Sauce

Incredients:

  • 1lb of ground beef
  • 2 large Prego (traditional)
  • 1lb of italian sausage
  • 4 slices of bacon
  • 1 package of sliced mushrooms (~2 cups)
  • 1-2 tblsp of minced/diced garlic
  • 1 tblsp butter
  • 1 cup red wine (merlot/shiraz/chianti/etc)
  • fresh basil
  • oregeno
  • garlic powder
  • onion powder

Instructions:

Note:  This will make a LOT of meat sauce, so either fiddle around with the proportions, or be prepared to feed a lot of people / have leftovers.

In a LARGE pot (or crock pot), pour both bottles of Prego sauce and combine 2 minced basil leaves, a large sprinkling of dried oregano, and a pinch or two of salt and start on a very slow simmer for 4 hours.

In a large skillet, combine the butter, garlic and bacon.  When the bacon is mostly reduced, add in the mushrooms and sautee the mushrooms.  When the mushrooms are nearly finished, pour the wine in and continue to cook until the wine is mostly reduced.

Leaving the grease and wine in the saucepan, carefully scoop the mushrooms and bacon into the sauce.

In the saucepan mix the beef and the sausage and sprinkle with onion powder, garlic powder, and salt (to taste). Once the meat is cooked, drain off all the oil and combine the meat into the sauce.

Check on the sauce every 15-30 minutes and stir completely to make sure nothing is sticking to the bottom or sides as well as mix the sauce that has bubbled to the top back into the sauce.

After the sauce has simmered for ~3.5 hours, start cooking the noodles.

3/21/2008

WPF: Element State Binding

I've been working with WPF lately.  Partly for work, but mostly to teach myself while at the same time being productive.  I am definitely one of those people that learns best by doing.

I have been working on adding some encryption to a application recently and I am making a form that will allow the user to enter a password that will be used for the encryption/decryption process.

encrypt.jpgOn the form that I made, I had a checkbox to determine whether they even want to use encryption at all, as well as two password boxes for the password and the confirmation.  I wanted to make it such that when they clicked the checkbox that it would enable the password fields and disable them when the checkbox was unchecked.  Essentially tie the IsEnabled property of the PasswordBox's to the IsChecked property of the CheckBox.  

Well, I could tie a method to the Checked event of the CheckBox, and then adjust the PasswordBoxes accordingly, or I could do it the WPF way and use Binding to tie the elements together to one another.

Opting for the latter (since I am trying to learn after all), I dug around in my WPF book and in short order, had the answer.

Assuming that the CheckBox is named checkbox1:

<PasswordBox Name="Password1" Margin="0,5" Width="200"
IsEnabled="{Binding ElementName=checkbox1, Path=IsChecked}"/>

What is happening here is that WPF is telling the IsEnabled property to watch checkbox1 and specifically the IsChecked property of that control and grab the value from there.

Pretty cool stuff.