Sunday, December 19, 2010

FormatBytes() - How big is that?

A handy function for formatting bytes, such as disk or file sizes.

1,024 bytes = 1 KB
1,048,576 bytes = 1 MB
1,073,741,824 bytes = 1 GB
1,099,511,627,776 bytes = 1 TB
1,125,899,906,842,620 bytes = 1 PB
1,152,921,504,606,850,000 bytes = 1 EB
1,180,591,620,717,410,000,000 bytes = 1 ZB


To format a byte count as a string, here’s a quick little routine to do the trick.

   1:      Public Function FormatBytes(ByVal nBytes As Double, Optional ByVal szFormatString As String = "###,###,###,##0") As String
   3:          Dim POSTFIXES() As String = {"Bytes", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"}
   4:          For n As Integer = POSTFIXES.Length - 1 To 0 Step -1
   5:              Dim nPow As Double = Math.Pow(1024, n)
   6:              If nBytes >= nPow Then
   7:                  nBytes /= nPow
   8:                  Return nBytes.ToString(szFormatString) & " " & POSTFIXES(n)
   9:              End If
  10:          Next
  11:          Return nBytes.ToString(szFormatString) & " Bytes"
  13:      End Function

Wednesday, December 15, 2010

Using Array.Copy to shift array elements

I wrote a network communications class that will perform socket reads into a pre-allocated Byte buffer.  This buffer is always the target of socket reads, so that I can avoid doing (perhaps many) unnecessary memory allocations.  For this byte buffer, I need to keep track of where “active” data in the buffer lives.  Initially there is no active data, so both START and END equal zero.  Later on, however, START and END may not be pointing to the beginning of the buffer and I need to SHIFT the active bytes to the front of the buffer and adjust the START and END pointers accordingly.  This way the next socket read can read “BUFFER_SIZE – END” bytes.

But how do we shift the bytes in the array down?  Some might create a new array and use Array.Copy to copy the active bytes over.  But we really want to use the same buffer, so we just want to shift the active bytes down to element 0.  Will Array.Copy do this correctly?  Doing a “shift left” (moving elements towards the beginning of the array) requires that the bytes are shifted in ascending array-index order.  If you go the other way, descending, you’ll clobber your data if there is any overlap.  Similarly, you need to shift in descending order when you are doing a “shift right” and moving elements up the array.

In order for Array.Copy to work correctly in both cases, it needs to detect that when there is an overlap between the source and target range and then move the elements in the proper order.  Does it do this?  Well.. YES!

In the example below, I take an array of bytes with 13 elements and shift the middle 9 bytes left; then I do it again, but shift right.

Here’s the output:


Here’s the code:

Imports System.Text
Module Module1
    Sub Main()
        Console.WriteLine("Testing Array.Copy on Byte array to shift contents up and down:" & vbCrLf)
        Dim A() As Byte = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12} 
        Console.WriteLine("FROM A(" & (A.Length() - 1).ToString() & ") = " & BitConverter.ToString(A))
        Console.WriteLine("Array.Copy(A, 2, A, 0, 9)")
        Array.Copy(A, 2, A, 0, 9)
        Console.WriteLine("   = A(" & (A.Length() - 1).ToString() & ") = " & BitConverter.ToString(A))
        A = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12}
        Console.WriteLine("FROM A(" & (A.Length() - 1).ToString() & ") = " & BitConverter.ToString(A))
        Console.WriteLine("Array.Copy(A, 2, A, 4, 9)")
        Array.Copy(A, 2, A, 4, 9)
        Console.WriteLine("   = A(" & (A.Length() - 1).ToString() & ") = " & BitConverter.ToString(A))
    End Sub
End Module

Sunday, December 5, 2010

Tracing Library/DLL calls on Win32

I have searched for a program to verify all the sectors of a hard drive, to detect errors.  Obviously, formatting the drive is one method, but I actually found that the format did not pick up bad sectors that I knew were on the hard drive.  After some searching I found a program called “HD Tune” which has an option to perform an “Error Scan” on a disk.  Using this utility, it successfully detected the error spots on the disk.


It would be nice to write such a utility myself.  But how?  Ideally I would be able to detect all the mounted disks on the system, determine the size and geometry, determine the number of sectors on the disk and perform a Read operation on each sector- looking for errors.  I would imagine the KERNEL32 function DeviceIoControl() will play a major part of it.

A quick investigation did not turn up anything promising.  So how does HD Tune do it?  Good question.  I never really played around with any sort of process spying utilities, at least not in a long time, so I fired up Spy++.  It’s good at spying on window messages, but what I want to know is what external Win32 DLL functions was it calling.  Spy++ won’t let you see that.  So another Google hunt for an answer.

Before getting into that, another question of interest is determining DLL dependencies.  What DLL’s is a processes using?  To answer that, one good utility is Dependency Walker, which can be found at


Now I can see all the KERNEL32.DLL functions being called by HD Tune.  The next step is to be able to see the actual calls being made, with parameters and return values.  Can we find a utility to do this?  Let’s find out!

One method, and arguably the most elegent, of viewing calls made by a process is via a technique called Import Address Table (IAT) patching.  Executable programs on windows and DLL’s are built on the Portable Execution (PE) file format.  One section in this format is called .idata contains a table (yeah, you got it, the Import Address Table) with names of imported functions.  An interesting article on this is "API Spying Techniques for Windows 9x, NT and 2000" by Yariv Kaplan at  Not only does the table list the functions called, but they act as a jump table.  That is, when a function is called, it is done through an indirect JMP of the function in the IAT.  That turns out to be a perfect spot to intercept the call.

Quickly searching around, we can find a few candidates in the field:

  • APISPY32 – An older program originally written for Windows 95.  Indication is that it works under Windows 2000 and XP also.  Available as a ZIP download at – direct download link is Updated APISPY32.  At this time, I’m not going to look at this one; instead I’ll focus on the following two.
  • Detours – Binary Interception of Win32 Functions (Microsoft Research).  Detours is a library for instrumenting arbitrary Win32 functions on x86, x64, and IA64 machines. Detours intercepts Win32 functions by re-writing the in-memory code for target functions. The Detours package also contains utilities to attach arbitrary DLLs and data segments (called payloads) to any Win32 binary.  A free “Express” version is available.
  • STraceNT: A System Call Tracer for Windows – Uses IAT patching to trace function calls.  This is the most promising and I’ll try this one first.



