Everything in Particular

April 21, 2009

The Video Game Scapegoat

Filed under: Uncategorized — bhart @ 9:38 pm

Background Info

The following is a satire I wrote 3 years ago about the stupid comments you hear from the media and other people about video games causing highschool murders. It is hard to believe it has already been 10 years since the Columbine shooting incident. People will continue to blame whatever the hell they feel like I suppose for these incidents; books, movies, games, magazines, music, to name a few. If people are determined to carry out a massacre, they’ll do it regardless of what kind of media as at their disposal. The same kind of media that is available to the rest of us who don’t go on killing sprees. Anyway, here it is.

dnbc

This is a Dateline Exlusive

jp “Earlier last week, there was a bombing at columbine high school in Colorado. The two suspects are dead and officials have been trying to figure out the motive behind the massacre. The two suspects’ rooms have been inspected by the local police force here, and they have taken a couple of pictures for us to see what kind of rooms the two boys had.”  

 

gamelibrary “Here you can see a vast array of video games. Among these games were found the titles Mortal Kombat, Doom 64, and other violent video games.”  

 

vonhitmustache “This poster of Hitler was also found in one of their rooms. From what their diaries say, they had been planning this attack for a long time and have idolized Hitler for years. They planned to attack on Hitler’s birthday, celebrating their massacre.”

 

jp “The two boys’ parents had never been very involved in their sons’ lives, and didn’t even know they were worshipping Hitler all these years and harboring so much hatred.”

 

stonerboner “So Jane, what was the reason these two boys lashed out like this and killed so many of their classmates?”

 

jp “It’s all of the video games they played. They are all bad and make kids violent and kill. They should all be banned.”

 

stonerboner “What about their obsession with Hitler and Satanism through many years of their lives? Did that play a role in making them commit their homicidal massacre?”

 

jp “No, not at all. The fact that they both had terrible parents which were rarely home and that they both adored Hitler for years had nothing to do with their violent behavior. It’s all the video games fault. They are so bad for children. Don’t buy them for your kids, or they’ll be killers too.”

 

stonerboner “So there you have it, it appears that worshipping Hitler and being involved in Satanism for years isn’t at all harmful to your kids. Neither is poor parenting or holding grudges against classmates who bully you. It’s the video games that are the only culprit. They make killers out of kids. In a nutshell, video games are the root of all evil. That is the one and only possibility and reason. Thanks Jane. We’ll be right back after a short commercial break.”

 

That pretty much sums up my thoughts on the subject. Nuff said. The original spoof can be found here.

April 4, 2009

Disgusting People

Filed under: Uncategorized — bhart @ 12:33 pm

Recap

This rant is about two types of despicable/disturbing people. But before I get into that, I’d like to recap the last rant and differentiate between stupid and despicable people. The last rant was about a stupid woman and her son who blame two months with an unexperienced teacher for the son’s entire outlook on life. I mean, give me a f^%!ing break! How stupid and overdramatic can you be? Apparenty quite a bit. Anyway, on to the first of two types of disgusting people.

Type 1

We’re all familiar with this type in one form or another.  This is the conceited, vain, stuck-up type of person who looks down on others and places themselves on a pedestal high above most everyone else.  Their attitude can be so disgusting it makes you want to smack them across the face.  They are usually dishonest with others and show complete disregard for them.  Their attitude is very disgusting.  One person who has these charactersitcs is known as Andree Close.  Its always great to see (on rare occasion) when these types of people are knocked down from their pedestals and put in their place.  I  have to applaud those who cause such people to fall from their ‘throne’.  There was one such occasion where this happened to the above mentioned person.  There was someone who came across her path that she treated like complete s!%# that retaliated, probably much to her surprise and anger.  It was probably the first time that had happened to her.  I don’t know why people are usually afraid to stand up to these types of people, but thank god someone did in her case.  It was about time someone had done something.  Apparently she was told off quite a bit through emails sent to her exposing her true character and calling her names, knocking her down a few pedestals.  Of course, being the whiny, b!tchy person that she is, she went to seek help from an even more disgusting person (yes, I didn’t know there could be another worse than her either).  This leads us to disgusting person #2.

Type 2

