Thursday, December 31, 2009

SCHEMA

SCHEMA
=========

-----------
USER "A"
-----------

--owns--> SCHEMA "S1"

--contains--> SP_1

<--owns-- DB_ROLE "R"

--owns--> SCHEMA "S2"

--contains--> TABLE_1

<--owns-- USER "B"

--owns--> SCHEMA "S3" --contains--> VIEW_1 <--owns-- USER "B", DB_ROLE "R"


-----------
USER "DBO"
-----------

--owns--> SCHEMA "DBO"


----------------
USER "DB_OWNER"
----------------

--owns--> SCHEMA "DB_OWNER"


----------------
DB_ROLE "R"
----------------

--owns--> SCHEMA "S2"

--contains--> TABLE_2

--owns--> SCHEMA "S3"

--contains--> VIEW_2


Schema can only contain certain entities, namely OBJECT (tbls, views, SPs, functions, queues and synonyms are objects that are "ownership-transferable" while other objects like linkedsrvrs, constraints, rules, triggers, credentials, statistics etc. are not), TYPE and XML SCHEMA COLLECTION.


**The only reliable way to find the owner of a object is to query the sys.objects catalog view. The only reliable way to find the owner of a type is to use the TYPEPROPERTY function.



A schema contains database (catalog) objects such as tables, views and SPs. A schema owner may be a DB user, DB role or app role.


DB user has one to many relationship with dbo schemas i.e. a schema can belong to only one user while a user can own many schemas.


"dbo" exists as a default schema. "dbo" also exists as a DB user. By default dbo user owns dbo schema.

"db_owner" is also both schema and user. So are other db_*,INFORMATION_SCHEMA etc. In fact, it is tempting to create the same schema name for every DB user. Is that a good practice?

Beginning with SQL Server 2005, a user can own an OBJECT or TYPE that is contained by a schema owned by another database user.

Wednesday, December 16, 2009

Recipe: pumpkin soup w/o pumpkin

1 Onion
2 Potatoes
1 cup cream
1 jar of maple pumpkin butter

Satay chopped one white onion with olive oil.
Throw in 2 chopped potatoes.
After being somewhat cooked, blend until smooth.
Pour back to pan, add a cup of cream and a whole jar of MAPLE PUMPKIN butter.

Tuesday, November 24, 2009

XML Serializer: How to omit namespace and other redundant info

public static string SerializeType(Type aType, object aObject)
{
XmlSerializerNamespaces lXmlSerializerNamespaces = new XmlSerializerNamespaces();
lXmlSerializerNamespaces.Add("", "");
XmlSerializer lXmlSerializer = new XmlSerializer(aType);
XDocument lXDocument = new XDocument();
using (XmlWriter lXmlWriter = lXDocument.CreateWriter())
{
XmlWriterSettings lXmlWriterSettings = lXmlWriter.Settings;
lXmlWriterSettings.OmitXmlDeclaration = true;

lXmlSerializer.Serialize(lXmlWriter, aObject, lXmlSerializerNamespaces);
lXmlWriter.Close();
}
return lXDocument.ToString();
}

Thursday, October 1, 2009

Write Dataset to XML with WriteSchema

Serializing dataset ignores empty datatables

When you call lDataSet.WriteXml(aXMLFilePath), any data table without rows will be ignored. To include it (because table schema may still be important), use the WriteXml overload that writes to an xmlWriter and enable"WriteSchema".

I use XDocument that can create XmlWriter but I'm sure there are other ways.

XDocument lXDocument = new XDocument();
using (XmlWriter lXmlWriter = lXDocument.CreateWriter())
{
lMasterDataSet.WriteXml(lXmlWriter, XmlWriteMode.WriteSchema);
}
lXDocument.Save(@"c:\temp\PSReportServer_MasterDataSetWithSchema.xml");




Saturday, September 26, 2009

how to enumerate enum?

internal enum ChartRendererTypes
{  TabularTextual,  GanntChartFX }
foreach (ChartRendererTypes suit in Enum.GetValues(typeof(ChartRendererTypes)))
{
}

Thursday, September 24, 2009

Debugger issues

Debugger cannot start if

Protected ReadOnly Property Logger() As ILogger
Get
CreateLogger()
Return mLogger
End Get
End Property