Unfortunately, under Windows 7 (at least), I was not able to get STraceNT to run HDTune.EXE or even a simple CRC32.exe program that I wrote.  It could be a Windows 7 issue.  So I’ll fire up Windows XP on a Virtual PC and see if it will run on there.  (5 minutes later!)  Yes, it seems to be working fine under Windows XP, so it seems to be an issue with running under Windows 7.


Detours, from Microsoft Research, is not an application; it’s a library.  With it, you can develop your own utility much like STraceNT.  In fact, that’s just one of the things you can do with it.  One of the samples (C++ code) is an utility like STraceNT that shows how to intercept and log some 1400+ Win32 API function calls.  At least one person has used Detours to make such a utility (no source code)- see

Thursday, October 28, 2010

Tuesday, October 19, 2010

5 Natural Ways To Boost And Improve Your Metabolism

Slow Metabolism? 5 Natural Ways To Boost And Improve Your Metabolism

1. Get your Omega – 3s fatty acids: Omega – from where do you think you can get Omega – 3s? Yes you guessed it. 3s is found in fish such as salmon, herring, and tuna. But why doctors always tell us to eat fish? and how fish improves your metabolism? Well, the answer is that Omega-3s balance blood sugar and reduce inflammation, helping to regulate metabolism. They may also reduce resistance to the hormone leptin, which researchers have linked to how fast fat is burned.

2. Switch to Green Tea: I talked about the benefits of green tea in previous posts and showed how many great benefits can it contribute to the human body. Now I can add another benefit which is your Metabolism. But how much do you have to drink? According to one study, if you drink five eight-ounce cups of green tea a day, you can increase your energy expenditure by 90 calories a day. Sounds like a lot of tea, but it’s not hard to do if you also drink it iced.

3. Eat Breakfast: Sometimes when we wake up in the morning we don’t feel hungry, probably we will be satisfied with cup of coffee or tea. But the way that doctors explain it to their patients is “Eating breakfast gets the engine going and keeps it going.” According to the National Weight Control Registry (an ongoing study that tracks 5,000 people who lost an average of 66 pounds and kept it off more than five years), 78 percent of those who keep it off eat an a.m. meal every day. Wow great results.

4. Buy Organic Food Only: Fruits, vegetables, and grains grown without pesticides keep your fat-burning system running at full-tilt because they don’t expose your thyroid to toxins, Hyman says. Nonorganic produce, on the other hand, “blocks your metabolism mainly by interfering with your thyroid, which is your body’s thermostat and determines how fast it runs,” he explains.

5. Exercise: The next time you run, swim, or even walk, ramp up the intensity for 30-second intervals, returning to your normal speed afterward. Using this strategy will help you consume more oxygen and make your cell powerhouses, the mitochondria, work harder to burn energy, explains Mark Hyman, MD, an integrative and functional medicine specialist in private practice in Lenox, Massachusetts, and author of Ultrametabolism: The Simple Plan for Automatic Weight Loss. “You increase the number of mitochondria and how efficiently they burn throughout the day,” he explains.

10 Ways to Boost your Metabolism


The Elusive Metabolism Boost

Boosting the metabolism is the holy grail of weight watchers everywhere, but how fast your body burns calories depends on several factors. Some people inherit a speedy metabolism. Men tend to burn more calories than women, even while resting. And for most people, metabolism slows steadily after age 40. Although you can't control your age, gender, or genetics, there are other ways to get a boost. Read on for 10 ways to rev up.

(1) Build Muscle

Our bodies constantly burn calories, even when we’re doing nothing. This resting metabolic rate is much higher in people with more muscle. Every pound of muscle uses about 6 calories a day just to sustain itself, while each pound of fat burns only 2 calories daily. That small difference can add up over time. In addition, after a bout of resistance training, muscles are activated all over your body, increasing your average daily metabolic rate.

(2) Kick Your Workout Up a Notch

Aerobic exercise may not build big muscles, but it can rev up your metabolism in the hours after a workout. The key is to push yourself. High-intensity exercise delivers a bigger, longer increase in resting metabolic rate than low- or moderate workouts. To get the benefits, try a more intense class at the gym or include short bursts of jogging during your regular walk.

(3) Drink More Water

The body needs water to process calories. If you are even mildly dehydrated, your metabolism may slow down. In one study, adults who drank eight or more glasses of water a day burned more calories than those who drank four. To stay hydrated, drink a glass of water or other unsweetened beverage before every meal and snack. In addition, try munching on fresh fruits and vegetables, which are full of fluid, rather than pretzels or chips.

(4) Have Your Drinks on the Rocks

Ice-cold beverages prompt the body to burn more calories during digestion. Research suggests five or six glasses of water on the rocks can use up an extra 10 calories a day. That might not sound like much, but it adds up to a pound of weight loss per year -- without dieting. You can get the same benefit by drinking iced tea or coffee, as long as you forego the cream and sugar.  [CHRIS: I don’t really agree with this recommendation.  Cold water may not be the best for your stomach to deal with.  Some, like myself, prefer room-temperature water.  It’s easy on the stomach and goes down much faster than cold ice water.]

(5) Eat More Often

Eating more really can help you lose weight -- eating more often, that is. When you eat large meals with many hours in between, you train your metabolism to slow down. Having a small meal or snack every 3 to 4 hours keeps your metabolism cranking, so you burn more calories over the course of a day. Several studies have also shown that people who snack regularly eat less at meal time.

(6) Spice Up Your Meals

Spicy foods contain chemical compounds that kick the metabolism into high gear. Eating a tablespoon of chopped red or green chili pepper can temporarily boost your metabolic rate by 23 percent. Some studies suggest the effect only lasts about half an hour, but if you eat spicy foods often, the benefits may add up. For a quick boost, spice up pasta dishes, chili, and stews with red-pepper flakes.

(7) Eat More Protein

The body burns up to twice as many calories digesting protein as it uses for fat or carbohydrates. Although you want to eat a balanced diet, replacing some carbs with lean, protein-rich foods can jump-start the metabolism at mealtime. Healthy sources of protein include lean beef and pork, fish, white meat chicken, tofu, nuts, beans, eggs, and low-fat dairy products.

(8) Drink Black Coffee