I don’t know whether to classify this next type as disgusting or insane.  This type of person stands up for Type 1, mentioned above.  They may even go to extreme lengths in this person’s name, ‘honor’ or any other false sense of ‘chivalry’ to attack any such ‘offenders’.  This type of person has the mentality that women have never done, can’t do, and never will do any wrong.  They have a misandrist mentality.  They think of women as above everything, even anyone’s belief or concept of anything divine, or godlike.  They classify most, if not all men as conceited, low-life  b!#tards who aren’t worth much, or anything at all.  Kevin Salmon is one such person who fits this description, and who Andree went running to when her feelings were hurt.  (oh god, what a tragedy!)  I mean, there’s nothing more important than the fragile feelings of a b#tch like her, right?  That supercedes everything else doesn’t it? To hell with everyone else.  After hearing what had happened, and being the weirdo he was and probably still is, he called the police on the person that had stood up to her.  Now that’s pretty extreme in my opinion. He is little more than a fool who protects women from getting their feelings hurt. He takes great, moronic pride in this. It doesn’t matter what they do or what they’re like, they’re all so special to him. Creepy. (*gag*)

Thoughts

I don’t know what else happened after that, but it’s a shame we have these two types of people in our societies. The two types of people above feed off each other and perpetuate the cycle of hate.  I know there are two sides to every story, but I mean really, know matter how you look at it, those two types are crazy.  Those two types of people are scary quite honestly.  It’s too bad that those who choose to stand up to crap like that are belittled and hated and have the tables turned on them.  I believe she got what she deserved and shame on Kevin for supporting people like her.

February 25, 2009

Overdramatic Parents & the education field

Filed under: Uncategorized — bhart @ 4:52 pm

The Preface

Today’s rant is about an overdramatic mother who works for the granite school district named Donna Lloyd. She sent a letter to a school where her son attended complaining about a new teacher. This new teacher had never taught before, didn’t know all the material, and was busy working on taking care of other classes he had to teach. At the time this letter was sent, the teacher had only been teaching for about 4 months, and on top of that, started right in the middle of the semester when the original teacher left, and after 2 weeks of the classes being taught by a sub. I don’t have the letter with me, but I did read it and will paraphrase the ridiculous complaints of this mother. This is just one of the many examples how parents like to play the blame game when their kids whine and act like babies when they aren’t being entertained in the school system. Pretty scary stuff.

The complaints from the parent

“My son had an F posted on the internet and couldn’t play sports until he got his grade up. I don’t know if the teacher knows that people actually look at those grades posted, but his coach wouldn’t let him play baseball until he got the grade up.”
This isn’t a teacher’s problem, this is the student’s problem. Teachers are supposed to post current grades online and its the job of the students to get the grades up with the teacher’s help if they need it. I don’t see how this was something the teacher wasn’t supposed to do. It’s his fault if he’s failing, he needs to turn in whatever assignments were missing. All of that info is clearly posted online, so yes, the teacher knows that other people see the posted grades. Isn’t that the point? Interesting that she blames her son’s shortcomings with grades on the teacher.

“The teacher couldn’t help him with every assignment he had. Thank goodness another kid in the class knew what to do to help him.”
Honestly, lady, it does take a little while getting down all the material for 4-5 different classes on your plate. The fact is, teachers don’t know everything and there are things that take them time to learn. I’ve had a few teachers in the past, (one in college that I’m currently thinking of) who didn’t know the material that well, and couldn’t teach it well either. That sometimes happens when people are new to the game and learning some of the material themselves. But I certainly didn’t whine about it and send a letter to the heads of the school. Yeah, it’s not the ideal situation having a teacher who is still learning themselves, but it DOES happen. Deal with it! That’s how life is!

I don’t really remember what else she may have whined about (and don’t care), but for the most part, they were unfounded. What was mentioned above was the gist of it. It would’ve been different if it would’ve been with an experienced teacher, etc., but there are new hires who didn’t go to college to become a teacher, who are learning the ropes. I hope someone throws her into the middle of something she’s never done before and makes ridiculous demands on her abilities and then whines to her superiors about it. My advice, Donna and her son Jacob need to stop being whiners and finding scapegoats for their problems and grow up and deal with things more maturely.

February 13, 2009

Heritage Web Solutions – A Mormon run sweat shop

Filed under: Uncategorized — bhart @ 9:07 pm

What is it?

Heritage Web Solutions is a company which makes websites and provides web hosting for owners of small businesses. It is a company run by four clueless morons known as David Aitken, Mark Strong, Brad Stone and Leah Young. It is located in Provo, Utah.