Why? This is not good. First, this property is intended to be get only, not set so VB requires adding ReadOnly key. Fine so far! But CreateLogger() is a function call that ensures mLogger comes out alive i.e. if mLogger is not already instantiated, then the function instantiates it, sets to specific log file etc. But we cannot test that, the VS debugger does not like that function and just simply says the debugger cannot be started! The release version bombs as well and prompts you with that dialog box asking if you want to see the error with a debugger (however, I noticed the dialog had VS2003 debugger!! I'm using VS2008 IDE!!)

Solution: Write "Me.CreateLogger()"

Saturday, September 12, 2009

Samsung 4500W printer info

Support

Things like how to scan using Scan Thru, where to buy a toner etc.

Should be able to see the printer's own website (thru a web service). Just type in its IP address as set up by DHCP router.

Ctrl panel should have Samsung Scan Manager thru which you can quick scan also - may need to set up the IP there though.

Friday, July 31, 2009

Scripting

Powershell
http://powershell.com/Mastering-PowerShell.pdf

Muse

on seemingly promising stock rally
==========================
it's not green shoots. It's an assisted form of convalescence.
it's contrived from less-than-desirable cost-cutting measures.

Tuesday, July 14, 2009

DataSet Related

Copying a datatable
===============
When trying to add a datatable to a dataset and you get an error saying datatable belongs to another dataset, then do this: Set a new copieddatatable = origdatatable.copy(). You should be able to add the new copieddatatable to the dataset.

Saturday, June 20, 2009

sponsored web search

http://research.microsoft.com/pubs/74046/ICDE2009.pdf

Friday, June 12, 2009

Calculate font width with GDI+

http://www.eggheadcafe.com/community/aspnet/2/10911/heres-a-sample.aspx

public Bitmap Render()
{

Graphics g = Graphics.FromImage(_canvas); //painting surface. uses canvas.

Font font = new Font(_font, _fontStyle);

SolidBrush shadowBrush; //for painting text
SolidBrush textBrush;

int nCharsFitted; //this is how we know we have all of the characters on the canvas
int nLinesFilled; //this tells us how many lines the text uses

//antialias fonts.
g.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAliasGridFit;

//create new canvas and set the size
Size canvasSize = _canvas.Size;
SizeF canvasSizeF = new SizeF(_canvas.Width, _canvas.Height);

//specify formatting options
StringFormat stringFormat = new StringFormat();
stringFormat.FormatFlags = StringFormatFlags.FitBlackBox & StringFormatFlags.NoClip;
SizeF textSizeF = new SizeF(0,0);

//fit text
while (true)
{
//measure text
textSizeF = g.MeasureString(_zText, font, canvasSizeF, stringFormat, out nCharsFitted, out nLinesFilled );

//see if it fits
if ((canvasSizeF.Height >= textSizeF.Height) &
(canvasSizeF.Width >= textSizeF.Width) &
(nCharsFitted == _zText.Length) &
(nLinesFilled * font.Height <= canvasSizeF.Height)) { //text fits break; } else { //text doesn't fit. lower point size and try again. font = new Font(font.FontFamily, font.SizeInPoints - 1, font.Style); } } //set point for where to start drawing the text PointF textPoint; PointF shadowPoint; switch(_eAlignment) { case Engine.Imaging.Alignment.Center: textPoint = new PointF((canvasSizeF.Width - textSizeF.Width) / 2, 0); break; case Engine.Imaging.Alignment.Right: textPoint = new PointF(canvasSizeF.Width - textSizeF.Width, 0); break; default: textPoint = new PointF(0,0); break; } //apply shadow? if (_nShadowDepth > 0)
{
shadowPoint = new PointF(textPoint.X + _nShadowDepth, + _nShadowDepth);
shadowBrush = new SolidBrush(_shadowColor);
g.DrawString(_zText, font, shadowBrush, new RectangleF(shadowPoint , canvasSizeF), stringFormat);
}


//define brush with color to paint text with
textBrush = new SolidBrush(_textColor);

//apply text
g.DrawString(_zText, font, textBrush, new RectangleF(textPoint , canvasSizeF), stringFormat);


textBrush = null;
shadowBrush = null;
g = null;
stringFormat = null;

return _canvas;
}

Another one
http://social.msdn.microsoft.com/forums/en-US/vblanguage/thread/8b301d31-5b2c-4c6d-b78f-c0867dd0084e

Monday, June 1, 2009

Random Health and Food Topics

Spicy food like curry may help fight brain cancer. Also first ever vaccine may be in the works. Here's the story on extratv.

Saturday, May 30, 2009

Down to quantities

References

healthy diet fit body

Per day

to fight hypertension and high blood pressure

fruits and vegetables in general are the best.

increase potassium - 4700 mg : bananas, potatoes (no, you can’t have french fries), canned white beans, yogurt, halibut, tuna, lima beans and winter squash

reduce sodium (most important for reducing hypertension, others are secondary) - 2300 mg (approx 1 tablespoon) : salty snack eaters eat 4X as much while average americans eat 2X as much

magnesium - 500 - 1000 mg: in a well-bal diet.

(increase) calcium - 800 - 1000 mg: average american gets half. Take supplement with 3-400mg.

** Vitamin D **

People have not figured out on D!! Just read this on WebMD and on MSN Health, and you will see that the experts have no freaking clue as to HOW MUCH D we need. Ask my doctor if I need to take D. I was going to order D supplements (since thru diet, getting 2000IU is almost impossible?) but I'm hesitant now. More info needed...

For me, I figure about 2000 IU (dark skinned, not enough sun exposure). Get this thru supplement since D is hard to get from food and since sun is not always available.

The U.S. Recommended Dietary Intake for vitamin D is currently 400 International Units (IU). However, research is suggesting that may not be enough. In fact, a recent study in the American Journal of Clinical Nutrition suggests that doses of 3,800 to 5,000 IU may be needed to maintain optimal blood levels, as the body doesn't absorb all it takes in. The official safe upper-limit (UL) for vitamin D intake is 2,000 IU, although many researchers are now saying this is much too conservative and it should be reset to 10,000 IU. However, scientific organizations are slow to change their recommendations, so it may be a while before the official UL is reset to a higher level.

A minimum of 1,000 IU every day is recommended. Keep in mind if you're overweight or dark-skinned, you are at a high risk for deficiency.

One cup of fortified milk has only 100 IU of vitamin D (we actually get much more vitamin D from the sun than we could ever get from food).

If you expose your face, arms, back, or hands to the sun three times per week for 15 minutes between 11 a.m. and 2 p.m., you'll get a dose of about 3,000 IU of vitamin D. So, before you slap on the sunscreen, give yourself this small amount of sun exposure. Then, you can put on the sunscreen to avoid over-exposure to the sun.

Heart disease prevention

maintain body weight
exercise
low saturated and trans fat
high omega3 fatty acid
keep LDL below 100, HDL over 40
be happy

Whey protein
.7 * body wt of about 150 = 105 gm of whey (too much??)
still sounds too much. taking 20g scoop 4 times already sounds enough.
space it out daily so liver/kidney is not overworked
isolate form is better but more expensive, mix of isolate and concentrate (higher % of isolate though) gives you biggest bang for buck

What to eat before during after excercise?
after exercise, only 10-20g of protein says this article!!

Saturday, May 23, 2009

abs workout

best abs workout - most with no tools

best abs workout take 2

long arm weighted crunch - with light dumbells on each hand and lying flat with knees bent

youtube at home crunch

youtube ** good review

What's in a breakfast?

Why breakfast is important?

Cereals are just "better than nothing". If u must, look for whole grain, add >5g of daily fiber, <25% sugar calories.

Vitamin D, Fish Oil, Vitamin E etc.

after workout supplement

WebMD Protein Shakes
10 Diet Myths - after workout, get 8 grams of protein (small carton of low fat choco milk). no need to get 4 scoops of whey.

For body building, get something with more protein(>50%), less carb.

Best way to get protein is always through diet, but this is difficult to do right after workout. whey is the best source of supplemental protein (better than milk, egg or soy) RIGHT AFTER WORKOUT (in body for short time). casein protein is for meal replacement or before going to bed (in body for long time).

Low carb dutch chocolate

Thursday, May 21, 2009

Mutivitamins


My summary:
What you are looking for in a multivitamin is various vitamins and minerals. Minerals are bulky so that's why you are prompted to take a few pills a day. Chances are 1 pill a day probably cannot give you 100% of daily value as far as minerals are concerned but it is certainly possible to get 100% of all vitamins in a pill. But that's ok since I think we should get minerals via other means on a daily basis.
- No iron
- Calcium: 1000 mg (DV), get ALL from food, if over 51, 1200mg, if over 75, 1500mg, men shouldn't take a calcium supplement; Andrew Weil, founder of the Arizona Center for Integrative Medicine at the University of Arizona, says it increases the risk of prostate cancer.
- Carotenoids desired: beta carotene, alpha carotene, gamma carotene, lycopene, lutein, beta-cryptoxanthin, zeaxanthin or astaxanthin.
- vitamin A: sources are usually retinol (aka "performed vitamin A" or acetate or palmitate) and beta carotene. Def go with latter. Excess retinol (acetate, palmitate) is said to cause reduction in bone density and fracture and harm liver health. Take no more than 5000 IU and 100% from beta carotene is the best. No vit A for smokers! Also, 50% from supplement and 50% from food is the best.
- vitamin B6: 2(DV)-50 mg (for heart disease)
- vitamin B12: 6 mcg(DV) but if over 50, 25-100 mcg (for heart disease and nerve damage)
- vitamin C: 200-500 mg (heart and age related diseases)
- vitamin D: 400 IU or if north of boston 600IU in winter/fall
- vitamin E: 400 IU (30IU is DV), make sure type is d-alpha-tocopherol (rather than "dl") or tocotrienols
- vitamin D: 2000 IU
- folic acid: 400(DV)-800 mcg (heart)
- chromium: 200 mcg (120 mcg DV) (prevent diabetes)
- Magnesium: 400mg(DV), get from supplement and food like beans and artichokes (bones and heart)
- yeast based selenium: 200 mcg if man (prevent cancer), less than 70 mcg if woman.

- I think, due to potential side effects and risks, it is best to know what you lack the most and focus on supplementing only those. To that end, nothing beats the real sources like fruits and vegetables etc. Look at the vitamins picture.




WebMD Multivitamins FOR MEN

References:

What to look for?

What to look for, take 2?

Bad for you? Get everything from diet, except vitamin D which you can get from supplement!

Should I? For athletes and body builders, need to replace vitamins and minerals fast, so may make sense.

On and on and on.... My conclusion: take something to replenish vitamins and minerals right after workout in juice form . Otherwise, just take D on a daily basis. Rest, get from diet.

What to drink right after workout?

here is one
another one

So, maybe drink my regular NATURAL fruit juice in the morning and after workout, but mixed with supplements? YEAH

How to choose best multivitamin?

If you must, look for those with:

No iron

3,000 to 5000 International Units of vitamin A, with at least 20% of it as beta-carotene

A lot of vitamin D

USP insignia

Good Reviews

One a day Men's Healt Formula - no iron, not sure about USP, $10 per 100 tablets

Centrum Silver Ignore 50+ sign

Fish oil supplements

Some Info on Fish Oil Supplements

WebMD Good for High Blood Pressure
WebMD Omega 3 strategy
After-taste can be eliminated by storing capsules in the freezer and taking them frozen.
Flax seed oil is not as good as fish oil (fish oil has both EPA and DHA, flax seed oil doesn't).

Good ONE-A-DAY ones with IFOS 5 star ratings

Make sure you go to IFOS to ensure 5 star ratings. The stuff you buy has to be of a certain batch with certain expiry date (older batches from the same company may be of poorer quality).

The following products are by batch number/expiry date
EPA/DHA are in mg/1000mg

Critical Omega from Renew Life
Batch 082917/09.11
IFOS 5 star findings: EPA/DHA 439/230
60 capsules
http://www.renewlife.com/
vitacost $26
(website says avail in WholeFoods and Triple Harvest Co-op near 02141 zip)
Ordered from vitacost - 2 units, they charge $5 for S&H


Kirkland Signature Fish Oil
Not on IFOS but high Amazon ratings ($25 for 180 gels!!! sounds too good to be true?), also sold by Costco

GNC Triple Strength Fish Oil
EPA/DHA 647/253
60 gels, $15 for goldcard holders


Other good ones I ditched for various reasons

Barleans - not on IFOS, good review but suggested use is 2-6 per day!!!
See Yourself Well Omega 3 - IFOS, but 3 per day (also known as another site Nuratec), 300 capsules $100
Zone Labs OmegaRx - IFOS but 4 per day, from zone site, 120 capsules for 30 day is $40 with autoship or $50 without
PharmaOmega - again more than 1 per day

Thursday, May 14, 2009

C# keywords I

ref and out
===========

Use ref if the type instance already exists before entering the function. Use out otherwise. Therefore, ref is in and out.

Sunday, May 10, 2009

MSG

Monosodium glutamate, or MSG, earned its reputation in Asian takeout kitchens across America, but almost all fast-food restaurants use the flavor enhancer to some extent. Interestingly, MSG has no distinct taste itself. Instead, it amplifies other flavors, especially in foods with chicken or beef flavoring, through processes that scientists don't fully understand.

http://recipes.howstuffworks.com/processing-facts-channel.htm

HFCS

http://recipes.howstuffworks.com/high-fructose-corn-syrup2.htm

Unlike glucose, which is metabolized a number of ways by your body, fructose is only metabolized by your liver. When the liver receives more fructose than it can handle, the excess sugars are turned into fats in the form of triglycerides, which are harmful to your arteries and your heart.

The biggest problem is that HFCS is being added to food items that don't normally have sugar and that you wouldn't even describe as sweet -- crackers, for instance. So, not only are we chugging down lots of sugars with our sodas, but your PBJ sandwich could have HFCS in each of its three ingredients. Meal after meal, day after day, all of this extra sugar adds up, and that, and not necessarily the qualities of HFCS itself, is likely one reason why rates for obesity and diabetes have climbed since the introduction of HFCS. (Other factors are in play as well, such as decreased activity and exercise levels and increased fat consumption.)
So what can we do? Well, for starters, do everything you're already supposed to do. Get regular exercise, watch your fat intake and get regular medical checkups. Next, it wouldn't hurt to mimic the practices of those strange (and rare) individuals in grocery-store aisles who read the labels of the food they are purchasing. Once you get in this habit, you will likely be shocked to learn just how much of your regular grocery purchases contain high-fructose corn syrup. If nearly all of your food contains concentrated sugars, it stands to reason that you'll be eating too many sugars. And if you want to go crazy, eat some fruits and veggies. You'll get all the glucose you need (not much), and these healthier alternatives will take the place of the less healthy foods now flooding our markets and grocery stores.

Monday, April 20, 2009

ETF

Consider an ETF as a company stock that invests in certain things - like in S&P500 index, shorting of S&P100, fixed income of anything like emerging markets, gold, even in something as specific as homeland security. In essence, they can invest in anything and can work with either up or down market.

If you are investing more than $5000, ETFs are better than mutual funds due to cost savings. However, there are usually transaction fees (every time you buy more shares or sell shares). Find brokerage firm or a bank that charges low fee (based on your total investment with them) or NO FEE.

Tips

Find the right brokerage/bank with very low or no fee if you maintain balance.

Invest your retirement money in ETFs.

Resources

ETF Browser from Yahoo
Filter by "bear market" to see short and ultra-short ETFs

Brian T Mikes - Dynamic Wealth Report

Weekly Top 10 ETF Rankings from Trader Planet

ETFs 60 seconds guide from Fool

ETFGuide.com

ETF Investing Guide from Seeking Alpha

VIX

http://marketsci.wordpress.com/2008/09/22/test-of-condor%E2%80%99s-vix-based-trading-strategy/

http://trading-stock-market.blogspot.com/2008/03/vix.html

http://www.tradingmarkets.com/.site/stocks/commentary/editorial/-68023.cfm

http://vixandmore.blogspot.com/2007/07/tradingmarkets-5-vix-rule.html

http://seekingalpha.com/article/105643-trading-strategy-vix-spread-and-the-stock-market

*** http://www.smallcapnetwork.com/scb/how-i-use-the-vix-to-trade-stocks/2274/

http://wallstreetblips.dailyradar.com/story/trading_strategy_the_vix_spread_and_the_stock_market/

http://www.ibankcoin.com/woodshedderblog/index.php/2008/09/15/stretched-vix-strategy-signals-buy-the-spy/

Thursday, April 16, 2009

My Investment-related Links

Sector Options
http://www.nasdaqtrader.com/Micro.aspx?id=phlxsectorindexoptions
http://www.optionsmentoring.com/stockoptions/Trading_a_Sector_Option_103.shtml

Market Sector Indices (may or may not have options)
http://quotes.nasdaq.com/aspx/sectorindices.aspx

Options on ETFs and HOLDRS
http://www.cboe.com/Products/optionsOnETFs.aspx

iShares ETFs
http://us.ishares.com/home.htm?c=JAC01&gclid=CMSZivqA9pkCFeRM5Qodsl2tSA

The Options Insider
http://www.theoptionsinsider.com/unusualactivity/?id=1739

Learn Options tips - http://www.theoptionsinsider.com/tradingtechnology/

Learn options from OptionPlanet (associated with TOS)
http://www.optionplanet.com/assembled/list.html

Learning about stocks, options, forex (Learning Markets)

Premarket (8 - 9:30) and afterhours (4 - 6:30) (simple course)
Only stocks can be traded, but no options or any derivatives?

Interesting statistical finds on market

Earnings Announcements

http://www.cqa.org/uploads/papers/1287938062443d2a80c3515.ppt#298,22,Abnormal

There are abnormal order flows around announcement dates but most of these are by small traders (<$5000 per trade?).

Small buys go way up on announcement days. Institutions buy BEFORE announcement days, expecting buying pressure (to partially arbitrage). These buying pressures are from small investors. Buying pressures mean prices go up.

There is a BIG earnings announcement premium (observed by: earnings announcements correlated with higher volumes and higher volumes lead to higher premiums)

Sam: is reverse true of selling pressure? No doubt!

Whoa Market!

So how does a company refinance its maturing debt by going to the credit market?

Tuesday, April 14, 2009

Basics of Various Options Strategies

Straddles and Strangles

http://www.finotec.com/options/straddle-strangle-strategy.php

TOS Commission Rates

https://www.thinkorswim.com/tos/displayFaq.tos

What are thinkorswim's commission rates?

For Stock orders, you have the choice of 'Per Share Commission' at $.015 per share ($5.00 minimum) OR 'Flat Fee Trading' at $9.95 per trade (market or limit orders; 5,000 shares maximum). For Option orders, you pay the lesser of $2.95 per contract OR $1.50 per contract plus $9.95 (only one $9.95 charge for unlimited spread legs). For Futures orders, you pay $3.50 per mini contract (inclusive of exchange fees).

Commissions on option spreads

If the trade was entered as a spread, there is only one $10 ticket charge regardless of the number of legs associated with that spread, or $2.95 per contract if that's less.

TOS Margin Requirements on EQUITIES and EQUITY OPTIONS, Margin Schedule

https://www.thinkorswim.com/tos/displayFaq.tos

What is a pattern day trader?

Effective September 28th, 2001 the NYSE and NASD imposed a $25,000 minimum equity requirement for 'pattern day traders.' Consistent with the new margin rules, if a thinkorswim customer's margin account falls under $25,000 and the customer has opened and closed positions on the same day four times within five days, the customer will not be allowed to open new positions until the $25,000 requirement is restored.
Additionally, for a designated 'pattern day trader' account, the customer is allowed on any day to open new positions up to a total of the account's Day Trading Buying Power (defined as four times account equity less maintenance margin requirements). The rule requires orders exceeding Day Trading Buying Power to be rejected.

Margin Requirements

What are your margin requirements for equities and equity options?

Please see our margin requirements in the MARGIN SCHEDULE in the RATES section. Generally speaking, our margin requirements for equities and equity options conform to NASD requirements.

How do I calculate the margin on a short call or short put?

To learn how to calculate the margin requirement of a short call or short put, see our margin schedule.

Margin Schedule

Options: Exercise and Assignment

https://www.thinkorswim.com/tos/displayFaq.tos?categoryKey=TRADING

How do I exercise an option contract prior to expiration?

If you trade options, it's imperative that you understand the basics of exercise and assignment. You don't need to know all the theoretical details, but you must be prepared for it, especially if you're short options where you don't control the exercise feature. Learn more in the "Exercise and Assignment, Early or Otherwise" section of the Option School section of our website. Remember that clients are required to submit an electronic exercise advice by 3:20 pm CST.

How do I know that I have been assigned on a short option?

If you are short any options that are in the money you should check your account daily to see if you have been assigned. In the case of early assignment (assignment prior to expiration) we will make every attempt to reach you prior to the opening of the market on the day we receive the exercise notice on your behalf, but you still need to maintain the habit of checking your account personally.
At expiration, any equity option that is .01 of a point or more in the money will be automatically assigned. In addition, in the money cash-settled options are exercised on the holder's behalf. There is too much volume on expiration to contact each person individually, so you need to check your accounts on the TOS system on Monday morning after expiration to see where you stand. In any case, our clearing firm will send you a confirmation showing your purchase or sale of stock on an exercise.

Please explain automatic exercise at expiration.

Equity options that are in-the-money by .01 of a point or more by the close of trading on the Friday before expiration are automatically exercised. Clients who wish to exercise options that are in-the-money by less than .01 of a point must notify us electronically via the exercise page by 3:20 pm CST.

TOS Order Types

https://www.thinkorswim.com/tos/displayFaq.tos?categoryKey=TRADING

***
https://www.thinkorswim.com/tos/displayPage.tos?webpage=servicesOrderTypes

What types of orders does thinkorswim accept?

For all listed products, the thinkorswim software accepts

market
limit
stop
MOC - Market On Close
LOC - Limit On Close
trailing stop (read disclaimer below)
stop limit
conditional
OCO - One Cancels Other (read disclaimer below)

For option spreads, the thinkorswim software accepts

limit
conditional
OCO (read disclaimer below)
market


Through our trade desk, we accept ANY order type imaginable.

All orders, except for option spread orders, are executed electronically. Option spreads are executed via open outcry because none of the five option exchanges currently support electronic spread execution. All trade executions and confirmations will be delivered electronically back to the trading application.

Order Type Explained

LIMIT - default order type for all single option, spread and stock orders. The limit price for buy orders is placed below the current market price. The limit price for sell orders is placed above the current market price. Limit orders will be filled at the limit price or better, but are not guaranteed a fill.

MARKET (also known as "not held") - order used to guarantee an execution, but not guarantee a price or time of execution. The risk of market orders is that you have no control over what the execution price is. We strongly suggest you avoid using them with options, especially option spreads.

STOP (also known as "stop loss") - order used to open or close a position by buying if the market rises or selling if the market falls. The stop price for buy orders is placed above the current market price. The stop price for sell orders is placed below the current market price. A stop order turns into a market order when the stop is triggered, so the final execution price or time of a stop order is not guaranteed. The same risks of market orders apply to stop orders.

In addition to the Standard STOP order which is sent to the exchange, we have created 3 new STOP order types. The "Mark" stop order will be triggered once the Mark or value of the asset reaches or surpasses your stop price. The "Bid" stop order will be triggered once the bid of an asset rises to your stop price or surpasses it (this can be used for a Buy Stop order). The "Ask" stop order will be triggered if the ask price falls to your stop price or surpasses it (this can be used for a Sell Stop order).

STOP LIMIT - order used to open or close a position by buying if the market rises or selling if the market falls, but that turns into a limit order when the stop price is triggered. Stop limit orders have a stop price and a limit price. When the stop price is triggered, the limit order is activated. The stop price for buy orders is placed above the current market price. The stop price for sell orders is placed below the current market price. The stop price does not need to be the same as the limit price. Just as with a limit order, the stop limit order will be filled at the limit price or better, but may not be filled at all.

[Combining Stop and TrailingStop is a good strategy]
TRAILING STOP - stop order that continually adjusts the stop price based on changes in the market price. A trailing stop to sell raises the stop price as the market price increases, but does not lower the stop price when the market price decreases. A trailing stop to buy lowers the stop price as the market price decreases, but does not increase the stop price as the market price increases. In both cases, the stop "trails" the market price. When the stop price is reached, the order becomes a market order. The same risk of market orders applies to trailing stops.

[Combining StopLimit and TrailingStopLimit is a good strategy]
TRAILING STOPLIMIT - this order type works the same way as the trailing stop, only instead of a market order being sent to the exchange, a limit order will be sent to the exchange. With this order, you will be able to stipulate the worst price you are willing to accept for a fill. There is no guarantee that you will be filled, though, as the price may gap through your limit price.

MOC (Market on Close) - order that buys or sells at the market price at the close of trading. You must submit the order by 2:40 pm CT. The same risk of market orders applies to MOC orders.

LOC (Limit on Close) - order that buys or sells at a limit price at the close of trading. You must submit the order by 2:40 pm CT. The order can be filled at the limit price or better, but is not guaranteed a fill.


How do OCO orders work?

OCO orders (one cancels other) are orders that work simultaneously and cause a cancel to be sent when one of them fills. OCO Disclaimer: There is no guarantee that the cancel can be sent in time to prevent the second order from filling, leaving you with executions on both orders. It is especially important not to place an OCO order where both component orders are close to the market.

[Combining Stop (StopLimit) and TrailingStop (TrailingStopLimit) is a good strategy]
Trailing stop disclaimer:

thinkorswim does not recommend trailing stop orders, as there is no guarantee that your order will be filled at or near the designated stop price, which is especially dangerous in rapidly rising or falling markets. In addition, trailing stop orders will accentuate volatility in rough markets.

A trailing stop allows you to specify a limit on the maximum possible loss, without setting a limit on the maximum possible gain. A trailing stop SELL (BUY) order is an order where the stop price is set at some fixed amount away from the asset's bid (ask). If the market price rises (falls), the stop loss price also rises (falls) by this fixed amount. If the stock price falls (rises), the stop price remains the same. When the market moves against the position by the set amount, the stop order is triggered, and is submitted as a market order.

For example, XYZ shows a price of 50.00. A customer puts in a trailing stop order to sell at $1.00 below the current bid. A stop order is entered into the system for $49.00. When the bid price rises to $52.00, the stop order price rises to $51.00. When the bid price drops to $51.50, the stop order price remains at $51.00. When the ask price drops to $51.00, the stop order is triggered and submitted as a market order.

NOTE: The market order resulting from a triggered trailing stop order is not guaranteed to execute at any specific price. A trailing stop sell order becomes a market order when the last traded price is less than or equal to the stop price or if the ask price is less than or equal to the stop price (which is determined by the highest bid price after the tralstop is entered.) Trailing stop sell orders for Nasdaq stocks and US equity options are only triggered after two ask prices are less than or equal to the stop price.

A trailing stop buy order becomes a market order when the last traded price is greater than or equal to the stop price (which is set at a specified differential above the lowest offer). Trailing stop buy orders for Nasdaq stocks and US equity options are only triggered after two bid prices are greater than or equal to the stop price. For US equities markets, stop orders will only be elected by prices posted during normal NYSE trading hours.

Thursday, April 9, 2009

My Trading Strategies

My Trading Strategies

combine stop with a trailing stop

http://www.investopedia.com/articles/trading/08/trailing-stop-loss.asp

One of the best ways to maximize the benefits of a trailing stop and a traditional stop loss is to combine them. Yes, you can use both, but it is important to note that initially the trailing stop should be deeper than your regular stop loss. An example of this concept is to have a stop loss set at 2% and the trailing stop at 2.5% so that you are able to trail a stock's price movements without getting stopped early in the game and allowing for some price fluctuation as the stock finds support and momentum. Be sure to cancel your original stop loss when the trailing stop surpasses it.








make use of margin
how?


My Market Info Strategies

trade earnings announcements:
ST price movement depends not on the actual value of the earnings but on expected/actual difference, actual vs sector benchmark, price momentum, support n resistance on chart.

EPS can be GAAP or non-GAAP and most companies announce both. Make sure when you compare estimate vs. actual, you are using either GAAP or non-GAAP on both (TOS software seems to go for non GAAP while Bloomberg does GAAP)

earnings calendar from bloomberg

What is the best source of real-time financial market news as it happens? Check out these and compare: tradethenews, eSignal's RealTimeTraders Pro Newswire

Spread between nasdaq and DOW/S&P

There seems to be a consistent spread between dow and nasdaq indices although they are correlated. How to take advantage of this spread? profit when (1) nasdaq>dow (2) nasdaq<dow or (3) as long as there is the spread.

Strategies

before mkt open, look for companies that made earnings announcements after last close.
a. place a limit BUY order on option with a large LIMIT if you think the underlyer is hot (is there a better one, maybe traillimit or trailstop on BUY?). Can do before the mkt opens.
b. after the BUY goes thru, immediately place a trailingstop (or combine it with a stop).

professional traders sometimes sell shares just before earnings announcements (they made money already and don't want to be exposed to volatility caused after earnings announcement) which can cause momentary price drop. can we take advantage of this?

many companies announce earnings and other financial data during off market hours so there could be a good opportunity to trade during premarket 8-9:30 or after hours 4-6:30. however, only stocks are allowed. what's a strategy here whereby you take advantage of earnings news and buy/sell stocks, at the same time enter options orders to kick in when mkt opens?

many websites and trading apps (like TOS) show earning calendars but how to search on the blue chip companies only? you may have to do this manually i.e. create a list of blue chip companies with announcement dates. know that companies are not required to honor their announcement dates. right after the announcement, i think you can make money by taking an appropriate position (call or put) and putting in another trailstop immediately.

pre-market and after hours trading
look at TOS Times and Sales under "gadgets" to see what prices stocks are trading on various ecns after hours or before mkt open. may be able to assess buy/sell pressures from this info and create appropriate trades right when mkt opens. sam: my idea is that only the pros trade in off hours and mkt open usually follows the price movement in the off hours.

NASDAQ-100 Pre-Market Heatmap

adopt contrarian techniques
http://biz.yahoo.com/etfguide/090417/241_id.html?.&.pf=retirement


My Options Strategies

small but sure intra-day profit on OEX

Look at where the market is going. When you detect a turnaround, quickly take that position and buy (call or put, depending on what direction the turnaround is occurring). Wait to see if your hunch was right.
(A) If Y, do 2 things. (1) set an alert for floor (so that u might wanna sell and mimimize loss) and (2) set an alert for ceiling (so that u can go back and comfortably make a trailstop order). Alternatively, without the alert, you can create an actual stop loss order for (1). Alert(1) gives you the last-minute choice to hold off on selling if you think your position is going to turn around, but don't wait too long. If it is not turning around, your hunch was not right so make another trade outlined in (B).

(B) If N (you hunch was not right), do 2 things. (1) create another order in the direction the market is moving against your original hunch i.e. buy call or put, opposite to your first order. [Don't be so concerned about this second trade because it is almost impossible to lose money on both trades since they are opposite and you will be close to break-even at the worst.] (2) Monitor both of your positions. You are relatively safe. Your piority now should be to minimize loss and to even make some profit but that may not occur intra-day, especially if the market is only moving sideways. So at this point, when you have 2 opposite positions, you want to extend your closing out to another day ot two, whenever the market moves drastically (and they have been generally speaking, especially when it opens). The only caveat is that, if you are only 1 or 2 days away from expiration, the time value decays much faster so the market has to move that much more drastically to break even with 2 positions over 2/3 days. When one trade moves enough that, if you were to close out BOTH positions you would break even, (1) close out the trade that is of a lower value (the one currently moving against market) and (2) immediately create a stop loss or trail stop on the other.

Hopefully you will make profit with (A). If not, at worst, you will break even with (A) and (B). Example, I bot OEX 395 may call (month away from exp) at $14.2 sometime after 10AM when the market was turning around from negative open to when it was just hitting the positive side. I then set a floor alert at BID=$13.9 (looking back this should have been $13.4 to confidently assert the market was moving against me but oh well i lucked out here) and ceiling alert at BID=$15.2. I then got the ceiling alert (whoa lucky me!) after a few minutes (asserting my hunch of turnaround was right) at which point I created a trailstop at -.30 (meaning MKT-.30 most probably with TOS since they don't give you the option to specify MKT-.30, BID-.30 or ASK-.30) when BID=$15.2 and ASK=$15.60 or something (ignore the LAST which was still at $14.2). This tells me MKT was somewhere between $15.2 - $15.6. Anyways the trailstop got triggered and the position was sold at $15.50.

I was comfortable enough to shell out $1300 to $1600 for this one contract and to make about $100-$150 profit like this. I do think this strategy is relatively safe. I should aim to make $500 intra-day profit by either (1) shelling out $5000-$6000 i.e buy 5 contracts or (2) run this strategy multiple times a day (especially when you can afford to watch market turn around on a big piece of news).

I also think this strategy is better than trading a spread because with spread, you are essentially trading both (A) and (B) simultaneously while saving on commission. With this strategy, on the upside, you could potentially make a lot more gain with (A) without (B), while on the downside, you pay an extra commission to take the same position as the spread. I think that extra commission, being the cost of this strategy over the spread strategy, is well worth it.

when to place the 1st (A) trade? (1) right at mkt open - if the previous close was really up or down, then assume mkt open is turning around (2) after mkt open - give 15 mins or so whenever mkt begins to take a turn (may or may not happen though) (3) near the mkt close - if the mkt is moderately higher/lower to much higher/lower, assume the next morning's open will turn around so make the trade at/near mkt close in the opposite direction (4) when a piece of news during mkt seems to break the market trend - usually happens fast, make the trade right away.

On DJX (1/100 of DJIA)

Applies to any any index option: wait until u see a trend (not at the bell or before, give some time to settle). jump in and set a stop. hopefully stop won't trigger. assuming so, create a new TS order with a fairly wide gap (where if stop does trigger on this order, be prapared for a small loss. on the upside, the wide gap shields u from small hiccups and hopefully puts you in a profitable path). then replace the TS with a new one as time goes by, locking in some profit. ** if ur at almost the end of day, n u find that makrket is moving against u, don't make the trail stop kick in yet i.e. make the gap even wider if u can (as long as u can take that extra loss in the worst case scenario). the idea is that, hopefully stop does not trigger and the order remains active at the next open. that's when u may see market swinging back in ur favor (on average, if mkt goes up big on a day, next day it sheds some and vice-versa) or at the worst case, u will lose that extra money u r ok with loosing.

Wednesday, April 8, 2009

Let's character-assasin Dennis Miller...

Dennis Miller was one of the most intellectually wry observers of cultural and political attitude in this country as of only a few years ago. Now he's turned into a war-mongering Bush-loving right wing sycophant. He appears on O'Reilly's show occasionally as Mr. Reilly's towel boy. What a shame!

Wednesday, April 1, 2009

Buying home

http://www.crpboston.com/news.php#52

So you think you’re ready to start your search for a new home? Often buyers begin their search by visiting open houses and that is a very good way to begin the process. But, don't waste time visiting properties that are priced out of your budget. Not only will you spend time looking at a home you can't afford but you'll start feeling there's nothing you like in your price range. Instead, start by looking at properties priced BELOW what you can afford and work your way up the price ladder. You be surprised to find just what you're looking for at a price you can afford.With the tightening of the mortgage market, lenders have become much more careful about the borrower's ability to pay the monthly mortgage. Gone are the days of \"Sure you can afford it - it's only going to go up\" and \"We're happy to lend you the money!. In the reality of today's marketplace, lenders are much more diligent about how they lend and to whom.With this in mind, tip # 1 is: SPEAK WITH A MORTGAGE BROKER OR A REPUTABLE LENDER before staring your search to learn based on your personal financial dynamics, exactly what you can afford. Armed with this information, you'll not waste your time looking at properties you'll never be able to buy.An extremely valuable tool in this regard is Chase Manhattan's \"Passport To Purchase Program\" offered by Otis & Ahearn. Chase will provide you with a pre-approval letter (no commitment to borrow from them is required) and will lock your mortgage rate for 90 days. If the rate you've locked goes down, so does your rate. Tip number #2 is: GET A PRE-APPROVAL LETTER for the amount your lender says you can afford. There's a big difference between a Pre-qualification letter and a Pre-approval letter. Pre-qualification means that you've spoken with a lender and they feel that because you're still breathing and are employed you should have no problem qualifying for a loan. Pre-approval means that you have actually taken the time to apply for a mortgage with a lender and that lender has agreed to lend you a certain amount of money provided specific conditions are met. For example you still have to be alive at the closing, still employed and there can be no significant changes in your credit since you were Pre-approved. There may be more contingencies to the lender giving you the loan but you get the point.Tip #3 is:KNOW WHERE YOU STAND. Knowledge equals power. Knowing how much of a loan you can get, at what rate of interest and what your monthly payments will be and having the Pre-approval arrow in your quiver, you are now in a position to know in what price range you can search for your home. That knowledge helps you and/or your Broker help you find the right property and puts you in the position of being able to tell a Seller \"Yes, I can get the money for this property!\" It also eliminates the frustration of falling in love with a property only to discover there's no way you can get a mortgage to buy it.Tip #4 is:Know what's happening in the price range and neighborhoods in which you have interest. I provide my clients with three year historical sales information in their neighborhoods of choice. This data lets you see what is actually happening, good or bad, in any area of the city, no matter what the press is saying. Let me know if you would like to see a sample report – I call them ZoomsIn© Reports because they zoom in to real estate activity in specific Boston neighborhoods.

Tuesday, March 31, 2009

Computer Viruses and Malware

http://news.cnet.com/8301-1009_3-10207375-83.html?tag=mncol;posts

A quick way to tell if your computer is infected is to try to access the Web site of a major antivirus vendor, which the worm blocks.

Saturday, March 28, 2009

Comcast McAfee

comcast
srs32--@comcast.net, m---cc--

mcafee/comcast
srs32--@comcats.net 998d6As8
Serial Number: 7466381748335924001378100

Wednesday, March 4, 2009

Sunday, March 1, 2009

Interfaces for Collections

http://www.centrifugalbumblepuppy.com/posts/asp-net-collections-interfaces.aspx

For all public properties and method parameters, accept the least restrictive interface.

For all custom collections, implement the most restrictive interface possible.

This means that if a custom collection is in the slightest bit list-like, it should implement IList whenever possible. Conversely, all your methods should accept ICollections, even if this means re-implementing some functionality through static extension classes or decorators.

Interesting Collections

[SerializableAttribute]
[ComVisibleAttribute(false)]
public abstract class KeyedCollection<TKey, TItem> : Collection<TItem>
Use this collection class (since being a generic abstract class, your collection class is actually a concrete class derived from the constructed version of the generic type) if each collection item also contains the key.

Basically, the motivation to create and use your derived class comes from the fact that it will be making good use of inherited OOB functionality from base for free and also that you can add custom behaviors by overriding some protected members of base.

Sort of a hybrid between IList<T> and IDictionary<TKey,TValue>.

To use this collection class,
(a) First, create a constructed KeyedCollection (for example, KeyedCollection<int,OrderItem> where OrderItem class has a unique field called OrderNumber)
(b) Derive a collection class from the constructed type (for example, SimpleOrder : KeyedCollection<int,OrderItem>)
(c) Override the protected member GetKeyForItem.

Saturday, February 28, 2009

WCF: Part 1

WCF service, WCF service class or just a sevice are all used interchangeably here to mean a WCF service class you want to expose to the world. Client and WCF client are also used interchangeably. A WCF client may or may not be a WCF service also - if it is, the term "client" is being used in the context of making a call to another service.

What is WCF?

WCF provides a runtime environment to expose your CLR types as services and to consume other services as CLR types.

How you turn a CLR class into a WCF service is easy using WCF attributes, a WCF host, WCF runtime and some prescribed methods to expose your service as an interface (aka endpoint).

Although a windows service can be developed without WCF, a WCF service is very easy to develop due to off-the-shelf facilities such as hosting, service instance management, asynchronous calls, reliability, transaction management, disconnected queued calls and security.

WCF clients and services interact using SOAP messages which are independent of transport protocols like HTTP, tcp, msmq, named pipes etc. Thus, a WCF client can interact with a non-WCF service while a WCF service can interact with a non-WCF client (though if both services and clients can be developed with WCF, you get WCF-specfic advantages mentioned above).

A WCF client never directly interacts with a WCF service - it always uses a proxy (allowing location transparency)

A WCF client can easily interact with a WCF service that may reside in the same app domain, across app domains, across processes or across machines.

A WCF Service Has >1 EndPoints, Where an Endpoint is a True Interface

Endpoint is a term to encapsulate 3 of the properties that describe a service class you want to expose to the outside world. A=Address (where), B=Bindings (how) and C=Contract (what). In other words, an endpoint is an interface to a WCF service class.

An endpoint has inherently nothing to do with service class code. A host is required to expose the endpoint.

Address: is platform-neutral and specifies location and transport protocol to use with the service class. Format is as follows.

[transport]://[machine/domain][:optional port]/[optional URI] i.e.
http or net.tcp or net.pipe or net.msmq://localhost[optional :8001]/[optional myservice]

Bindings: A canned set of choices regarding transport protocol, message encoding, communication pattern, reliability, security, transaction and interoperability for the service class.

A client must use the same binding values as the service class. A single service class can support multiple bindings as long as each is hosted on a different address. You can use OOB bindings or OOB bindings with tweaked-in properties (on things like transaction propagation, reliability, security etc.) or write your own from the scratch.

WCF-provided OOB Bindings
BasicHttpBinding (protocol - http/s; encoding - text, mtom; interoperable - yes)
or the related BasicHttpContextBinding
WSHttpBinding (protocol - http/s; encoding - text, mtom; interoperable - yes)
or the related WSHttpContextBinding
WSDualHttpBinding (protocol - http; encoding - binary; interoperable - no)
NetTCPBinding (protocol - tcp; encoding - binary; interoperable - no)
or the related NetTCPContextBinding
NetNamedPipeBinding (protocol - ipc; encoding - binary; interoperable - no)
NetMSMQBinding (protocol - msmq; encoding - binary; interoperable - no)

Binary encoder used in WCF bindings is proprietary to MS so don't write a custom parser for the binary encoder on non-WCF platforms. Use a decision tree (starting with "are client and service both WCF?") to use the most appropriate binding for your service.

Contracts: is platform-neutral and specifies what a service class does.

4 types of contracts exist. service, data, fault and message (message contract is not recommended to be used. A better alternative is to use custom headers).

WCF Hosting

A host exposes an endpoint or multiple endpoints of a service class. A host process can host multiple WCF service classes and a single WCF service class can be hosted in multiple host processes.

A host must be running with service types already registered before a client call comes in.

A host can be an IIS, WAS (on Vista or Win2008), a Windows NT service, a console app or a Windows forms app (the latter 3 are in-proc hosts where service and clients must run in the same process. They also happen to be self-hosts because the services are not being hosted from an external process like IIS or WAS. Instead the services are hosted by WCF class ServiceHost).

Self-Hosting using ServiceHost class

[ServiceHost is WCF-provided but Juval's generic version i.e. ServiceHost<T> : ServiceHost that utilizes extension methods provides an easier model for self-hosting. See here for details]

Note that the purpose of a host is to expose the endpoints, so think of how you can expose the endpoint (address, binding and contract) of each of your service class and with self-hosting, it means your host is going to be the WCF-provided ServiceHost class.

ServiceHost : ServiceHostBase : CommunicationObject implements ICommunicationObject

We use the methods (open, close, aynch open, close) and events defined within the ICommunicationObject interface and use them on the ServiceHost class to open the host, expose the endpoints and close the host programatically or using a config file or both.

Using programmatic approach, in the main() method (of an NT service code, a console app code or a Windows forms app code) , create a new instance of WCF-provided ServiceHost class passing in typeof(YourServiceClass), repeat with a new ServiceHost instance for each service class you want to expose, and call Open on the instance.

Use a new instance of ServiceHost for each different service class you want to expose.

Open() method on an instance of ServiceHost loads the WCF runtime and launches monitoring worker threads (to monitor for client calls) that handoff calls to worker threads from the I/O completion thread pool (100 of these exist by default). Close() method refuses future calls on the instance effective immediately but the ones being run in the instance are run to completion. For a graceful exit of all ServiceHost instances, call each one's Close() when the host process itself is shuttiong down (you can override timeout 0f 10 seconds that an instance of ServiceHost is given to gracefully exit when Close() is called).

Metadata Exchange

A service that does not publish metadata is like a .NET internal class i.e. a client can still call the service if it got hold of metadata through some other mechanism.

Since the host knows everything there is to know about your service class (the host is the one to set up the endpoint/s for your service class), the host can publish the metadata also if instructed to do so.

There are 2 ways to publish metadata - HTTP-GET or a dedicated endpoint. Using WCF, you add a behavior, programatically or administratively, to your service indicating it wants the host to publish its metadata over HTPP-GET. Recommendation: use the hosting code to check for metadata behavior in config file first and if there is none, use a new instance of ServiceMetadataBehavior and set HttpgetEnabled to true, still allow the config file to override.

MEX endpoint

There is no need to enable http-get (although no harm in doing so) if you can publish metadata over a special endpoint called MEX endpoint on the host - just assign an address (full or any registered base), binding (WCF provides http, https, tcp and ipc oob) and add the metadata behavior.

You can add one or multiple MEX endpoints for your service class administratively or programatically.

Recommendation: Use Juval's ServiceHost<T> to easily enable metadata both over http and thru a MEX endpoint.


Tuesday, February 24, 2009

Extension Methods

http://msdn.microsoft.com/en-us/library/bb383977.aspx

Extension methods enable you to "add" methods to existing types without creating a new derived type.

Extension methods are a special kind of static method, but they are called as if they were instance methods on the extended type.

Sam: When you look at the definition of the extended method, you will see the first parameter to be in the format of "this IMyInterface<T> var". This is the norm. From the client side, when you call the method, you ignore this first parameter (Intellisense in VS2008 will automatically and conveneiently hide this first parameter for you so that the method looks like any other instance method on a class).

In general, you will probably be calling extension methods far more often than implementing your own. A general guideline is that that you implement extension methods sparingly and only when you have to. Use inheritance instead. Sam: so why is Juval Lowy's extension methods (in his book "Programming with WCF") found within "public static class CollectionExtensions" of his ServiceModelEx library a good thing to use?

For client code written in C# and Visual Basic, there is no apparent difference between calling an extension method and the methods that are actually defined in a type.

You can use these methods to extend a class or interface, but not to override them. An extension method with the same name and signature as an interface or class method will never be called. At compile time, extension methods always have lower priority than instance methods defined in the type itself. In other words, if a type has a method named Process(int i), and you have an extension method with the same signature, the compiler will always bind to the instance method. When the compiler encounters a method invocation, it first looks for a match in the type's instance methods. If no match is found, it will search for any extension methods that are defined for the type, and bind to the first extension method that it finds.



Some available extension methods
The most common extension methods are LINQ standard query operators that add query functionality to IEnumerable collections and IEnumerable generic collections. So, by simply using System.Linq, you should see a whole lot of instance methods like OrderBy, Average on types like List, List, string[] etc.

Example: "OrderBy" extended method on any class that implements IEnumerable<T>

In System.Linq ns, OrderBy is overloaded and defined as

(1) public static IOrderedEnumerable<TSource> OrderBy<TSource, TKey>(
this IEnumerable<TSource&gt; source,
Func<TSource, TKey> keySelector)

(2) public static IOrderedEnumerable<TSource> OrderBy<TSource, TKey>(
this IEnumerable<TSource&gt; source,
Func<TSource, TKey> keySelector,
IComparer<TKey>comparer)

Also in System.Linq, IOrderedEnumerable is defined as

public interface IOrderedEnumerable<TElement> : IEnumerable<TElement>, IEnumerable

Using (1), from a client's perspective (where you ignore the 1st param), see how the method takes a delegate Func<TSource, TKey> variable that points to a method (could be anonymous or a lambda expression), quite possibly on the client.

Example showing various equivalent ways of calling the "OrderBy" method where its delegate variable parameter points back to a client method.

Assume you have a simple class Pet with 2 public members Name and Age.

Pet[] pets =
{
new Pet { Name="Barley", Age=8 },
new Pet { Name="Boots", Age=4 },
new Pet { Name="Whiskers", Age=1 }

};

//(1a)Explicitly defining the delegate variable Func<TSource, TKey> and pointing it to an explicit method

Func<Pet, int> del = MyFunctionMatchingtheDelegate;
IEnumerable<Pet> query = pets.OrderBy(del);

private static int MyFunctionMatchingtheDelegate(Pet p)
{
return p.Age;
}


//(1b)Implicitly using the delegate variable Func<TSource, TKey> and pointing it to an explicit method

IEnumerable<Pet> query = pets.OrderBy<Pet,int>(MyFunctionMatchingtheDelegate);



//(2a)Explicitly defining the delegate variable Func<TSource, TKey> and pointing it to an anonymous method
Func<Pet, int> del = delegate(Pet p)
{
return p.Age;
};
IEnumerable<Pet> query = pets.OrderBy(del);


//(2b)Implicitly using the delegate variable Func<TSource, TKey> and pointing it to an anonymous method
IEnumerable<Pet> query = pets.OrderBy<Pet, int>
(
delegate(Pet p)
{
return p.Age;
}
);


//(3a)Explicitly defining the delegate variable Func<TSource, TKey> and pointing it to a lambda expression
Func<Pet, int> del = pet => pet.Age;
IEnumerable<Pet> query = pets.OrderBy(del);


//(3b)Implicitly using the delegate variable Func<TSource, TKey> and pointing it to a lambda expression
IEnumerable<Pet> query = pets.OrderBy(pet => pet.Age);

In any case, the actual function (whether lambda expression, anonymous method or explicit method) is not executed until the foreach iterator is first accessed as follows.

foreach (Pet pet in query)
{
Console.WriteLine("{0} - {1}", pet.Name, pet.Age);
}


Notes
In each of the above examples, note we are using the IEnumerable<Pet> iterator even though the definition of OrderBy clearly implies IOrderedEnumerable<Pet>. I'm pretty sure you can use the IOrderedEnumerable in each of the above cases. What are the benefits of using IOrderedEnumerable over IEnumerable, if any?

The other overloaded OrderBy takes an an extra parameter IComparer. Create code examples for that.

Juval Lowy's numerous extension methods apply to IEnumerable<T> and to IEnumerable. Most of his methods also take .NET provided generic delegates like Converter, Action etc. as variables, thus allowing developers to create their own methods the delegates point to.


To Implement Your Own
http://msdn.microsoft.com/en-us/library/bb311042.aspx
(1) It is generally a good idea to extend an interface, not the class.
(2) Understand that if the method you are trying to add already has a matching instance method signature on a class, your extended method will never execute.
[This means, if the type changes and adds a new set of instance methods, one of which matches the extended method you already implemented, then all of a sudden, your extended method will never execute]
(3) Example:
namespace IT.ClientSystems.Extensions
{
using System;
using IT.ClientSystems.Interfaces;

// Define extension methods for any type that implements IMyInterface.
public static class Extension
{
public static void MethodA(this IMyInterface myInterface, int i)
{
Console.WriteLine("Extension.MethodA(this IMyInterface myInterface, int i)");
}

ClientSide: Assume ClassA implements IMyInterface and does not have an instance method called MethodA that takes an integer parameter.

using IT.ClientSystems.Extensions;
ClassA a = new ClassA();
a.MethodA(5);

(4) An advanced example would be for your extended method to take a generic delegate as one of the parameters like "OrderBy" method shown above. Many of System.Linq extension methods and those from Juval's personal library use generic delegate parameters. Common ones are Converter, Action, Predicate, Func etc.