If you’re a coffee drinker, you probably enjoy the increased energy and concentration that follows your morning ritual. Well, some of these benefits are linked to a short-term increase in your metabolic rate. In one study, the caffeine in two cups of coffee prompted a 145-pound woman to burn 50 extra calories over the next four hours. Just be sure to drink it black. If you add cream, sugar, or flavored syrups, you’ll take in far more calories than you burn.

(9) Drink Green Tea

Drinking green tea or oolong tea offers the combined benefits of caffeine and catechins, substances shown to rev up the metabolism for a couple hours. Research suggests drinking two to four cups of either tea may push the body to burn an extra 50 calories each day. That adds up to 5 pounds of weight loss in a year.

(10) Avoid Crash Diets

Crash diets -- those involving eating fewer than 1,000 calories a day -- are disastrous for anyone hoping to quicken their metabolism. Although these diets may help you drop pounds (at the expense of good nutrition), a high percentage of the loss comes from muscle. The lower your muscle mass, the slower your metabolism. The final result is a body that burns far fewer calories (and gains weight faster) than the one you had before the diet.

Best Bets

The impact of different foods and drinks on the metabolism is small compared to what you need for sustained weight loss. Your best bet for creating a mean calorie-burning machine is to build muscle and stay active. The more you move during the day, the more calories you burn. And remember: working out in the morning has the benefit of revving up your metabolism for hours.

Make the Most of Your Metabolism


By Colette Bouchez
WebMD Weight Loss Clinic-Feature
Reviewed by Louise Chang, MD

"It's my metabolism!"

Sound familiar? If you're carrying some extra pounds (and having a hard time losing them), it's tempting to put the blame on a sluggish metabolism.

But is your metabolism really the reason it's often so hard to lose weight? And, more important, is there anything you can do about it?

WebMD asked experts to explore facts and myths about metabolism -- and the good news is, there are things you can do to help boost your body's calorie-burning power.

See How You Can Boost Your Metabolism

What Is Metabolism?

Your metabolism, experts say, involves a complex network of hormones and enzymes that not only convert food into fuel but also affect how efficiently you burn that fuel.

"The process of metabolism establishes the rate at which we burn our calories and, ultimately, how quickly we gain weight or how easily we lose it," says Robert Yanagisawa, MD, director of the Medically Supervised Weight Management Program at Mount Sinai Medical Center in New York.

Of course, not everyone burns calories at the same rate.

Your metabolism is influenced by your age (metabolism naturally slows about 5% per decade after age 40); your sex (men generally burn more calories at rest than women); and proportion of lean body mass (the more muscle you have, the higher your metabolic rate tends to be).

And yes, heredity makes a difference.

"Some people just burn calories at a slower rate than others," says Barrie Wolfe-Radbill, RD, a nutritionist specializing in weight loss at New York University Medical Center.

Occasionally, Yanagisawa says, a defect in the thyroid gland can slow metabolism, though this problem is relatively rare.

And here's a fact that may surprise you: the more weight you carry, the faster your metabolism is likely running.

"The simple fact is that the extra weight causes your body to work harder just to sustain itself at rest, so in most instances, the metabolism is always running a bit faster," says Molly Kimball, RD, sports and lifestyle nutritionist at the Oscher's Clinic's Elmwood Fitness Center.

That's one reason it's almost always easiest to lose weight at the start of a diet, and harder later on, Kimball says: "When you are very overweight your metabolism is already running so high that any small cut in calories will result in an immediate loss."

Then, when you lose significant amounts of body fat and muscle, your body needs fewer calories to sustain itself, she says. That helps explain why it's so easy to regain weight after you've worked to lose it.

"If two people both weigh 250 pounds, and one got there by dieting down from 350 and the other one was always at 250, the one who got there by cutting calories is going to have a slower metabolism," says Yanagisawa. "That means they will require fewer calories to maintain their weight than the person who never went beyond 250 pounds."

Revving Your Engine

Though some of the factors affecting metabolic rate can't be changed, happily, there are ways to maximize the metabolism you're born with -- even when you're dieting.

Among the best ways is exercise. This includes aerobic workouts to burn more calories in the short term, and weight training to build the muscles that will boost your metabolism in the long run.

"Since muscle burns more calories than fat -- even while at rest -- the more muscles you have, the higher your resting metabolic rate, which means the more calories your body will be burning just to sustain you," says Kimball.

Personal fitness trainer Kelli Calabrese MS, CSCS, ACE, notes that every pound of muscle in our bodies burns 35 calories a day, while each pound of fat burns just 2 calories per day.

While 30 minutes of aerobic exercise may burn more calories than 30 minutes of weight training, Calabrese says, "in the hours following the cessation of exercise, the weight training has a longer-lasting effect on boosting metabolism."

Having extra muscle also means you can eat more and gain less.

Adds Yanagisawa: "We don't tell people to exercise while dieting only to burn calories -- we also know that exercise builds muscle and that is what will help you burn more calories and maintain the weight loss you work so hard to achieve."

Some women fear they'll "bulk up" with weight training. But Calabrese, author of Feminine, Fit and Firm, says not to worry.

"Women don't have the hormones necessary to develop those huge muscles, so you can feel good about doing weight training," she says.

Eat More, Burn Better

Of course, the diet advice we'd all love to hear is "Eat more and lose more weight!" But what really works is "Eat more often, and you'll lose more weight." Small, but frequent, meals help keep your metabolism in high gear, and that means you'll burn more calories overall.

"When you put too many hours between meals, your metabolism actually slows down to compensate," says Kimball.

If you then eat a huge meal -- at the same time your metabolism is functioning as if you're starving -- your body wants to hold on to every calorie.

While this won't make much difference on an occasional basis, Kimball says, make it a way of life and it can get harder to lose or maintain weight.

Kimball's advice is borne out by the findings of a study that was presented at the 2005 annual meeting of the American College of Sports Medicine. Researchers from Georgia State University reported that when athletes ate snacks totaling about 250 calories each, three times a day, they had greater energy output then when they didn't snack.

The study also found that snacking helped the athletes eat less at each of their three regular meals. The final result was a higher metabolic rate, a lower caloric intake, and reduction in body fat.

Fat-Burning Foods?

From supermodels who douse their food with red pepper, to movie stars who swear by green tea, there's no shortage of claims for foods that are said to increase metabolism. But do any of them work?