A brief history

The company started in 1999, but before that, it was a mortgage company; under a different name of course. I think they were all owners of the mortgage company except for David Aitken, who was a salesman.

Skimming the surface

On the surface, the company does have some impressive logos and websites they have completed for clients, and they are pretty cheap compared to a lot of other website companies. Their prices start at $199, which if I remember corretctly, gets you a simple, five page site which consists of a logo, html, css and javascript. Any other features such as databases, shopping carts, etc is extra (Usually a lot more money).  They also promise to get your website done in 2 weeks after you send in all the necessary materials and information they need.

Problems

Every company has their problems and have their share of unhappy customers, but this company is abysmally bad in many ways. Only by having worked there or knowing someone who has worked there can you fully know about all of the retarded things that go on there.

It is becoming a well-known fact among more and more people that the company is a sweat shop; although that wasn’t always the case in years past. It gradually became such mainly due to their salesmen selling more websites than they can keep up with. One might think that they would hire enough people to work on the websites to keep up with the demand since that would make sense, but instead they chose the cheapskate route and decided to pile an inordinate amount of work on their already existing resources.

A lot of problems in companies begins with its management. People who belong to this group in any company are usually so far removed from their employees and their daily schedules that they begin to have unrealistic expectations of how long things should take and how much work should be done in a given amount of time. That was a huge problem with Heritage Web Solutions. Not one of the aforementioned owners of the company had any experience or much knowledge about building websites, which was part of the problem.

As mentioned earlier, the workload and expectations were reasonable in the beginning, but after a short time that all changed. I’ll give you an idea of what it was like in the begginning and later on as to compare the drastic changes.

Expectations at first

1. Have a list of 20-30 websites to work on at any given time.
2. Communicate with clients after the 1st draft was done and make any necessary changes.

Getting each website done in 2 weeks was do-able as long as the clients were willing to communicate and give employees the materials needed, and if the clients weren’t so wishy washy and didn’t make multiple changes all the time.

Expectations later on

1. Have a list of 60-80 websites to work on at any given time.
2. Nearly constantly on the telephone with either one of your many clients or a random person calling into the phone queue in the company.

That’s right, many people would call into the company phone line daily and almost all employees were required to log into the phone queue. So for a good 2-3 hours a day, instead of working on websites which was part of their job description, they had to perform secretary duties as well. So many times when your phone randomly rang, you had to answer it and 98% of the time it wasn’t your client or anyone you could help. Why didn’t they just hire more secretaries to handle this and direct calls to the proper departments? To save money and give few people the work of many.

Some of these things are indicitative of many businesses, but it doesn’t make it any less absurd. So needless to say, there were random calls coming in everywhere, and nobody knew exactly who they should be transferred to; so many clients were tossed around the phone system and being understandably frustrated. Then the management had the audacity to question their employees why they weren’t completing as many websites as quickly as before. Do people in management have no common sense? As well as that, other departments would dump off their work load on another department that wasn’t supposed to, or could do the work. For example, the tech support deparment frequently sent calls from clients asking to set up an email account, or fix a technical issue to the web design department, who were only supposed to build the websites. Can you already get an idea of what a mess this turned out to be?

To top it off, they decided to make it a goal for everyone to complete two websites in a day while all this was going on. They threatened to fire anyone who couldn’t do all these things in their ridiculous time line. This company gets an F for management and its a wonder they’re even still around. It’s no wonder it turned out to be one of those companies that became a revolving door for high turn-around rate. Most people just quit after a short time after realizing the ridiculous workload and the small amount of time to do it all, and the added secretarial responsibilities they were given. Others were “let go” after they couldn’t meet their ridiculous expectations and small time frames. Those managers/owners should be fired themselves when they try and perform at their own set expectations and fail.

There are a few main reasons why this company is still afloat (amazingly).

1. They have good salesman.
2. They make monthly profits off all the websites they host.
3. They don’t give their full time employees any benefits until 1 year.

It’s incredibly cheapskate of them to do that. I’ve never heard of another company requiring their employees to wait that long for benefits. In short, it’s not a company I would ever recommend working for, unless you enjoy the above mentioned work conditions.

February 4, 2009

C#: Doing a modulus (mod) operation on a very large number (> Int64.MaxValue)

Filed under: Development, Technology — omatase @ 5:54 pm