"Actually, any food will increase your metabolism, mostly in the first hour after you eat -- that's when your system is most revved," says Kimball.

Further, she says, protein generally requires about 25% more energy to digest. So -- at least theoretically - a high-protein snack might rev metabolism a little more than a carb-heavy food with the same number of calories. That said, it's not clear that any food has special powers to boost metabolism significantly.

"Some studies have shown hot pepper and very spicy foods can increase metabolism by about 20% for about 30 minutes, but no one really knows if the extra burn lasts any longer than that, " says Kimball.

In a small study on Japanese women published in the British Journal of Nutrition, researchers found red pepper caused the body to heat up and revved the metabolism following a meal. But the most effects were seen primarily when the red pepper was eaten with high-fat foods (which are also higher in calories).

Another small study, published in the journal Medicine & Science in Sports & Exercise, reported that male athletes who added red pepper to high-carbohydrate meals boosted both their resting and active metabolic rates 30 minutes after the meal. But there was no evidence this burn power was lasting.

The same appears true for green tea, which contains a substance called EGCG (epigallocatechin gallate), a powerful antioxidant that some believe can bring about the same kind of calorie-burning effect as hot pepper.

In a study of 10 men published in the American Journal of Clinical Nutrition, researchers found that 90 milligrams of EGCG and 50 milligrams of caffeine taken with meals boosted 24-hour energy expenditure by 4% (caffeine alone did not show a similar effect).

But it's not clear whether this effect would be enough to boost weight loss. And that, says Radbill, is precisely the point.

"Essentially, you would have to drink so much of it in order to see even a small effect, that I don't think it's really worth it," says Radbill. "Drink green tea for other health-giving properties, but not to lose weight."

The bottom line, she says, is this: "All these foods may have a slight impact on metabolism, but the increase is still insignificant compared to what you need in order to lose weight."

Your best bet for keeping metabolism revved: Build muscles, snack on low-calorie, high-protein foods, and keep moving!


Metabolism Basics

Our bodies get the energy they need from food through metabolism, the chemical reactions in the body's cells that convert the fuel from food into the energy needed to do everything from moving to thinking to growing. Specific proteins in the body control the chemical reactions of metabolism, and each chemical reaction is coordinated with other body functions. In fact, thousands of metabolic reactions happen at the same time — all regulated by the body — to keep our cells healthy and working.

Metabolism is a constant process that begins when we're conceived and ends when we die. It is a vital process for all life forms — not just humans. If metabolism stops, a living thing dies.

Here's an example of how the process of metabolism works in humans — and it begins with plants. First, a green plant takes in energy from sunlight. The plant uses this energy and the molecule cholorophyll (which gives plants their green color) to build sugars from water and carbon dioxide in a process known as photosynthesis.

When people and animals eat the plants (or, if they're carnivores, when they eat animals that have eaten the plants), they take in this energy (in the form of sugar), along with other vital cell-building chemicals. The body's next step is to break the sugar down so that the energy released can be distributed to, and used as fuel by, the body's cells.


After food is eaten, molecules in the digestive system called enzymes break proteins down into amino acids, fats into fatty acids, and carbohydrates into simple sugars (for example, glucose). In addition to sugar, both amino acids and fatty acids can be used as energy sources by the body when needed. These compounds are absorbed into the blood, which transports them to the cells.

After they enter the cells, other enzymes act to speed up or regulate the chemical reactions involved with "metabolizing" these compounds. During these processes, the energy from these compounds can be released for use by the body or stored in body tissues, especially the liver, muscles, and body fat.

In this way, the process of metabolism is really a balancing act involving two kinds of activities that go on at the same time — the building up of body tissues and energy stores and the breaking down of body tissues and energy stores to generate more fuel for body functions:

  • Anabolism, or constructive metabolism, is all about building and storing: It supports the growth of new cells, the maintenance of body tissues, and the storage of energy for use in the future. During anabolism, small molecules are changed into larger, more complex molecules of carbohydrate, protein, and fat.
  • Catabolism, or destructive metabolism, is the process that produces the energy required for all activity in the cells. In this process, cells break down large molecules (mostly carbohydrates and fats) to release energy. This energy release provides fuel for anabolism, heats the body, and enables the muscles to contract and the body to move. As complex chemical units are broken down into more simple substances, the waste products released in the process of catabolism are removed from the body through the skin, kidneys, lungs, and intestines.
The Endocrine System

Several of the hormones of the endocrine system are involved in controlling the rate and direction of metabolism. Thyroxine, a hormone produced and released by the thyroid gland, plays a key role in determining how fast or slow the chemical reactions of metabolism proceed in a person's body.

Another gland, the pancreas secretes hormones that help determine whether the body's main metabolic activity at a particular time will be anabolic or catabolic. For example, after eating a meal, usually more anabolic activity occurs because eating increases the level of glucose — the body's most important fuel — in the blood. The pancreas senses this increased level of glucose and releases the hormone insulin, which signals cells to increase their anabolic activities.

Metabolism is a complicated chemical process, so it's not surprising that many people think of it in its simplest sense: as something that influences how easily our bodies gain or lose weight. That's where calories come in. A calorie is a unit that measures how much energy a particular food provides to the body. A chocolate bar has more calories than an apple, so it provides the body with more energy — and sometimes that can be too much of a good thing. Just as a car stores gas in the gas tank until it is needed to fuel the engine, the body stores calories — primarily as fat. If you overfill a car's gas tank, it spills over onto the pavement. Likewise, if a person eats too many calories, they "spill over" in the form of excess body fat.

The number of calories someone burns in a day is affected by how much that person exercises, the amount of fat and muscle in his or her body, and the person's basal metabolic rate (or BMR). BMR is a measure of the rate at which a person's body "burns" energy, in the form of calories, while at rest. The BMR can play a role in someone's tendency to gain weight. For example, a person with a low BMR (who therefore burns fewer calories while at rest or sleeping) will tend to gain more pounds of body fat over time, compared with a similar-sized person with an average BMR who eats the same amount of food and gets the same amount of exercise.

What Factors Influence BMR?

To a certain extent, BMR is inherited. Sometimes health problems can affect BMR, but people can actually change their BMR in certain ways. For example, exercising more will not only cause a person to burn more calories directly from the extra activity itself, but becoming more physically fit will increase BMR as well. BMR is also influenced by body composition — people with more muscle and less fat generally have higher BMRs.

Metabolism Problems

In a broad sense, a metabolic disorder is any disease that is caused by an abnormal chemical reaction in the body's cells. Most disorders of metabolism involve either abnormal levels of enzymes or hormones or problems with the functioning of those enzymes or hormones. When the metabolism of body chemicals is blocked or defective, it can cause a buildup of toxic substances in the body or a deficiency of substances needed for normal body function, either of which can lead to serious symptoms.

Some metabolic diseases are inherited. These conditions are called inborn errors of metabolism. When babies are born, they're tested for many of these metabolic diseases in a newborn screening test. Many of these inborn errors of metabolism can lead to serious complications or even death if they're not controlled with diet or medication from an early age.

Examples of Metabolic Disorders and Conditions

G6PD deficiency. Glucose-6-phosphate dehydrogenase, or G6PD, is just one of the many enzymes that play a role in cell metabolism. G6PD is produced by red blood cells and helps the body metabolize carbohydrates. Without enough normal G6PD to help red blood cells handle certain harmful substances, red blood cells can be damaged or destroyed, leading to a condition known as hemolytic anemia. In a process called hemolysis, red blood cells are destroyed prematurely, and the bone marrow (the soft, spongy part of the bone that produces new blood cells) may not be able to keep up with the body's need to produce more new red blood cells. Kids with G6PD deficiency may be pale and tired and have a rapid heartbeat and breathing. They may also have an enlarged spleen or jaundice — a yellowing of the skin and eyes. G6PD deficiency is usually treated by discontinuing medications or treating the illness or infection causing the stress on the red blood cells.

Galactosemia. Babies born with this inborn error of metabolism do not have enough of the enzyme that breaks down the sugar in milk called galactose. This enzyme is produced in the liver. If the liver doesn't produce enough of this enzyme, galactose builds up in the blood and can cause serious health problems. Symptoms usually occur within the first days of life and include vomiting, swollen liver, and jaundice. If galactosemia is not diagnosed and treated quickly, it can cause liver, eye, kidney, and brain damage.

Hyperthyroidism. Hyperthyroidism is caused by an overactive thyroid gland. The thyroid releases too much of the hormone thyroxine, which increases the person's basal metabolic rate (BMR). It causes symptoms such as weight loss, increased heart rate and blood pressure, protruding eyes, and a swelling in the neck from an enlarged thyroid (goiter). The disease may be controlled with medications or through surgery or radiation treatments.

More Metabolic Disorders

Hypothyroidism. Hypothyroidism is caused by an absent or underactive thyroid gland and it results from a developmental problem or a destructive disease of the thyroid. The thyroid releases too little of the hormone thyroxine, so a person's basal metabolic rate (BMR) is low. In infants and young children who don't get treatment, this condition can result in stunted growth and mental retardation. Hypothyroidism slows body processes and causes fatigue, slow heart rate, excessive weight gain, and constipation. Kids and teens with this condition can be treated with oral thyroid hormone to achieve normal levels in the body.

Phenylketonuria. Also known as PKU, this condition occurs in infants due to a defect in the enzyme that breaks down the amino acid phenylalanine. This amino acid is necessary for normal growth in infants and children and for normal protein production. However, if too much of it builds up in the body, brain tissue is affected and mental retardation occurs. Early diagnosis and dietary restriction of the amino acid can prevent or lessen the severity of these complications.

Type 1 diabetes mellitus. Type 1 diabetes occurs when the pancreas doesn't produce and secrete enough insulin. Symptoms of this disease include excessive thirst and urination, hunger, and weight loss. Over the long term, the disease can cause kidney problems, pain due to nerve damage, blindness, and heart and blood vessel disease. Kids and teens with type 1 diabetes need to receive regular injections of insulin and control blood sugar levels to reduce the risk of developing problems from diabetes.

Type 2 diabetes. Type 2 diabetes happens when the body can't respond normally to insulin. The symptoms of this disorder are similar to those of type 1 diabetes. Many kids who develop type 2 diabetes are overweight, and this is thought to play a role in their decreased responsiveness to insulin. Some can be treated successfully with dietary changes, exercise, and oral medication, but insulin injections are necessary in other cases. Controlling blood sugar levels reduces the risk of developing the same kinds of long-term health problems that occur with type 1 diabetes.

Reviewed by: Steven Dowshen, MD
Date reviewed: May 2009


Thursday, October 7, 2010

Silverlight debugging: Telling Visual Studio not to break on ValidationException

I found it was annoying that I would get thrown into the debugger every time a ValidationException was thrown in the Silverlight field validation logic.  This can be fixed by telling VS to ignore this particular exception:

VS 2010 already has the ValidationException in the Exceptions list, but if yours doesn’t or you are using VS 2008, you can follow these instructions to manually add it:

  1. Click on Debug->Exceptions (Ctrl+D, E)
  2. Click on Add…
  3. Select the Type as “Common Language Runtime Exceptions”
  4. Type the name as System.ComponentModel.DataAnnotations.ValidationException and click OK.
  5. You’ll now see this exception in the list.  Uncheck “User-unhandled just for this exception, and click OK.


This lets you keep all of the other exceptions turned on, but Visual Studio will no longer break when Silverlight hits a ValidationException.

Wednesday, September 22, 2010

CTS, baby!!

It’s a Cadillac CTS!!  This puppy rocks!!  Just need to add a new custom sound system.

Life is good!


Monday, September 20, 2010

Workout from Tom Venuto

  Arm circles 15 each direction (forward, backward)
  Tai Chi twists 15 each side (left, right)
  Trunk circles 10 each direction (left, right)
  Prisoner lunges (body weight) 15 per leg (left, right)
  Push-ups 15

Workouts are broken into Phase I and II, each lasting 4 weeks.  Each workout is done 3 times a week with at least a day of rest in between each workout.  Cardio can be done on rest days as well as workout days.  Ideally, give yourself one full rest day a week.  After repeating Phase I and II, two times each (16 weeks), take a week off.  Phase I is for muscle development and conditioning, Phase II is for strength.

  Phase I Phase II
Reps 12-15 6-10
Sets 3 3
Purpose Muscle Development Strength

There are two workouts (A and B) that are alternated.  The exercises are specially chosen and with the alternation give your body 96 hours between focusing on the same muscle group.  This gives you time to heal and avoid overtraining.  In addition, each workout utilizes supersets.  So for exercises A1 and A2, for example, one set of A1 is performed, followed by one set of A2, without rest in-between.  Then rest for one minute and perform the next set.  After 3 sets, move to the next exercise group.

  A1 Dumbbell squat (quads, lower body)  
  A2 Bird dog (lower back, gluts) 15-20 reps
  B1 Dumbbell split squat/static lunge (quads, lower back)  
  B2 Dumbbell row (horizontal pull)  
  C1 Dumbbell bench press (horizontal push)  
  C2 Plank (core) 30-60 sec
  D1 One legged toe raises (calves)  
  A1 Romanian dead lift (hips emphasized, lower body)  
  A2 Shoulder press (vertical push)  
  B1 One legged hip extension (hip dominant, lower body) 15-20 reps
  B2 Dumbbell pullover (vertical pull)  
  C1 Reverse crunch (lower abs) 15-20 reps
  C2 Cross knee crunch (abs and rotation) 15-20 reps
  D1 Dumbbell curl (biceps)  
  D2 Two-Dumbbell extension (triceps)  

La Roux – Bulletproof

Awesome!  From her eponymous album.

Tuesday, September 14, 2010

7 Healthy Habits of Highly Fit People

fitness22 Ever wonder how people who always seem to be in great physical shape got that way? More importantly how do they stay healthy, fit and in-shape?  Here are the seven healthy habits that almost all fit people seem to have in common:

Healthy Habit #1: They Eat
No one ever dieted their way to long term fitness and health. Despite the disturbing trend toward fad diets like Master Cleanse (which involve extreme calorie restriction or striking entire food groups from a person’s diet,)  well-conditioned, in-shape people eat.  And they actually eat a lot.

The difference between fit eaters and fat eaters, is that highly fit people eat differently — they tend to eat more whole, unprocessed foods; have higher lean protein intake; consume the bulk of their carbohydrates in the form of complex carbs like whole grains, vegetables and whole fruit; and avoid the “fat free food” trap.  They also tend to eat more frequently (as many as six to seven meals a day), but make those meals smaller.

The result is that they have more stable blood sugar, more consistent energy levels, and are less prone to gaining body fat because they rarely eat more calories in any given meal than their body can utilize.

Healthy Habit #2: They Move
People who seem to be perpetually in good shape not only eat frequently, but they move a lot. This seems elementary, but in a sedentary society, we are moving less than ever before.

Highly fit people don’t shy away from physical activity in their daily lives, whether that is walking when they could have drove or taking the stairs when the elevator would have been more convenient. If we walked more, and drove less, we wouldn’t have to spend as much time on the treadmill at the gym.  Yet our daily lives are often arranged in such a way to discourage physical activity.

Highly fit people consciously go out of their way to find opportunities to move. Whether that is parking a greater distance away from the shopping mall, taking the stairs at work, or even picking up their pace when walking from meeting-to-meeting, you’ll always notice that fit people seem to be on the move.

They also find ways to get exercise that doesn’t always require spending time at the gym. Whether that’s recreational sports, walking the dog, swimming, running, yoga, Pilates or even stretching at their desks, they understand that staying in-shape is a lifestyle, not just a “kick” you go on.

Healthy Habit #3: They Make the Time for Exercise
“I don’t have time for exercise” isn’t something you’ll hear from a highly fit person. Everyone is busy and everyone has career, family and community obligations. But highly fit people make time for exercise.

Indeed, they often hold their exercise time sacred and will always figure out a way to meet their other commitments, while still meeting their health, diet and fitness needs. The truth is that most people have far more time available in their day then they think. They spend time watching TV, playing video games, surfing the Internet, going to the movies or even sleeping an extra hour or two.

Exercise doesn’t require that much time. In general, less than 60 minutes a day. Most people easily have that time available to them, they just choose to use it differently. Highly fit people, on the other hand, make exercise a priority. They make a choice to watch an hour less of TV in the evening in order to take care of their body and health. And with all of the studies that show the tremendous benefits to regular exercise, it’s clear that more people should follow their lead and make it a priority as well.

Healthy Habit #4: They Drink Water
Highly fit people understand the benefits of water. When you see them, whether its at the gym, at home or in the office, a bottle of water will often be close at hand.  Study-after-study has shown that proper hydration isn’t just important to athletes and runners, but everyone. Water can blunt fatigue, improve concentration and thought clarity, discourage the formation of kidney stones, improve digestion and improve performance in the gym.  Highly fit people drink a lot of water … and they are healthier for it.

Here’s the really good news: fit people don’t just drink tap or bottled water, they also consume plenty of green and black tea.  Recent research has actually indicated that consuming tea not only counts toward your daily hydration requirements, but may actually be more healthy overall than plain water.

Healthy Habit #5: They Don’t Diet!
This is related to Habit #1. Highly fit people don’t “go on diets” — they are on a diet every day.

That doesn’t necessarily mean they are restricting calories every day. It means that they understand that long term health and fitness requires consistently eating smart. And smart eating for a highly fit person is just part of their every day routine.

You can often spot a highly-fit person because they don’t skip breakfast, they will often bring their own lunch to work and they seem to always be snacking on healthy foods like apples, vegetables and nuts. It’s also rare to see them eating fast food or drinking soda — arguably to of the worst types of foods a person can consume and a leading cause of obesity according to a 2006 study published in the American Journal of Clinical Nutrition.

The one exception to this rule is competitive male and female bodybuilding. Competitive bodybuilders will often diet (drastically, some times)  leading up to a competition in order to drive their body fat down to very low levels (for men the low-single digits and for women, the mid-teens.)  It’s very difficult for any person, no matter how well-conditioned they are, to maintain these extremely low, competition-grade body fat levels for any significant amount of time.  Still, even most competitive bodybuilders will admit that if it weren’t for their sport, they would never utilize these diet tactics.

Healthy Habit #6: They Have Goals
Highly fit, in-shape people always have a goal. After all, you can’t improve something unless you know what you are trying to improve it to. Those goals can be small and incremental, or large and ambitious. In either case, they act with a sense of purpose when it comes to their health and physical fitness.

Whether that goal is to maintain their current physique, improve it, reduce body fat, gain additional muscle, increase their endurance or stamina, become more flexible,  improve their coordination,  or develop a better golf swing, they will always have a goal that they are shooting for.

If you ask a fit person what they are currently working on, they will always be able to tell you their goal. And if you observe them exercising, you’ll be able to sense that they have purpose. They rarely sit still between sets, they minimize socialization in the gym during their workout, and again, they always seem to be on the move and “in the zone.” In other words, they won’t just be going through the motions, they’ll be striving for something.

Healthy Habit # 7: The Record Their Progress
Healthy, highly-fit people keep track of their exercise so they can determine whether they are actually making progress toward their goal.  You can’t improve what you don’t measure.

Most highly-fit people keep an exercise log of some sort or another. It may simply be a notebook where they write down each exercise, the weight and completed reps. Or it may be more formal, for example a store-bought exercise and fitness log  or a sheet provided by their gym.  There are even programs available for cell phones or PDAs that can help track progress.

One of the first pieces of advice I give someone who feels like they aren’t making progress with their workout routine or diet is to start an exercise and food log. Often, people aren’t working as hard as they think at the gym or they’re eating more calories than they originally estimated. By keeping track of the details of your diet and workout regimen, you can have better visibility into potential stumbling-points and improve them.

Fitness-conscious people understand this, since meeting their goals means understanding that progress from the little improvements you make each workout. Unless you are tracking those improvements, you’ll find yourself stalled and frustrated.

The Takeaway: Make These Habits Your Own
Remember, you don’t have to be an athlete, competitive bodybuilder, aerobics instructor or fitness model to take advantage of these seven healthy habits. Regardless of your level, experience or personal health and diet goals,  you can can live a healthier and happier life by adopting some of the same habits as highly-fit people.

Monday, August 23, 2010

Retrieving configured DNS servers across all network adapters

   1:  Dim dnsAddressList As IPAddressCollection = Nothing
   3:  For Each adapter In System.Net.NetworkInformation.NetworkInterface.GetAllNetworkInterfaces()
   5:      Dim adapterProperties = adapter.GetIPProperties()
   6:      Dim dnsServers As IPAddressCollection = adapterProperties.DnsAddresses
   7:      If dnsAddressList Is Nothing Then
   8:      dnsAddressList = dnsServers
   9:      Else
  10:      dnsAddressList.Union(dnsServers)
  11:      End If
  12:  Next adapter
  14:  Return dnsAddressList

Tuesday, August 17, 2010

Raleigh Ki Aikido

4-week Beginners Course
Tuesdays, 6:00-7:30 p.m., starting on August 31, 2010
A once-a-week course for those new to Shinshin Toitsu Aikido (Aikido with Mind and Body Coordination). This course introduces the Four Basic Principles of Mind and Body Coordination and the basic movements used in aikido techniques, along with breathing meditation.  Learn how to use mind and body coordination to improve learning, athletic performance, and awareness of your surroundings. ** The FIRST class is mandatory. **
Intermediate class
Tuesdays, 6:30-8:00 p.m. (July through August 24)
This class is for those who have completed the Beginners Course. Joining Ki Society by paying the one-time Ki Society initiation fee is required.
General Aikido class
Thursdays, 6:30-8:30 p.m.
This class is for those who have completed 8 weeks of Intermediate class.

* Intermediate class participants can attend the Beginners Course at no additional cost.  Once you complete 8 weeks of Intermediate class, students can attend any classes.

Tuesday, August 10, 2010

Visual Studio 2010 Productivity Power Tools (Extension)

More info and download at

Can also be installed from within VS 2010 - Tools / Extension Manager, then search for "Pro Power Tools" to find Productivity Power Tools by Microsoft; then click Download and then Install.

Manage individual extension features in the Tools / Options / Productivity Power Tools item:


Invoking the ConnectionString Editor in Visual Basic.NET application

image  image

Add project references to:

  • adodb.dll
    NET: ADODB - C:\Program Files\Microsoft.NET\Primary Interop Assemblies\adodb.dll
  • MSDASC.dll
    COM: Microsoft OLE DB Service Component 1.0 Type Library

Sample code to invoke ConnectionString editor to create a new connection string or edit an existing one:

   1:  Imports MSDASC
   2:  Imports ADODB
   4:  Public Class FormSettings
   6:      Private Sub ButtonEditConnectionString_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ButtonEditConnectionString.Click
   8:          Dim szConnectionString As String = TextBoxConnectionString.Text.Trim()
  10:          Dim I As MSDASC.DataLinks = New DataLinks
  11:          Dim C As ADODB.Connection = New ADODB.Connection
  13:          If szConnectionString.Length() = 0 Then
  14:              If I.PromptNew(C) Then
  15:                  TextBoxConnectionString.Text = C.ConnectionString
  16:              End If
  17:          Else
  18:              C.ConnectionString = szConnectionString
  19:              If I.PromptEdit(C) Then
  20:                  TextBoxConnectionString.Text = C.ConnectionString
  21:              End If
  22:          End If
  24:      End Sub
  26:      Private Sub FormSettings_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
  28:          'Connection String
  29:          TextBoxConnectionString.Text = My.Settings.ConnectionString
  31:      End Sub
  33:  End Class

Friday, August 6, 2010

Durham Bulls Stadium

Friday, August 6th, playing Indianapolis; Fireworks afterwards

Directions -

Parking (use South Deck) -

Seating -

SQL Server temporary tables Logo 

Temporary Tables

Written by Bill Graziano on 17 January 2001

Sophie writes "Can you use a Stored Procedure to open a table and copy data to a sort of virtual table (or a records set) so that you can change the values with and not affect the actual data in the actual table. And then return the results of the virtual table? Thanks!" This article covers temporary tables and tables variables and is updated for SQL Server 2005.

I love questions like this. This question is just a perfect lead in to discuss temporary tables. Here I am struggling to find a topic to write about and I get this wonderful question. Thank you very much Sophie.

Temporary Tables

The simple answer is yes you can. Let look at a simple CREATE TABLE statement:

YakID int,
YakName char(30) )