/// <summary>
/// calculates a modulus on any number, specifically
/// designed to work around the Int64 limits of the
/// current version of c# which cannot hold a number
/// larger than 9,223,372,036,854,775,807
/// </summary>
/// <param name="iban"></param>
/// <returns></returns>
private static int largeNumberModulus(string numberToModulus, int modulusOperand)
{
string modulusWorkingNumber = numberToModulus;

while (modulusWorkingNumber.Length > 0 && !(modulusWorkingNumber.Length < 18 && Int64.Parse(modulusWorkingNumber) < modulusOperand))
{
// number to work with
Int64 currentNumber = 0;
if (modulusWorkingNumber.Length > 18)
{
currentNumber = Int64.Parse(modulusWorkingNumber.Substring(0, 18));

// remove first 18 characters
modulusWorkingNumber = modulusWorkingNumber.Substring(18);
}
else
{
currentNumber = Int64.Parse(modulusWorkingNumber);

// remove remaining used characters
modulusWorkingNumber = string.Empty;
}

string carryOver = (currentNumber % modulusOperand).ToString();
modulusWorkingNumber = carryOver + modulusWorkingNumber;
}

return int.Parse(modulusWorkingNumber);
}

January 24, 2009

TheForm is undefined / not defined error in asp.net

Filed under: Uncategorized — omatase @ 9:22 pm