You'll notice I prefixed the table with a pound sign (#). This tells SQL Server that this table is a local temporary table. This table is only visible to this session of SQL Server. When I close this session, the table will be automatically dropped. You can treat this table just like any other table with a few exceptions. The only real major one is that you can't have foreign key constraints on a temporary table. The others are covered in Books Online.

Temporary tables are created in tempdb. If you run this query:

YakID int,
YakName char(30) )

select name
from tempdb..sysobjects 
where name like '#yak%'

drop table #yaks

You'll get something like this:

#Yaks_________________________ . . . ___________________________________00000000001D

(1 row(s) affected)

except that I took about fifty underscores out to make it readable. SQL Server stores the object with a some type of unique number appended on the end of the name. It does all this for you automatically. You just have to refer to #Yaks in your code.

If two different users both create a #Yaks table each will have their own copy of it. The exact same code will run properly on both connections. Any temporary table created inside a stored procedure is automatically dropped when the stored procedure finishes executing. If stored procedure A creates a temporary table and calls stored procedure B, then B will be able to use the temporary table that A created. It's generally considered good coding practice to explicitly drop every temporary table you create.  If you are running scripts through SQL Server Management Studio or Query Analyzer the temporary tables are kept until you explicitly drop them or until you close the session.

Now let's get back to your question. The best way to use a temporary table is to create it and then fill it with data. This goes something like this:

CREATE TABLE #TibetanYaks(
YakID int,
YakName char(30) )

INSERT INTO #TibetanYaks (YakID, YakName)
SELECT 	YakID, YakName
FROM 	dbo.Yaks
WHERE 	YakType = 'Tibetan'

-- Do some stuff with the table

drop table #TibetanYaks

Obviously, this DBA knows their yaks as they're selecting the famed Tibetan yaks, the Cadillac of yaks. Temporary tables are usually pretty quick. Since you are creating and deleting them on the fly, they are usually only cached in memory.

Table Variables

If you are using SQL Server 2000 or higher, you can take advantage of the new TABLE variable type. These are similar to temporary tables except with more flexibility and they always stay in memory.  The code above using a table variable might look like this:

DECLARE @TibetanYaks TABLE (
YakID int,
YakName char(30) )

INSERT INTO @TibetanYaks (YakID, YakName)
SELECT 	YakID, YakName
FROM 	dbo.Yaks
WHERE 	YakType = 'Tibetan'

-- Do some stuff with the table 

Table variables don't need to be dropped when you are done with them.

Which to Use

  • If you have less than 100 rows generally use a table variable.  Otherwise use  a temporary table.  This is because SQL Server won't create statistics on table variables.
  • If you need to create indexes on it then you must use a temporary table.
  • When using temporary tables always create them and create any indexes and then use them.  This will help reduce recompilations.  The impact of this is reduced starting in SQL Server 2005 but it's still a good idea.

Answering the Question

And all this brings us back to your question.  The final answer to your question might look something like this:

DECLARE @TibetanYaks TABLE (
YakID int,
YakName char(30) )

INSERT INTO @TibetanYaks (YakID, YakName)
SELECT 	YakID, YakName
FROM 	dbo.Yaks
WHERE 	YakType = 'Tibetan'

UPDATE 	@TibetanYaks
SET 	YakName = UPPER(YakName)

FROM @TibetanYaks

Global Temporary Tables

You can also create global temporary tables. These are named with two pound signs. For example, ##YakHerders is a global temporary table. Global temporary tables are visible to all SQL Server connections. When you create one of these, all the users can see it.  These are rarely used in SQL Server.


That shows you an example of creating a temporary table, modifying it, and returning the values to the calling program. I hope this gives you what you were looking for.

Friday, June 18, 2010

Yeah, Baby!



SQLCE Sample Code and Projects

Lessons in programming with SQL Server Compact Edition:

Deploying SQL Server Compact Edition

In the interest of copy and paste and making your life easier, here are the 7 dll’s you need to locate and add to your project. You should be able to find them in C:\Program Files\Microsoft SQL Server Compact Edition\v3.5 (or v3.0). If you are using 3.0, substitute “30” for “35” in the names of these dll’s.

  • sqlceca35.dll
  • sqlcecompact35.dll
  • sqlceer35EN.dl
  • sqlceme35.dll
  • sqlceoledb35.dll
  • sqlceqp35.dll
  • sqlcese35.dll

Set the Build Action to “Content”, and “Copy to Output Directory” to “copy always” on these entries in Solution Explorer. On the reference to the System.Data.SqlServerCe.dll in your project, set “Copy Local” to “true”.

Wednesday, April 21, 2010


Json - Release: Json.NET 3.5 Release 7

Json.NET library makes working with JSON formatted data in .NET simple. Key features include a flexible JSON serializer to for quickly converting .NET classes to JSON and back again, and LINQ to JSON for reading and writing JSON.

-Flexible JSON serializer to convert .NET objects to JSON and back again
-LINQ to JSON for reading and writing JSON
-Writes indented, easy to read JSON
-Convert JSON to and from XML
-Supports Silverlight and the Compact Framework

The JSON serializer is a good choice when the JSON you are reading or writing maps closely to a .NET class. The serializer automatically reads and writes JSON for the class.

For situations where you are only interested in getting values from JSON, don't have a class to serialize or deserialize to, or the JSON is radically different from your class and you need to manually read and write from your objects then LINQ to JSON is what you should use. LINQ to JSON allows you to easily read, create and modify JSON in .NET.

Thursday, April 1, 2010

Easiest way to set ListView ItemHeight in an Owner-Drawn ListView

When creating an owner-drawn ListBox, you will receive measure-item messages that allow you to specify the height of items.  In a ListView control, that functionality is not there.  So how is the ItemHeight determined in a ListView in Details mode?  It uses the ImageList height then the Font height, so to override the item height create a dummy ImageList and set it to the desired height and assign it to the listview depending on the view.  Using the Font to set the height does not work very well because it also affects the height of the Header control, an unwanted side-effect.

Wednesday, March 17, 2010


If you have extra 3.5" internal hard drives, perhaps for backups or archiving purposes, what's the best way to store them?  This is the answer – a VHS-like static-free enclosure that can be placed on a bookshelf.  I found a similar item on Amazon, but it looks flimsy and apparently has one side longer than the other so you can't stand it straight up on a bookshelf.  The Hudzee looks strong, snug, and will store nicely on a bookshelf.  They're about $65 for 10 of them, not very cheap, but if you have hard drives accumulating, it's a good investment.

Friday, March 12, 2010


Started a new blog, for myself really, to chronicle my exercise - specifically, following one of the year-long programs found in the book "The New Rules of Lifting", which I just finished reading.