`I just spent about 3 hours trying to fix this error with the LoginStatus control. The control updates fine when I log in, but when I click the “Logout” link on the LoginStatus control I wasn’t getting a postback. After a little more looking I noticed I was getting a javascript error whenever I clicked Logout. The error I was getting was “TheForm is undefined”. I googled and googled and googled and ultimately I didn’t find the fix for my problem on google but I did find a lot of different solutions to the problem. I am consolidating them with the solution for me all in one place so that hopefully noone else has to go through this.
Scenario 1

Make sure when including external Javascript files like so:


<script type="text/javascript" language="javascript" src="javascriptFile.js">

That you DO NOT self close (i.e. …src=”javascript.js” />) but that you include a close tag. The above example would look like:


<script type="text/javascript" language="javascript" src="javascriptFile.js"></script>

Scenario

The script created by Asp.Net references your form by id. Make sure your form id matches what is shown in the javascript generated. For instance mine had to be named Aspnetform so I made sure it looked like:

<form id="Aspnetform"  runat="server">

I also read that the id is case sensitive so make sure that is correct as well.
Scenario 3

Make sure your form has a runat=”server” attribute as follows


<form id="Aspnetform" runat="server">

Scenario 4

This is the one that got me. I had my form defined outside of my <body> tag. My HTML looked like this:


<form id="Aspnetform" runat="server">
&lt;body&gt;
&lt;/body&gt;
&lt;/form&gt;

This will not work. Swapt the order of your tags to be thusly:

&lt;body&gt;
<form id="Aspnetform" runat="server">
&lt;/form&gt;
&lt;/body&gt;

Hope this helps someone else.

September 15, 2008

Speed Up Your Computer

Filed under: Technology — omatase @ 4:34 pm

This is a beginners guide to speeding up your computer. This is step one of the guide. For step one we will focus on hard drives. The slowest components in your computer are those with moving parts. This is why it is best to start here. The more RAM, faster CPU craze is something that even consumes some of the experts. The fact is though, that more RAM, faster CPU might not actually be what you need. Indeed spending money on these components might not do anything to speed up your computer at all!

This is the first in a series of articles designed to make it easy for you to know how to speed up your computer (pc or laptop) with the least amount of money or work.

How to know if you need a faster hard drive

Laptop Users:

Most laptops come with slow hard drives to help increase battery life. Although this is the case, putting in a faster hard drive is not likely to cause any battery life problems.

Step 1: What am I working with now?

Most laptops come with 5400 RPM hard drives and most PCs come with 7200 RPM drives. If this is the case for your computer and you are looking to speed up your computer and extend its life, you need to upgrade that to a faster drive. First, though, let’s check your current drive speed. Click: Start, All Programs, Accessories, System Tools, System Information. This should give you a screen that looks like the following:

System Information - Disks

System Information - Disks

Using the above image as your guide, expand Components, Storage then select Disks. On the right-hand pane you will see a description of your disk drive.  Write down the Model (In my case HTS721080G9AT00) and do a search for it on Google. This should bring up results that will give you specification information for your drive and tell you what speed it is. To find the speed look for the numbers 5400 or 7200 and the letters RPM. Drive speed is measured in many ways, the RPM specification shows you how fast the disk spins. Here are the specifications on newegg for my drive:

 

I have highlighted the RPM specification to make it stand out a little more for you.

Once you know your speed you know if an upgrade can help speed up your computer. This is the case if you are using a laptop and you have a 5400 RPM drive (or less) or if you are on a desktop and have a 7200 RPM drive (or less). Here are some links to some good drives that I can recommend to help speed up your computer.

All of these links are from a company called Newegg. I have been a Newegg customer since October of 2003 when they were first getting started. I cannot recommend any online retailer more highly which is why all of my product recommendations link to them.

These links are for some great hard drives focused at performance for your PC or laptop (ordered by most highly recommended) – Updated 09/2008:

Laptop (price range before shipping: $99.99 – $164.99):

Laptop Hard Drive #1

Laptop Hard Drive #2

Laptop Hard Drive #3

PC (price range before shipping :  ($149.99 – $294.99)

PC Hard Drive #1

PC Hard Drive #2

PC Hard Drive #3

June 23, 2008

Bulk / Batch Printing on a Network Attached Epson Dot Matrix Printer

Filed under: Development, Technology — omatase @ 9:49 am

I recently had the “opportunity” to learn first hand how to go attack the topic of batch printing against an Epson Dot Matrix Printer. I’m posting this here to document my woes and difficulties on this very bumpy road.

Defining the Problem

Why should batch printing be any different than single printing? There are a few simple reasons this is different:

  1. Running out of paper
  2. Paper jams
  3. Printer becomes paused

Basically the problem is, if you send 100 print jobs to the printer, you want some way of assuring the jobs actually completed. Imagine if you sent 100 print jobs to the printer and the printer runs out of paper at 50. If your application isn’t set up to do batch printing properly it will send the remaining 50 jobs to the printer even though the printer may have no way of receiving them. Whether it is capable of receiving these jobs is really a matter of the model and how much memory it has to queue up your jobs. The size of the print jobs is also a factor. So your application happily sends the remaining 50 jobs to the printer, how many ultimately print successfully when the paper is loaded? 20? If so what happens to the other 30 print jobs? How does the user even know that they didn’t print or which ones didn’t print?

Finding the Answer

Epson was exactly 0 help on this issue. There was no information online that even gives a hint of a clue of an inkling of where to even start looking. So, I emailed their support department. Here is the email I sent them:

I am writing an application that will print invoices to [a printer with model #LQ-2090]. One requirement of this application is for batch printing. I have a few questions about the support for batch printing with this printer:
1. If it runs out of paper while jobs are being sent to it, what is its behavior? Does it queue requests? What queue limitations (memory limit etc) does it have?
2. If #1 isn’t possible is there a programmatic way to query when the printer is out of paper or otherwise unable to print?
This email was sent originall on 06_05_2008. Since I was actively working on the application I couldn’t wait for their response. The chances it would take too long or that it wouldn’t be helpful were too great. So I did some researching of my own as well. Ultimately the answer came through my own research. I think Epson sent some response about how much memory was available on the printer and then said there was “no way” to ask the printer for a status. So just as I anticipated the response didn’t yield any information that would be helpful, in fact it was wrong about not being able to query the printer for a response. Their email also came several days after I wrapped up the project. I can’t find their response so I can’t say the date exactly but I want to say it took them something like 2 weeks to respond.

The Solution

Ultimately, as I said, I found the answer myself. I was coding along happily one day when one of my colleagues mentioned there was a web server built in to the network card we installed in the printer. Curious, I decided to check it out. It was from that web site that I got my first glimmer of hope. The printer supported SNMP and there were configuration items for setting up SNMP and SNMP traps Sweet! My first instinct was to do it all through traps. Surely the printer would send me a message saying “Please Load Paper” or something like that whenever there was an alert. So I pulled out my Trap Receiver application (iReasoning) and told the printer to send all traps to my desktop. With that all set up I simulated a few scenarios by forcing an out of paper situation, a paused situation and a jam situation. From across the room I could see my trap receiver filling up with traps. Excited I ran over to my computer to see what information the printer was sending me. My elation was premature and short lived. For a few minutes I compared the different traps I had received trying to notice differences. If I was sent the number 12398521 for instance whenever the printer was out of paper, I could just put those values in a config file and be done with it. What I found though over the course of a few minutes was that every trap was the same! What? It didn’t even matter if the trap was sent for a different reason, the data I recieved was exactly the same! Well, the same save for the fact that it was including in the trap an incrementing number. So the first trap sent 0, the second sent 1, the third 2 and so on. Well this is completely useless! If I want to know how many traps I have received I can count them myself! :) . I have a little experience with SNMP traps but if this is a standard thing to do with traps this is a new one for me. Whenever I send a trap I include a human readable message letting someone (or some program) know what is going on. Ultimately I did figure out (I think) what these incrementing numbers were supposed to be telling me. More on that later though. Well, it was apparant that the SNMP traps weren’t going to be of any use. I could treat them like a toggle I guess, but how would I know to have the toggle on or off to begin with? How would I know if I got a message even if the printer was capable of continuing to print? This is not a solution I would except, so I decided to keep looking. The next place I began looking was google. I decided to do a search for something less specific, a search that didn’t include Epson or LQ2090. Doing that got me a hit that ultimately led to the answer. The hit I got was of someone asking how to use SNMP messages to get printer status information. While the article I found was for a different printer and didn’t have any information in it that was, in the end, directly usable getting the hint that SNMP messaging is a possible route I could go was invaluable.

From there it was more and more google searches that led me to this real gem (extreme sarcasm applied here): ftp://ftp.pwg.org/pub/pwg/pmp/mibs/rfc1759.txt. This my friends is rfc 1759. I recommend you look away, look away! Everytime I try to get any useful information from an RFC it always leaves me asking “WHY!?!”. Why on earth would someone write this, and how is it supposed to be useful? After a lot of searching I was finally able to find a guide that explains the RFC. This guide broke down the RFC terminology and explained what it meant, then gave the SNMP OID for each item. This guide, IMO should be the RFC. In any case, guide useful, RFC useLESS! *sigh* ok I feel better now.

As much as I have talked up the guide, it was also ultimately of no help :( . Although it did contain what I was searching for, I couldn’t find what I was looking for as a consequence of just not expecting what I was looking for to be called what it was called.

So how did I find the answer? Good old trial and error / brute force. I opened up my MIB browser app (also by iReasoning) and told it to hit the printer with every SNMP message possible by doing a walk on OID 0. This yielded hundreds of results, with after a little doing I was able to copy into a text file and save it. I did this 3 times: once when the printer had paper and was good to go, once when the printer was in an out-of-paper error state, and once when the printer was paused. I then took those 3 files and did a diff on them using KDiff (a very nice diffing tool). What I found is below (you will want to click to enlarge):

printer diff

The OID that is shown in this diff is the “printmib.prtAlert.prtAlertTable.prtAlertEntry.prtAlertDescription.1″ OID. While this seems like a very reasonable thing to call it I was still unable to find it through my searches either in google or in the above-mentioned guide. I was always searching for things like “printer status” or “out of paper”. In any case, this brute force method did give me all I needed to begin querying the printer for its current state and so I was basically done with my discovery session. I don’t know all of the unique alert descriptions that can be retrieved from this printer on this OID (I couldn’t find a list anywhere from epson even after I knew some items on the list) but here are those I have found: supply the paper, remove the paper, paused. Of course it is not unlikely for this to be different between printer manufacturers and models so you may have to do a bit of trial and error.

One Final Small Problem

One minor final thing I ran into was that the OID would change slightly upon each new alert. The first alert would show up under OID printmib.prtAlert.prtAlertTable.prtAlertEntry.prtAlertDescription.1.0, the second printmib.prtAlert.prtAlertTable.prtAlertEntry.prtAlertDescription.1.1 and so on up the number scale until the printer was power cycled. This gave me another “A-HA!” moment when I suddenly realized what those stupid traps I mentioned before were all about. The aforementioned printer RFC had some information in it indicating the printer could have multiple rows of alerts in a table in its MIB and that there needs to be some method by which one can return things like total number of alerts and current alert index via SNMP. I never figured out how to send an SNMP message to the printer to retrieve the current alert index (although the RFC seems to indicate it is possible), but I now realized the incrementing number in the traps was the alert index. I could then use that number to construct the correct OID for my SNMP message querying the printer for its alert status description! Pretty cool!

Now, For those of you who aren’t receiving or cannot programmatically receive traps from your printer another solution to this problem (and the one I ended up implementing) is to attempt to get the alert description at OID .0. If that fails (or returns an empty value), tell your SNMP client to do a GetNext(). If the GetNext returns a non-empty value that belongs to an OID that begins with “printmib.prtAlert.prtAlertTable.prtAlertEntry.prtAlertDescription.1″, then you are good to go. Here is some sample code that does that for your reference:


while (manager.LastError == 0 &amp;&amp;  returnedValue.OID.StartsWith(oid))

{

value = returnedValue.Value;
returnedValue = SnmpObject.manager.GetNext();

}

When this loop completes “value” will have the “next”-most value for the OID we are targeting.

All Done

This marks the end of the material I set out to cover. Hopefully this will be useful to anyone trying to get a batch printing application off the ground. SNMP is universal so as long as your printer is network attached, even with vastly different features, the solution could likely be similar.

Comments and questions welcome, thanks!

January 24, 2008

Making Use of the Find, FindIndex or FindAll Methods With Generic Lists in C#

Filed under: Development — omatase @ 12:59 pm

I often find myself in a position where I have a collection of objects and I need to determine if a particular element exists in the list. In the past (versions of C# prior to 2.0) whenever I had a list I knew I was going to have to search through I would make use of a Dictionary object. The Dictionary object provides built-in very fast searching. In my pre-.Net life I was a VB6 developer and was always forced to write my own quick sort and binary search routine for such a task. Fortunately for us Microsoft has seen the value and need of making this available in the framework.

Aren’t Dictionaries Overkill?

The difference between a generic List however, and a Dictionary are that the Dictionary requires a name and a value for each item in your collection. What if you only want a list of values? I have to admit I have made up some “names” just to appease the requirements of the Dictionary object so I can add my values and take advantage of the great searching capabilities already provided by the dictionary object. Whenever I do this though it never quite sits right with me. No, I’m not worried about memory overhead. I haven’t even checked memory usage but that’s because there really wouldn’t be any point with the amount of memory available on even relatively older machines compared to the amount of memory a few thousand integers would take. No, the nagging feeling has always been that it’s a work around. I’m using a screw driver to do the job of a hammer in some ways and it doesn’t sit right with me.

Let’s do it right

One day I decided enough was enough. I was going to figure out a way to use built-in framework methods to do searching on a generic list. Looking at the intellisense for an instantiated List<string> showed there were a few methods that might do exactly what I needed. (In retrospect I do believe these are methods I had seen and tried to use before but without any luck. You may see here shortly why I gave up the first time I tried, it is certainly not implemented in an intuitive way). Those methods are Find, FindIndex, and FindAll. That might not be a complete list but these three all work the same and so any others may very well as well. I’m also not going to show how to do this on all three methods since, as stated earlier, they work the same.

Searching for the answer

My quest to begin using these methods started with the intellisense. I looked at the parameters for all of the overloads on the Find method. I noticed a recurring parameter it expected was a “predicate” which excuse my ignorance but I had no idea what that was. Since each of the overloads required a predicate, and I didn’t know what one was, I knew my searching through the intellisense quest was over. I needed an example of how to use this. So I did a Google search, something like [Generic List Find] (without the brackets). The first result was to this MSDN article http://msdn2.microsoft.com/en-us/library/x0b5b5bc.aspx . Below is the relevant code excerpt from the article.


using System;
using System.Collections.Generic;

public class Example
{
public static void Main()
{
List dinosaurs = new List();

dinosaurs.Add("Compsognathus");
dinosaurs.Add("Amargasaurus");
dinosaurs.Add("Oviraptor");
dinosaurs.Add("Velociraptor");
dinosaurs.Add("Deinonychus");
dinosaurs.Add("Dilophosaurus");
dinosaurs.Add("Gallimimus");
dinosaurs.Add("Triceratops");

Console.WriteLine();
foreach(string dinosaur in dinosaurs)
{
Console.WriteLine(dinosaur);
}

Console.WriteLine("nTrueForAll(EndsWithSaurus): {0}",
dinosaurs.TrueForAll(EndsWithSaurus));

Console.WriteLine("nFind(EndsWithSaurus): {0}",
dinosaurs.Find(EndsWithSaurus));

Console.WriteLine("nFindLast(EndsWithSaurus): {0}",
dinosaurs.FindLast(EndsWithSaurus));

Console.WriteLine("nFindAll(EndsWithSaurus):");
List sublist = dinosaurs.FindAll(EndsWithSaurus);

foreach(string dinosaur in sublist)
{
Console.WriteLine(dinosaur);
}

Console.WriteLine(
"n{0} elements removed by RemoveAll(EndsWithSaurus).",
dinosaurs.RemoveAll(EndsWithSaurus));

Console.WriteLine("nList now contains:");
foreach(string dinosaur in dinosaurs)
{
Console.WriteLine(dinosaur);
}

Console.WriteLine("nExists(EndsWithSaurus): {0}",
dinosaurs.Exists(EndsWithSaurus));
}

// Search predicate returns true if a string ends in "saurus".
private static bool EndsWithSaurus(String s)
{
if ((s.Length &amp;amp;gt; 5) &amp;amp;amp;&amp;amp;amp;
(s.Substring(s.Length - 6).ToLower() == "saurus"))
{
return true;
}
else
{
return false;
}
}
}

I won’t go into detail on how this code works. Please visit the article directly for that. But I will point out one big problem with this example. The method that tells Find how to determine if it has ‘found’ what it is looking for has a hard-coded string in it. It is searching for a hard-coded value. This method is the “EndsWithSaurus” method. Notice how it is doing a string comparison on “saurus”.

This doesn’t help me at all! Unless I know at design time what I would be searching for. But what if I have two lists. One list is a master list of countries in Asia and the other list is a supposed subset of that list. Let’s say it is a list provided from user input. I want to validate the list the user has provided contains only countries that exist in Asia. So I need to iterate through each item in the user-provided list and for each iteration of the loop determine if the current item exists in the Asia master list. Something like this:


private void validateUserInput(List listWithValuesEnteredByUser)
{
List asiaList = MethodThatReturnsAllCountriesInAsia();

foreach (string current in listWithValuesEnteredByUser)
{
// determine here if the value exists
}
}

Now I’m suddenly in a sport where I can’t hardcode the search routine that Find, FindIndex or FindAll might use. We all know that hard coding is a bad idea anyway so we shouldn’t get away with it even if we can but you see my point. And since we all know hard coding is bad, we all also know making use of a wider scoped variable in this case would be bad as well right? We shouldn’t even look twice at that temptation. It’s a hack and a work around as seen here:


// ugly work around hack
string _widelyScopedVariable = string.Empty;

private void validateUserInput(List listWithValuesEnteredByUser)
{
List asiaList = MethodThatReturnsAllCountriesInAsia();

foreach (string current in listWithValuesEnteredByUser)
{
// ugly work around hack
_widelyScopedVariable = current;

if (string.IsNullOrEmpty(asiaList.Find(findCountry)))
{
// country not found. user input found to be invalid
}
}
}

private bool findCountry(string input)
{
// ugly work around hack
return _widelyScopedVariable == input;
}

The Answer

So what is the correct way of doing the above? Anonymous delegates. With anonymous delegates we can embed a method that will share the scope of our loop. This means it will have access to “current” which is what we are searching for. Here is some sample code:


private void validateUserInput(List listWithValuesEnteredByUser)
{
List asiaList = MethodThatReturnsAllCountriesInAsia();

foreach (string current in listWithValuesEnteredByUser)
{
if (string.IsNullOrEmpty(asiaList.Find(delegate(string input)
{
return (input == current);
})))
{
// country not found. user input found to be invalid
}
}
}

Wrapup

Not only does this significantly shorten the code we have to write (a definite plus) but we also don’t have to use any ugly hacks.

It is important to note that “input” is defined as a string because the list I am searching through is a list of strings (List). If for instance you have a generic list defined like: List<Animal> then the parameter changes from “string input” to “Animal input”.

It is also important to say that since it cannot be assumed that your generic list is sorted and in some cases can’t be sorted it is not possible for this built-in routine to search your list using a binary search and therefore is likely to be less efficient than the dictionary search.

September 5, 2007

Clearing the read-only flag on a file in C#

Filed under: Development — omatase @ 4:58 pm

FileInfo myFile = new FileInfo("c:\\myfile.txt");

if ((myFile & FileAttributes.ReadOnly) == FileAttributes.ReadOnly)
{
// remove the read only attribute
myFile.Attributes = (FileAttributes)(Convert.ToInt32(myFile.Attributes) - Convert.ToInt32(FileAttributes.ReadOnly));
}
Older Posts »

Powered by WordPress