Tuesday, December 30, 2014

Books on Finance, investing, economics



The Little Book That Beats the Market by Joel Green- blatt.3

Swensen’s most recent book, Unconven-tional Success: A Fundamental Approach to Personal Investment.

Seeing What Others Don't: The Remarkable Ways We Gain Insights

“Mastermind: How to Think Like Sherlock Holmes,” by Maria Konnikova
“A Few Lessons from Sherlock Holmes,” by Peter Bevelin.

Steven Penman’s excellent book “Accounting for Value” 

Pat Dorsey in his wonderful book, “The Little Book that Builds Wealth” writes:

patto: 7408798108

“Extraordinary Popular Delusions and the Madness of Crowds” by Charles 

A Few Lessons from Sherlock Holmes Paperback – Import, 16 Sep 2013
by Peter Bevelin (Author)
A Few Lessons from Sherlock Holmes is a book for those who want to improve their thinking. It is a practical and enjoyable book that tells in a short-easy-to-read way about what we all can learn from Sherlock Holmes. Peter Bevelin has distilled Arthur Conan Doyle's Sherlock Holmes into bite-sized principles and key quotes. This book will appeal to both Sherlock fans as well as those who want to think better. It contains useful and timeless methods and questions applicable to a variety of important issues in life and business. We could all benefit from 'A few lessons from Sherlock Holmes'.

COURTESY :BUSINESS INSIDER

When Warren Buffett started his investing career, he would read 600, 750, or 1,000 pages a day.Even now, he still spends about 80% of his day reading."Look, my job is essentially just corralling more and more and more facts and information, and occasionally seeing whether that leads to some action," he once said in an interview."We don't read other people's opinions, “he says. "We want to get the facts, and then think."To help you get into the mind of the billionaire investor, we've rounded up his book recommendations over 20 years of interviews and shareholder letters.


1."THE INTELLIGENT INVESTOR " by Benjamin Graham

When Buffett was 19 years old, he picked up a copy of legendary Wall Streeter Benjamin Graham's "Intelligent Investor."It was the one of the luckiest moments of his life, he said, since it gave him the intellectual framework for investing."To invest successfully over a lifetime does not require a stratospheric IQ, unusual business insights, or inside information," Buffett said. "What's needed is a sound intellectual framework for making decisions and the ability to keep emotions from corroding that framework. This book precisely and clearly prescribes the proper framework. You must provide the emotional discipline."

2."SECURITY ANALYSIS" by Benjamin Graham

Another groundbreaking work of Graham's, Buffett said that "Security Analysis" has given him "a road map for investing that I have now been following for 57 years."
The book's core insight: If you do a thorough enough of analysis, you can figure out the value of a company — and if the market knows the same.Buffett has said that Graham was the second most influential figure in his life, only after his father."Ben was this incredible teacher, I mean he was a natural," he said.

3."COMMON STOCKS AND UNCOMMON PROFITS" by Philip Fisher

While investor Philip Fisher — who specialized in investing in innovative companies — didn't shape Buffett in quite the same way as Graham did, he still holds him in the highest regard.
"I am an eager reader of whatever Phil has to say, and I recommend him to you," Buffett said.In "Common Stocks and Uncommon Profits," Fisher emphasizes that fixating on financial statements isn't enough — you also need to evaluate a company's management.

4."STRESS TEST : REFLECTIONS ON FINANCIAL CRISES" by Tim Geithner
Buffett says that the former Secretary of the Treasury's book about the financial crisis is a must-read for any manager.
Lots of books have been written about how to manage an organization through tough times. Almost none are firsthand accounts of steering a wing of government through economic catastrophe.
"This wasn't just a little problem on the fringes of the U.S. mortgage market," Geithner writes. "I had a sick feeling in my stomach. I knew what financial crises felt like, and they felt like this."
5. "THE ESSAYS OF WARREN BUFFETT"

If you want to get to know the way Buffett thinks, go straight to the Sage himself.

In this collection, he keeps it very real — in his signature folksy-intellectual fashion.
"What could be more advantageous in an intellectual contest — whether it be chess, bridge, or stock selection —than to have opponents who have been taught that thinking is a waste of energy?" he asks.

6. "JACK :STRAIGHT FROM THE GUT " by Jack Welch

In his 2001 shareholder letter, Buffett gleefully endorses "Jack: Straight From The Gut," a business memoir of longtime GE exec Jack Welch, who Buffett describes as "smart, energetic, hands-on."In commenting on the book, BloombergBusinessweek wrote that "Welch has had such an impact on modern business that a tour of his personal history offers all managers valuable lessons."
Buffett's advice: "Get a copy!"

7. "THE OUTSIDERS" by William Thorndike, Jr.

In his 2012 shareholder letter Buffett praises "Outsiders" as "an outstanding book about CEOs who excelled at capital allocation."Berkshire Hathaway plays a major role in the book. One chapter is on director Tom Murphy, who Buffett says is "overall the best business manager I’ve ever met."The book — which finds patterns of success from execs at the Washington Post, Ralston Purina, and others — has been praised as "one of the most important business books in America" by Forbes.

8."THE CLASH OF THE CULTURES " by John Bogle

 Bogle's "The Clash of the Cultures" is another recommendation from the 2012 shareholder letter.In it, Bogle — creator of the index fund and founder of the Vanguard Group, now managing $2.0 trillion in assets — argues that long-term investing has been crowded out by short-term speculation.But the book isn't all argument. It finishes with practical tips, like:
a)      Remember reversion to the mean. What's hot today isn't likely to be hot tomorrow. The stock market reverts to fundamental returns over the long run. Don't follow the herd.
b)      Time is your friend, impulse is your enemy. Take advantage of compound interest and don't be captivated by the siren song of the market. That only seduces you into buying after stocks have soared and selling after they plunge.

9. "BUSINESS ADVENTURES :TWELVE CLASSIC TALES FROM THE WORLD OF WALL   STREET" by John BrooksBogle's "


The Clash of the Cultures" is another recommendation from the 2012 shareholder letter.

Back in 1991, Bill Gates asked Buffett what his favorite book was.To reply, Buffett sent the Microsoft founder his personal copy of "Business Adventures," a collection of New Yorker stories by John Brooks.Gates says that the book serves as a reminder that the principles for building a winning business stay constant. He writes:  For one thing, there's an essential human factor in every business endeavor. It doesn't matter if you have a perfect product, production plan and marketing pitch; you'll still need the right people to lead and implement those plans.The book has become a media darling as of late; Slate wrote that it's "catnip for billionaires.”

You are here: Home / Interviews / Value Investing, the Sanjay Bakshi Way – Part 4
Value Investing, the Sanjay Bakshi Way – Part 4
POSTED ON AUGUST 15, 2012 // 37 COMMENTS


  296

Here’s the final part of my interview of Prof. Sanjay Bakshi. You can read the first three parts here – Part 1 | Part 2 | Part 3
Safal Niveshak: Can you draw down a series of steps and checklists – the process – you use to identify stocks to buy using the value investing route?
Prof. Bakshi: You need different checklists for different styles of investing.
If you are analysing a bankruptcy situation, the checklist you will use will obviously be different from the one when you are buying into a business on the basis of the skills of one person, like Ajay Piramal.
Buying into Piramal Healthcare was essentially a bet on the man’s ability to allocate capital. So to evaluate how likely he will do that in the future, your checklist must first examine how well he allocated capital in the past and also how did he treat his minority investors in the past.
Once you’ve done the past evaluation and formed a positive view, the next question that you have to answer on your checklist is: How likely is it that Ajay Piramal will get opportunities to allocate capital well in the future within his circle of competence?
You also have to think about how the existing businesses the company owns may do in the future and as you know one of the businesses – drug discovery – is one that possesses the possibility of delivering one or more positive black swans.
So your checklist has to incorporate how to deal with the uncertainty.
Obviously, the due diligence required in such an investment operation is very different than one required in evaluating the economics of a tender offer.
When there’s an open offer at Rs 100 and the stock is selling at Rs 95, you can make Rs 5 in a two month period, then the process revolves around whether they (the company) are going to honour it or not, whether the offer will get delayed or not, and what are the risks involved in the transaction.
In such situations, you really don’t have to worry about the quality of the management, the earnings, P/E multiples etc. Those things become completely irrelevant.
So you have to think about the process very carefully, and every style, every single opportunity will have its own checklist.
Safal Niveshak: But what could be a checklist for a small investor who is focusing on a simple Buffett kind of a strategy – buying good companies with durable moats?
Prof. Bakshi: The single most important thing here is that if you buy great companies, then you can go wrong only when you overpay for them.
If it’s going to remain a great company, you are unlikely to have a permanent loss of capital. Even in Infosys, people who got in it in 2000 have not lost money. They have made a little money, but much less than what they would have made if they had been smarter.
It’s hard to lose money in a great company, run by ethical managers, except when you have grossly overpaid for it. Even if you have moderately overpaid for it, it is not going to kill you in the long run.
People get killed by buying mediocre or shady companies at high prices. They don’t get killed by buying good companies at good prices.
The checklist for a small investor who focuses on buying good companies with durable moats would revolve around three factors – business, people, price.
For evaluating business, I highly recommend reading Pat Dorsey’s book – “The Little Book that Builds Wealth”.
It’s such a simple, common-sensical book that investors can learn from. It will help them in spotting moats. It will also help them in keeping away from thousands of companies that have no moats. So, for “business” factor checklist, read that book.
For “people factor”, you need a checklist for evaluating managements. Perhaps, we can work on this together for the benefit of your readers.
It would be a simple checklist covering skills (operating as well as capital allocation) and ethical conduct.
There are lot of red flags one should look for:
  • You don’t want to see management paying itself exorbitant salaries and perks.
  • You don’t want to see promoters merging their private companies into the company whose stock you are evaluating.
  • You don’t want them to appoint their relatives who don’t have adequate qualifications.
  • You don’t want them to have a lot of related-party transactions with their own privately held companies.
  • You don’t want to be involved with companies where the promoters trade in and out of the stock.
  • You don’t want to be get involved with promotional managements.
Essentially, you want to keep away from shady promoters.
For “price factor,” a simple rule can be used. You don’t have to make it complicated. A rule like never paying a more than a P/E multiple of 13 (where “E” is expected minimum future earnings) can be used. Since the stock has already passed the tests on “business factors” and “people factors,” having a simple rule on the “price factor” makes a lot of sense.
Safal Niveshak: At low valuations, the mediocre companies are anyways value traps, right?
Prof. Bakshi: Absolutely! So the checklist that I would have for a small investor would also have a question – Is this the right time to buy stocks?
The simple rule that I can give is that the Indian stocks have hovered from 11x P/E multiple on the lower end for the NSE-Nifty to a 27x on the higher side.

Data Source: Ace Equity

So obviously if you are buying stocks when the P/E multiples are 23, 24 or beyond, you should be a bit careful. You shouldn’t put a lot of money in stocks.

But if the stock that you like a lot is available to you in an environment where the aggregate multiples are 12-14, or even right now, which is about 15, then it’s a good environment to buy into long term stocks.
So think a little bit about timing. You don’t want to buy great companies at fabulous prices during bull runs. You want to buy them in bear markets, and then you have to exercise patience.
Safal Niveshak: Yes, I have a kind of a checklist that I use with my stock analysis. It’s like a logic chart that helps you go through a checklist of what you want to see in a company and what you want to avoid, including a behaviour checklist. I’ll share it with you.
Prof. Bakshi: Yes, I’ve seen it. It’s very good. It would also be great if you had a checklist on corporate governance, including things like what auditors are saying about the company, how frequently auditors are being changed, what is happening in the insider activity, are they trading in and out of the shares very frequently, or are they not doing that and they are building a stake in the company and are there for the long term.
Safal Niveshak: Thanks for the idea! My next question – If you were to go back to the start of your career as an investor, would you like to change something – add or delete?
Prof. Bakshi: I’ll add patience.
One of the things about investing is that when you are young, you are much more impatient than when you get older. Maybe it’s to do with age, maybe it’s to do with experience, or maybe it’s to do with learning the hard way.
So I would add patience. I used to be much more active earlier. I used to be hyper-active – jumping in and out!
I realized that it was a mistake. So that is one thing I would definitely add – the value of patience.
Recall the point I made earlier about the role of long term compounding at a given rate which will give you much better results than the same rate of compounding achieved by jumping in and out of the market.
The second thing I would add is this – I would think very carefully about the idea of value traps.
Again, this is something I’ve learned the hard way and I am still learning it, by the way – that you end up buying into things that you think are cheap, but they will remain cheap for very good reasons.
Graham used to say that in the short-run the market is a voting machine but in the long run it’s a weighing machine.
Well, some people take that metaphor too far (I certainly did) and forget that it’s not a law of physics for every cheap stock to eventually rise to its intrinsic value.
Value investors should recognise that out of a universe of 6,000 stocks, a significant number would be “value stocks” but a very significant proportion of “value stocks” are “value traps” and it’s important to avoid those and focus on the rest.
The third thing I wish I had added earlier is this – Paying up for quality.
These three things even Buffett learned over time. He was much less patient than he is now – he bought Berkshire Hathaway which he later confessed to be a value trap and he extricated himself from a bad situation by taking out the cash flow from the shitty textile business and putting it into cash generating businesses.
He also learned, over time, to pay up for quality.
I think when people think in terms of cost, they don’t think a lot about “opportunity cost.” For most people out-of-pocket costs loom much larger than opportunity costs, and since foregone opportunities are not out-of-pocket costs, people under-weigh them.
Not paying up for quality carries huge opportunity costs. These costs won’t show up in your P&L because a P&L does not reflect what you could have done but did not do.
The errors of omission are sometimes far more than the errors of commission. In the long run, opportunity costs really matter in the long run.
You must not say – “Well, my P&L will never show the opportunity losses, therefore they don’t matter.”
Safal Niveshak: You talked about holding on to a stock if you had bought it on favourable terms. The question is – How long should one wait for the value to be realised?
Prof. Bakshi: Graham had a very simple rule of dealing with value traps.
He basically said, “I’m doing statistical bargains. I don’t know which of these companies are going to perform, but I will limit the underperformers.”
So he kept a very simple rule. He would sell a stock if it went up by 50%, or 3 years, whichever happened first.
That was a very simple rule which largely kept him out of value traps.
But, this kind of a rule applies only to Graham & Dodd statistical bargains.
On the other extreme is the Philip Fisher Rule.
In his book, he writes, “If the job has been correctly done, then the time to sell a stock is almost never.”
Warren Buffett grabbed this rule and he dropped the Graham rule. Of course he did that after he changed his investing style as well.
Think of the following combination:
  • A high return on capital with the ability to reinvest that capital at a high rate of return
  • Those returns are sustainable because there is a moat – either in the form of a low cost advantage or in the form of a pricing power
  • You can continue to grow without requiring new outside capital (so there is not dilution of equity)
  • Balance sheet is extremely conservative (no debt and plenty of surplus cash )
  • Management that is both skilful – both in operations and in capital allocation – and honest
  • The entry price at which you had bought this share is not at the frothy end of the bubble market, and the multiple you had paid for this company is not excessive in relation to its own history.
If you get this combination, you’ll do very well over the long term, which is more than a decade. I have yet to encounter an exception to this rule.
Maybe there could be 4-5 years when the stock doesn’t do anything. But I don’t know an exception to this rule when you have all these attributes and you didn’t do well in the truly long run, which in my view is about a decade.
So that’s the point here. Think in terms of decades. Don’t think in terms of 3-4 years.
Indian stocks, from September 2007 till July 2012 have done nothing. So does that mean that Indian stocks are dead? Does that mean this is death of equities? I don’t think so!
I think we are poised for a very long bull run which will start, I don’t know when, but I think it’s going to start. And I think money will be made by the patient investor. But there will be periods of underperformance.
You are really looking for businesses that are going to keep on doing well even during adverse economic conditions, and stick with them.
So when it comes to the idea of selling, I wouldn’t want to sell them just because they didn’t do anything for the next 2, 3, or 4 years. I won’t apply the Graham rule to such stocks.
It’s very rare to find such situations. Think about Nestle. The guy who found it 20 years ago or 10 years ago, doesn’t need to do anything else in his life. For him, to switch out of that stock simply because it’s moved up a lot, or not gone anywhere for 3 years – either of those two decisions – would have been foolish.
Thus doing anything in that stock would have been a mistake, other than just buying and sitting on it. Some stocks are of that nature and true wealth is created by being in those stocks and remaining there – not by jumping in and out.
Safal Niveshak: When you came back to India in 1994 after finishing your course at LSE, you believed in India growth story and that you can apply Buffett principles here. What are your views on India growth story now?
Prof. Bakshi: I still believe in the India growth story. I believe that India will create more wealth in the next 20 years than it has in the last 30 years and the pace of change is only going to accelerate. Even though things don’t look good right now, things didn’t look good in 1991 also.
Safal Niveshak: Maybe that’s also because of the “recency effect”. We are seeing and hearing bad news all around us!
Prof. Bakshi: Absolutely! I have no hesitation in saying that the entrepreneurial spirit of India is alive and kicking.
A new wave of entrepreneurs will come, and replace the older ones. And the next wave of optimism is going to be bigger than the previous one.
And this is going to keep on happening. This is cyclical, but living standards will continue to grow and people are going to get richer and they are going to continue to spend and consume. Companies are going to benefit from this process for a long-long time. There is no stopping India as far as I can think.
As far as applying Buffett principles over here is concerned, I think those principles – whether they came from Buffett or Philip Fisher or Ben Graham or Munger – they make a lot of sense.
These are universal principles. But you have to adapt them to local conditions. You cannot blindly copy-paste!
I’ll give you an example. Graham used to invest in “net-nets”. This was at a time when the working capital of a company was a very important component of value. Today you live in a world where the best companies have negative working capital.
So the importance of working capital in the valuation of a company has actually gone down. This is point number one.
Two, in early situations, when companies sold below working capital, they could be liquidated for working capital at least, plus some money for fixed assets, and you could actually get liquidation value which was more than the market cap. Therefore there were good reasons to buy into those situations.
The probability of liquidation was higher then, than it is right now. American companies had diffused ownership. Indian’s companies are mostly controlled by a family of promoters who own stakes large enough to prevent any liquidation.
So a prosperous company selling below liquidation value is not going to be liquidated. And a troubled company doesn’t have much of a liquidation value for stockholders.
Think Kingfisher here. And most troubled companies have no working capital left anyway.
So, relying on working capital as a source of margin of safety is a very dangerous idea in the current environment where companies will not get liquidated.
The idea of buying into net-nets worked in the US for a while, but if you blindly copy-paste it here – a completely different market because ownership is concentrated – then it’s not going to work.
Safal Niveshak: Can you describe some of your most notable investment mistakes and what did you learn from them?
Prof. Bakshi: I will talk about three classes of mistakes.
First one is over-confidence, which results in over-sizing.
Buffett influenced me a lot in the early years of my career, a lot more than other people. I had only one role model then, while now I have many more.
He basically talked about focused investing. He talked about “betting the bank” or “backing up the truck” so to speak – putting a lot of money behind the ideas in which you have the maximum conviction.
In early years, I made this mistake. Even up to recently I made this mistake of buying into situations where I had a lot of confidence (which in hindsight turned out to be overconfidence), which resulted in over-sizing of the bet, and which was a bad idea that had bad consequences.
You have to think very carefully about position-sizing. No matter how good you feel about an idea, there has to be a cap. And that cap should not be 40-50%.
No matter how confident you are, you shouldn’t have more than maybe 10% in a stock. You should have at least 10 names in a portfolio – maybe more, but 10 is the minimum that you need to have.
I know there are people who will disagree with me completely, but I am giving you my thought process. I am giving you an insurance policy against over-confidence.
The second mistake that I made is again to do with something I mentioned earlier – “opportunity loss” which occurred not only by mistakes of omission but also by selling too early.
The sell decision is a very difficult decision, much more difficult than the buy decision.
A stock you own goes up 100% and you start thinking, “Oh my God, it’s already gone up so much! How much more can it go?” You get fearful of losing gains already made and you sell it and then it goes up by another 300%!
Safal Niveshak: Indeed! Anyways, can you talk about 5 reasons why you would sell a stock?
Prof. Bakshi: Single most important reason to sell a stock is that you made a mistake. It doesn’t matter what it cost you.
In fact, you should be blind to cost when determining whether you made a mistake or not. If the reason why you bought a stock no longer exists, sell it.
Most people find this very hard to do. They get emotionally attached to their earlier stock picks – even when they are obviously wrong. Or they start thinking, “It’s below my cost, and I can’t sell it because if I do, I’ll have a loss.”
That kind of thinking is foolish. The loss happened the day the wrong stock was bought, not on the day it was sold. On the sale date, economic loss became accounting loss, that’s all.
So, not selling something simply because it is below cost is a foolish way of thinking. You see, going wrong in a buy decision is ok. No matter how careful you are, you’re going to make mistakes. But holding on to something rotten – simply because its below cost or in the hope that someday it will go up – that kind of a mistake is inexcusable.
Making mistakes is ok, perpetuating them is not.
The second reason to sell is when it’s gone to fair value. So there is no margin of safety left.
The value was 100, you bought it at 30, it’s gone to 90-95, nobody is sure what the value is but the price is absolutely sure, and there is very little margin of safety. So you sell it.
Notice, I said “it’s gone to fair value” and not that “its price has increased to fair value”.
For a stock to no longer be a bargain, it’s not necessary for price to rise to value. It can happen the other way as well – Value can fall to a point where there is no margin of safety left.
And value falls for all sorts of reasons – there could be an unexpected impairment arising out of a bad capital allocation decision, a natural calamity which destroys earning power, an adverse and unexpected change in regulatory environment, etc.
So, you have to keep in mind that it’s not necessary for price to rise to meet value. Value can come down to say hello to price as well.
Reason number three to sell – selling an 80-cent dollar to buy a 30-cent dollar. Of course you will do this only when you don’t have any investible cash left.
Reason number four to sell – A stock has risen so much that it has become just too big a part of the portfolio that it is giving you sleepless nights.
Sell it down to the sleeping point. It’s not just about making money, you see. It’s also about living a stress-free life.
What’s the point of becoming so rich that you’re not unable to even sleep?
Reason number five to sell – Pare exposure to equities in a bubble market.
This is a top-down decision. Everyone loves their stocks in a bubble market because they are getting rich and they don’t want to leave the party. But the party will end eventually as all bubbles burst.
Doesn’t it make sense to pare exposure to equities despite the temptation to stay invested? I think there is. And if you have to sell, then you will have to deal will reducing exposure to your much-loved ideas. Hard to do, but necessary!
One way to deal with it is to think along the following lines – “I’ve to let you go right now, or at least a part of what I own of you, but I know you will come back to me, and then maybe we will live happily ever after. But for now, it’s bye-bye!”
In other words, follow Gordon Gekko’s modified advice – “Don’t get [too] emotional.”
Anyways, coming to the third mistake I’ve made in investing: Not paying up for quality.
Again, the results of such a mistake will never show up in the P&L. They will show up in the opportunity P&L.
So in my mind map, I have this opportunity P&L. It’s fascinating to think about this for a minute. It relates to the idea of circle of competence.
Buffett talked about circle of competence – things you can do well – this is your opportunity set. It’s okay for things that are outside your circle of competence for you to ignore them. It doesn’t matter if somebody else is doing very well in venture cap, private equity, or something that you have no clue about. So those are the things that are outside your circle of competence and you don’t have to worry about them at all.
But things that you could have done, which are within your circle of competence, but you did not do, they end up on your opportunity P&L.
The fact that I did not buy the 100-bagger like Google will never enter into even my opportunity P&L. This is because I could never have done it. I don’t understand that thing.
But the fact that I missed out on an opportunity that became a multi-bagger that was within my circle of competence because I understood it and because it was a very-high quality situation, and I didn’t buy it because I thought it will drop another 5% and then I’ll buy it – that’s a very costly mistake that appears on the opportunity P&L.
You need to fix not just mistakes of commission, but also mistakes of omission. You just have to learn to change your behaviour in order to reduce the losses that figure on your opportunity P&L.
Safal Niveshak: Are there any risks inherent to value investing except falling into value traps?
Prof. Bakshi: First, if you use the wrong kind of money for value investing, then you will fail. And the wrong kind of money is what I call as “impatient capital.”
Borrowed money is impatient capital. Interest keeps on compounding and markets don’t always co-operate, so you mustn’t borrow money to practice value investing, most of the time. There are exceptions but they are very few.
Another form of impatient capital is money taken from clients for value investing but money which can be withdrawn by the clients at a very short notice. That kind of money is not suited to value investing. Value investing needs patient capital.
Second, if you don’t have the right temperament, you will fail.
It doesn’t matter that you understand the idea of value, and you know there is the margin of safety. If you don’t have the right temperament – for example, if you get influenced by people in a party who are investing in the latest hot real estate fund and you feel that you have missed out on the action – all your friends are making money and you look like a fool and your temperament doesn’t want you to look like a fool – then value investing is not for you.
If you’re a party person, or you love being popular, or you love a lot of action, then don’t try value investing. It’s not for you. Do something else.
Typical value investors are loners. They hate crowds. They are independent thinkers who don’t get influenced by what the crowd is doing. They love doing unconventional and unpopular things. They are also extremely patient.
Safal Niveshak: How do you deal with a situation when you fall into a value trap? Please help with 1-2 case studies from your personal experience.
Prof. Bakshi: The first thing to do is to recognize it. Many people find this hard to do. They go into denial.
If something you bought has gone down 50%, something is wrong either with the market, or maybe something is wrong with you. And it’s not a good idea to assume that the market is wrong. It’s often wrong, no doubt, but not always.
Look at the fate of folks who bought into DLF, Unitech, Lanco, Rcom, and Suzlon in Jan 2008 and who are still holding those stocks. Here are the stock price returns from 1 Jan 2008 till date:
  • Lanco: -85%
  • DLF: -80%
  • Unitech: -95%
  • Suzlon: -95%
  • RCom: -93%
People, who held on to these names since 1 Jan 2008 – at some point, they went into denial. They kept on inventing new reasons to own these stocks even though the original ones were no longer valid.
People need a way to de-bias themselves and one good way to do that is to mentally liquidate the portfolio and turn it into cash and then, for each security, ask yourself, “Knowing what I know now, would I buy this stock?”
Often the honest answer would be a most certain “no”. Then the next question you have to face is – “Then why do I own it now?”
You have to deliberately expose yourself to cognitive dissonance and then you have to learn to promptly resolve it.
I used the above names as examples even though none of them were value stocks. But the same rules apply to value stocks, which turn out to be value traps. You have to recognise it which will expose you to cognitive dissonance, and then you have to rationally resolve the dissonance. And there is only now way to resolve it rationally – swallow your pride and sell it.
I’m reminded of something that someone sent to me recently titled – “Ten Rules for Being Human”.
Of these, as investors, there are four that really stand out.
Rule Two – You will be presented with lessons.
You are enrolled in a full-time informal school called “life”. Each day in this school you will have the opportunity to learn lessons. You may like the lessons or hate them, but you have designed them as part of your curriculum.
Rule Three – There are no mistakes, only lessons.
Growth is a process of experimentation, a series of trials, errors and occasional victories. The failed experiments are as much as a part of the process as the experiments that work.
Rule Four – A lesson is repeated until learned.
Lessons will be repeated to you in various forms until you have learned them. When you have learned them, you can go on to the next lesson.
Rule Five – Learning does not end.
There is no part of life that does not contain lessons. If you are alive, there are lessons to be learned.
Safal Niveshak: Certainly! As they say that the romance of life is not in “knowledge”, but in “knowing”. So you have to keep learning.
Prof. Bakshi: That’s true Vishal.
Safal Niveshak: Finally, what’s your recommendation for books that an investor must read?
Prof. Bakshi: Everybody will talk about the classics. But the single most important source that I talk about is the letters of Warren Buffett.
One of the things about valuation is that people don’t put a lot of value on things that come to you for free. And because these letters are free on a website, people say, “Oh, they’re there for anybody and they are free, so they aren’t worth much.”
That’s completely the wrong way of thinking about it!
Those letters are the most valuable source for learning about finance and investing in the whole world. And unfortunately people don’t treat them as such simply because they are free.
The other thing is that you have to read these letters by downloading them, taking a printout, and spending 2-3 days on one letter. You cannot skim through them. You have to read each one of them in a slow manner to actually absorb and make notes of what is important and connect various these across letters. You have to really do that!
Then, of course, there are all these classic books like:
  • The Intelligent Investor by Ben Graham
  • Extraordinary Popular Delusions and the Madness of Crowds by Charles Mackay
  • The Short History of Financial Euphoria by John Kenneth Galbraith
  • Security Analysis by Graham & Dodd
  • Margin of Safety by Seth Klarman
  • The Black Swan by Nassim Taleb
  • Influence by Robert Cialdini
So those are the classics. But I want to talk about four recent books that I liked a lot.
One of them is “Thinking fast and Slow” by Daniel Kahneman, the Nobel laureate who’s created the field of behavioural economics.
Another really good book that I read last year was “One Small Step Can Change Your Life: The Kaizen Way”. It’s about making small incremental changes in your life, like what Charlie Munger talks about the “slow contrast effect” or the “boiling frog syndrome”.
Slow changes will get unnoticed, but if you have to change a habit, do it gradually, very slowly. And it works. It worked for me.
There are two other recent books I liked. One of them I mentioned earlier: “The Little Book that Builds Wealth” by Pat Dorsey.
Then there’s a book that came last year, and it’s exceptionally good for those who have accounting knowledge. It’s called “Accounting for Value” by Stephen Penman.
He’s a professor at University of Columbia, and one who has related modern DCF with value investing styles of Graham & Dodd and Warren Buffett. He teaches you how to think about valuation, without thinking about beta, or capital asset pricing model. It’s a very good book.
Saving Capitalism from the Capitalists by Raghuram Rajan and Luigi Zingales: I had read this book when it was first published in 2003. At that point of time I was basically trying to figure out what to do with my life, having finished an MBA in information systems in 2002 and at the same time having realized that the MBA degree was one big con job. 

In 2014, the book was published again with a new afterword. I read it again and appreciated the book much more than I had done in 2003. The book is a great read for anyone who believes in the idea of free markets. It tells you loud and clear that the incumbent capitalists are the greatest enemies of the free market. The book also helped me understand why so many big businesses in India manage to default on their bank loans without the industrialists having to face the consequences of the same. 

After the Music Stopped by Alan S Blinder: This book was published in 2013, but I happened to read it only this year. The best books on historical events are written many years after the event has happened. Take the case of what I think is the best book on the Great Depression- The Great Crash 1929, written by John Kenneth Galbraith. The book was first published in the mid 1950s almost quarter of a century after the Depression started. One possible explanation for this is the fact that writing many years later, the author can leave out all the noise and concentrate on the most important issues. 

Over the last six years many books have been written on the financial crisis, but After the Music Stopped, in my opinion is perhaps the best book on it. It summarises the economic, the political as well as the legal angles of the financial crisis very well. If you are looking for a ready reckoner on the financial crisis, this has to be your go to book. 

Capital in the Twenty-First Century by Thomas Piketty: This was by far the bestselling title in economics during the course of this year, having been the number one book on Amazon.com for a while. It is very rare for an economics book running into 700 pages to be number one on Amazon. 

In this book the core argument offered by Piketty, who is a French economist, is that capitalism has led to greater inequality among people over the years. Piketty offers a lot of data from the developed countries to make his point. The book did not go down well with the American economists, and after it appeared many of them tried to discredit it by trying to find mistakes in the data and methodology used by Piketty. Who is right and who is wrong is too long a debate to get into here. Nevertheless, Piketty's book remains a must read for the fantastically lucid way in which its written and the several original ideas that it offers. 

The Dollar Trap by Eswar S. Prasad: The United States is in a huge financial mess. Nevertheless, dollar remains the go to currency of the world at large. Whenever there is a whiff of a crisis anywhere in the world, money is pulled out and moves to the dollar. Ironically, even when the rating agency Standard and Poor's cut the rating of the debt issued by the United States government from AAA to AA+, money moved into the US dollar. Prasad explains this "exorbitant privilege" of the dollar and the reasons behind it. 

While the US may not be in a great financial shape, but the world at large still has faith in the dollar. Prasad summarizes the situation well when he says: "It is possible that we are on a sandpile that is just a few grains away from collapse. The dollar trap might one day end in a dollar crash. For all its logical allure, however, this scenario is not easy to lay out in a convincing way." 

The book is a great read for anyone trying to understand one of the most fundamental disconnects of the times that we live in. 

Flashboys by Michael Lewis: No one quite writes about finance like the way Lewis does. From his first bookLiars Poker to the latest Flashboys, each one of his books on Wall Street and its ways has been a bestseller. One reason for the same is the fact that Lewis started as a Wall Street insider in the investment bank Salomon Brothers (which has since gone bust) and has managed to maintain his contacts since then. 

Flashboys is essentially a story of the people and systems that make up algorithmic trading that has taken Wall Street by storm. A majority of the trades on Wall Street are not driven by humans any more. They are driven by computers with a lot of processing power. And that is the fascinating story of Flashboys . If you are the kind who likes reading thrillers over weekends, this is just the right book for you. 

Business Adventures by John Brooks: I first discovered Brooks in the process of writing and researching my books. Someone suggested that I should be reading Brooks' version of the Great Depression called Once in Golconda: A True Drama of Wall Street 1920-1938. The book was a fantastic read and made me realize that Wall Street had a Michael Lewis even before the real Michael Lewis appeared on the scene. 

Early this year, Bill Gates wrote a blog on one of Brooks' other books called Business Adventures. He called it the best business book that he and Warren Buffett had ever read. This blog pushed the book to the top of the Amazon charts. It was re-issued after this. The book is a collection of twelve long articles that Brooks wrote about the American businesses, government as well as Wall Street, for the New Yorker magazine. And it has tremendous lessons for almost everyone connected with business and finance. 

Single Man-The Life & Times of Nitish Kumar of Bihar by Sankarshan Thakur: This book is the joker in the pack. In a list full of books on economics and finance, here is a book on politics. Having been born in erstwhile Bihar, I have always been interested in the politics of Bihar. And there is no better writer on Bihar in English than Thakur, who works as a roving editor for The Telegraph newspaper. 

Thakur chronicles the rather turbulent life of Nitish Kumar, starting a little before the Emergency, and goes on to chronicle the life of the Bihari politician over the next four decades. As he does that he also goes into the history of Bihar over that period. Unlike a lot of other biography writers, Thakur also goes into Kumar's unhappy personal life. 

The book is an excellent model for how to write a biography of an Indian politician. What we normally get to read are either hagiographies or out and out criticism (as is the case with so many books on Narendra Modi which swing at both ends). There is rarely a biography of an Indian politician which takes the middle path. If I had to choose just one book to read this year, then Single Man would have to be it. And this would be more for Thakur's andaz-e-bayan (the way he tells the story) than Kumar's story per se. 

How Not to Be Wrong-The Hidden Maths of Everyday Life by Jordan Ellenberg: This is another joker in the pack. I absolutely love to read good books on Mathematics. Ellenberg in this book goes around explaining the practical aspects of Maths in everyday life. He explains in great detail how media often uses Maths incorrectly to draw wrong conclusions. He also tries to answer some really interesting questions: How early should you get to the airport? What's the best way to get rich playing a lottery? And does Facebook know you are terrorist? 

If you are feeling a little adventurous and want to go a little out of your comfort zone, this is just the right book for you. 

The End of Normal by James Galbraith: I am reading this book currently and am around half way through it. James Galbraith is the son of John Kenneth Galbraith, who I feel was one of the most lucid writers on economics that the twentieth century saw. Galbraith junior writes in the same lucid way as his father did. 

Since the financial crisis broke out, economists and politicians have tried to tell the world at large that "all is going to be well," and that the financial crisis was just caused by bad policy and bad people. Galbraith challenges this world view and offers four reasons against it: the rising cost of real resources, the futility of military power, the labour saving consequences of the digital revolution and the breakdown of law and ethics in the financial sector. Long story short: The global economy will not see acche din (good days)any time soon. 

Hormegeddon-How Too Much Of a Good Thing Leads to Disaster by Bill Bonner: The regular readers of The Daily Reckoning would know by now that this has been one of favourite books of the year, given the number of times I have already quoted from it in my columns. I have been a big fan of Bonner's writing since I first met him in late 2008. 


In this book Bonner goes about explaining how too much of a good thing in public policy, economics and businesses, leads to disaster or what he calls FUBAR (f***ed up beyond all recognition). Bonner offers many examples from history to make his point-from Napoleon's decision to invade Russia to the outbreak of the Second World War to America's War on Terror. He then goes on to show that these disasters cannot be prevented by well-informed people with good intentions because they are the ones who cause them in the first place. 

Thursday, August 8, 2013

Diabetes Food

 
- One teaspoon of methi seeds soaked overnight in 100 ml of water is very effective in controlling diabetes. 
- Drink tomato juice with salt and pepper ever morning on an empty stomach. 
- Intake of 6 almonds (soaked overnight) is also helpful in keeping a check on diabetes.

Whole grains, oats, channa atta, millets and other high fiber foods should be included in the meals. If one feels like consuming pasta or noodles, it should always be accompanied with vegetable /sprouts.
Milk is the right combination of carbohydrates and proteins and helps control blood sugar levels. Two servings of milk in a daily diet is a good option.
High fiber vegetables such as peas, beans, broccoli and spinach /leafy vegetables should be included in one's diet. Also, pulses with husk and sprouts are a healthy option and should form a part of the diet.
Pulses are important in the diet as their effect on blood glucose is less than that of most other carbohydrate containing foods. Vegetables rich in fiber help lowering down the blood sugar levels and thus are healthy.
Good fats such as Omega 3 and MUFA should be consumed as they are good for the body. Natural sources for these are canola oil, flax seed oil, fatty fish and nuts. These are also low in cholesterol and are trans fat free.
Fruits high in fiber such as papaya, apple, orange, pear and guava should be consumed. Mangoes, bananas, and grapes contain high sugar; therefore these fruits should be consumed lesser than the others.
daily exercise may be walking for thirty minutes. soak five dry grapes(grapes with seeds) after removing the seeds in lemon juice of one lemon of normal size for about 12 hrs, take entire thing on empty stomach in the morning . after that nothing be taken for thirty minutes, only 5days continuously, every month reduces the sugar level drastically, even if u eat sweats moderately.

Wednesday, May 8, 2013

How to access MSI database using C#

First create a console project.

Add following reference


Add following code.


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using WindowsInstaller;


namespace msiReadTest1
{
    [System.Runtime.InteropServices.ComImport(), System.Runtime.InteropServices.Guid("000C1090-0000-0000-C000-000000000046")]
    class Installer { }

    class Program
    {
        static void Main(string[] args)
        {
            WindowsInstaller.Installer ins = (WindowsInstaller.Installer)new Installer();
            string strFileMsi = @"C:\Users\kyadav.STC\Desktop\VitreaEnterpriseSuiteClient6.5.0.msi";
            Database db = ins.OpenDatabase(strFileMsi, WindowsInstaller.MsiOpenDatabaseMode.msiOpenDatabaseModeReadOnly);
           
            string sql = "Select `Property`.`Property` FROM `Property`";
            View vw = db.OpenView(sql);  // I'd like to pull from other tables besides Property as well
            vw.Execute(null);
            Record rcrd = vw.Fetch();
            while (rcrd != null)
            {
                Console.WriteLine(rcrd.get_StringData(1).Split('|')[0]);
                rcrd = vw.Fetch();
            }
            vw.Close();
            Console.ReadLine();
         
        }
    }
}

Thursday, December 22, 2011

Check Credentials in local Security Policy

using System;
using System.Collections.Generic;
using System.Text;
using System.Collections;
namespace LsaSecurity
{
/*
* LsaWrapper class credit: Willy Denoyette [MVP]
*
* http://www.hightechtalks.com/csharp/lsa-functions-276626.html
*
* Added support for:
*
* LsaLookupSids
*
* for the purposes of providing a working example.
*
*
*
*/


using System.Runtime.InteropServices;
using System.Security;
using System.Management;
using System.Runtime.CompilerServices;
using System.ComponentModel;

using LSA_HANDLE = IntPtr;

public class Program
{
public static void Main()
{
using (LsaWrapper lsaSec = new LsaWrapper())
{
//// string[] accounts = lsaSec.GetUsersWithPrivilege("SeNetworkLogonRight");
ArrayList accounts = lsaSec.GetUsersWithPrivilege("SeDenyBatchLogonRight");//SeServiceLogonRight //SeCreateGlobalPrivilege//SeDenyBatchLogonRight
//int returnvalue = lsaSec.checkUserRights("AMAT\\KYADAV106192");
}


}
}

[StructLayout(LayoutKind.Sequential)]
struct LSA_OBJECT_ATTRIBUTES
{
internal int Length;
internal IntPtr RootDirectory;
internal IntPtr ObjectName;
internal int Attributes;
internal IntPtr SecurityDescriptor;
internal IntPtr SecurityQualityOfService;
}
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
struct LSA_UNICODE_STRING
{
internal ushort Length;
internal ushort MaximumLength;
[MarshalAs(UnmanagedType.LPWStr)]
internal string Buffer;
}

sealed class Win32Sec
{
[DllImport("advapi32", CharSet = CharSet.Unicode, SetLastError = true),
SuppressUnmanagedCodeSecurityAttribute]
internal static extern uint LsaOpenPolicy(
LSA_UNICODE_STRING[] SystemName,
ref LSA_OBJECT_ATTRIBUTES ObjectAttributes,
int AccessMask,
out IntPtr PolicyHandle
);

[DllImport("advapi32", CharSet = CharSet.Unicode, SetLastError = true),
SuppressUnmanagedCodeSecurityAttribute]
internal static extern uint LsaAddAccountRights(
LSA_HANDLE PolicyHandle,
IntPtr pSID,
LSA_UNICODE_STRING[] UserRights,
int CountOfRights
);

[DllImport("advapi32", CharSet = CharSet.Unicode, SetLastError = true),
SuppressUnmanagedCodeSecurityAttribute]
internal static extern uint LsaRemoveAccountRights(
LSA_HANDLE PolicyHandle,
IntPtr pSID,
bool allRights,
LSA_UNICODE_STRING[] UserRights,
int CountOfRights
);

[DllImport("advapi32", CharSet = CharSet.Unicode, SetLastError = true),
SuppressUnmanagedCodeSecurityAttribute]
internal static extern uint LsaEnumerateAccountsWithUserRight(
LSA_HANDLE PolicyHandle,
LSA_UNICODE_STRING[] UserRights,
out IntPtr EnumerationBuffer,
out int CountReturned
);

[DllImport("advapi32", CharSet = CharSet.Unicode, SetLastError = true),
SuppressUnmanagedCodeSecurityAttribute]
internal static extern uint LsaLookupSids(
LSA_HANDLE PolicyHandle,
int count,
IntPtr buffer,
[MarshalAs(UnmanagedType.SysInt)] out LSA_HANDLE domainList,
out LSA_HANDLE nameList
);

// NTSTATUS LsaLookupSids2(
// _In_ LSA_HANDLE PolicyHandle,
// _In_ ULONG LookupOptions,
// _In_ ULONG Count,
// _In_ PSID *Sids,
// _Out_ PLSA_REFERENCED_DOMAIN_LIST *ReferencedDomains,
// _Out_ PLSA_TRANSLATED_NAME *Names
//);
[DllImport("Advapi32.dll", CharSet = CharSet.Unicode, SetLastError = true), SuppressUnmanagedCodeSecurityAttribute]
internal static extern uint LsaLookupSids2(
LSA_HANDLE PolicyHandle,
int LookupOptions,
int Count,
IntPtr buffer,
out LSA_HANDLE domainList,
out LSA_HANDLE nameList
);

[DllImport("advapi32", CharSet = CharSet.Unicode, SetLastError = true),
SuppressUnmanagedCodeSecurityAttribute]
internal static extern int LsaLookupNames2(
LSA_HANDLE PolicyHandle,
uint Flags,
uint Count,
LSA_UNICODE_STRING[] Names,
ref IntPtr ReferencedDomains,
ref IntPtr Sids
);

[DllImport("advapi32")]
internal static extern int LsaNtStatusToWinError(int NTSTATUS);

[DllImport("advapi32")]
internal static extern int LsaClose(IntPtr PolicyHandle);

[DllImport("advapi32")]
internal static extern int LsaFreeMemory(IntPtr Buffer);

}

public sealed class LsaWrapper : IDisposable
{
private bool _writeToConsole = false;

[StructLayout(LayoutKind.Sequential)]
struct LSA_TRUST_INFORMATION
{
internal LSA_UNICODE_STRING Name;
internal IntPtr Sid;
}
[StructLayout(LayoutKind.Sequential)]
struct LSA_TRANSLATED_SID2
{
internal SidNameUse Use;
internal IntPtr Sid;
internal int DomainIndex;
uint Flags;
}

//[StructLayout(LayoutKind.Sequential)]
//struct LSA_REFERENCED_DOMAIN_LIST
//{
// internal uint Entries;
// internal LSA_TRUST_INFORMATION Domains;
//}

[StructLayout(LayoutKind.Sequential)]
internal struct LSA_REFERENCED_DOMAIN_LIST
{
internal uint Entries;
internal IntPtr Domains;
}

[StructLayout(LayoutKind.Sequential)]
struct LSA_ENUMERATION_INFORMATION
{
internal LSA_HANDLE PSid;
}

[StructLayout(LayoutKind.Sequential)]
struct LSA_SID
{
internal uint Sid;
}

[StructLayout(LayoutKind.Sequential)]
struct LSA_TRANSLATED_NAME
{
internal SidNameUse Use;
internal LSA_UNICODE_STRING Name;
internal int DomainIndex;
}

[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
public struct LOCALGROUP_USERS_INFO_0
{
public string groupname;
}

enum SidNameUse : int
{
User = 1,
Group = 2,
Domain = 3,
Alias = 4,
KnownGroup = 5,
DeletedAccount = 6,
Invalid = 7,
Unknown = 8,
Computer = 9
}

enum Access : int
{
POLICY_READ = 0x20006,
POLICY_ALL_ACCESS = 0x00F0FFF,
POLICY_EXECUTE = 0X20801,
POLICY_WRITE = 0X207F8
}
const uint STATUS_ACCESS_DENIED = 0xc0000022;
const uint STATUS_INSUFFICIENT_RESOURCES = 0xc000009a;
const uint STATUS_NO_MEMORY = 0xc0000017;

IntPtr lsaHandle;

public LsaWrapper()
: this(null)
{ }
// // local system if systemName is null
public int checkUserRights(string Username)
{
ArrayList accountsLogOnAsBatch;
ArrayList accountsLogOnAsService;
ArrayList accountsLogOnAsCreateGlobalObjects;
ArrayList accountsDenyLogonAsBatch;
ArrayList accountsDenyLogonAsService;
try
{
accountsDenyLogonAsBatch = GetUsersWithPrivilege("SeDenyBatchLogonRight");//SeDenyBatchLogonRight
if (accountsDenyLogonAsBatch.Contains(Username)) return 1;
accountsDenyLogonAsService = GetUsersWithPrivilege("SeDenyServiceLogonRight");//SeDenyServiceLogonRight
if (accountsDenyLogonAsService.Contains(Username)) return 1;
accountsLogOnAsBatch = GetUsersWithPrivilege("SeBatchLogonRight");//SeServiceLogonRight //SeCreateGlobalPrivilege
if (accountsLogOnAsBatch.Contains(Username))
{
accountsLogOnAsService = GetUsersWithPrivilege("SeServiceLogonRight");//SeServiceLogonRight //SeCreateGlobalPrivilege
if (accountsLogOnAsService.Contains(Username))
{
accountsLogOnAsCreateGlobalObjects = GetUsersWithPrivilege("SeCreateGlobalPrivilege");//SeServiceLogonRight //SeCreateGlobalPrivilege
if (accountsLogOnAsCreateGlobalObjects.Contains(Username))
{
return 0;
}
else
{
return 1;
}
}
else
{
return 1;
}
}
else
{
return 1;
}
}
catch (Exception)
{
return 1;
}
}

public LsaWrapper(string systemName)
{
LSA_OBJECT_ATTRIBUTES lsaAttr;
lsaAttr.RootDirectory = IntPtr.Zero;
lsaAttr.ObjectName = IntPtr.Zero;
lsaAttr.Attributes = 0;
lsaAttr.SecurityDescriptor = IntPtr.Zero;
lsaAttr.SecurityQualityOfService = IntPtr.Zero;
lsaAttr.Length = Marshal.SizeOf(typeof(LSA_OBJECT_ATTRIBUTES));
lsaHandle = IntPtr.Zero;
LSA_UNICODE_STRING[] system = null;
if (systemName != null)
{
system = new LSA_UNICODE_STRING[1];
system[0] = InitLsaString(systemName);
}

uint ret = Win32Sec.LsaOpenPolicy(system, ref lsaAttr, (int)Access.POLICY_ALL_ACCESS, out lsaHandle);
if (ret == 0)
return;
if (ret == STATUS_ACCESS_DENIED)
{
throw new UnauthorizedAccessException();
}
if ((ret == STATUS_INSUFFICIENT_RESOURCES) || (ret == STATUS_NO_MEMORY))
{
throw new OutOfMemoryException();
}
throw new Win32Exception(Win32Sec.LsaNtStatusToWinError((int)ret));
}

public ArrayList GetUsersWithPrivilege(string privilege)
{
LSA_UNICODE_STRING[] privileges = new LSA_UNICODE_STRING[1];
privileges[0] = InitLsaString(privilege);

IntPtr buffer;
int count;
uint ret =
Win32Sec.LsaEnumerateAccountsWithUserRight(lsaHandle, privileges, out buffer, out count);

if (ret != 0 && privilege != "SeDenyBatchLogonRight" && privilege != "SeDenyServiceLogonRight")
{
if (ret == STATUS_ACCESS_DENIED)
{
throw new UnauthorizedAccessException();
}

if (ret == STATUS_INSUFFICIENT_RESOURCES || ret == STATUS_NO_MEMORY)
{
throw new OutOfMemoryException();
}

throw new Win32Exception(Win32Sec.LsaNtStatusToWinError((int)ret));
}

LSA_ENUMERATION_INFORMATION[] lsaInfo = new LSA_ENUMERATION_INFORMATION[count];
for (int i = 0, elemOffs = (int)buffer; i < count; i++)
{
lsaInfo[i] = (LSA_ENUMERATION_INFORMATION)Marshal.PtrToStructure((IntPtr)elemOffs, typeof(LSA_ENUMERATION_INFORMATION));
elemOffs += Marshal.SizeOf(typeof(LSA_ENUMERATION_INFORMATION));
}

LSA_HANDLE domains;
LSA_HANDLE names;
int LSA_LOOKUP_RETURN_LOCAL_NAMES = 0;

ret = Win32Sec.LsaLookupSids(lsaHandle, lsaInfo.Length, buffer, out domains, out names);
//ret = Win32Sec.LsaLookupSids2(lsaHandle, LSA_LOOKUP_RETURN_LOCAL_NAMES, lsaInfo.Length, buffer, out domains, out names);

if (ret != 0)
{
if (ret == STATUS_ACCESS_DENIED)
{
throw new UnauthorizedAccessException();
}

if (ret == STATUS_INSUFFICIENT_RESOURCES || ret == STATUS_NO_MEMORY)
{
throw new OutOfMemoryException();
}

throw new Win32Exception(Win32Sec.LsaNtStatusToWinError((int)ret));
}

string[] retNames = new string[count];
List currentDomain = new List();
int domainCount = 0;

LSA_TRANSLATED_NAME[] lsaNames = new LSA_TRANSLATED_NAME[count];
for (int i = 0, elemOffs = (int)names; i < count; i++)
{
lsaNames[i] = (LSA_TRANSLATED_NAME)Marshal.PtrToStructure((LSA_HANDLE)elemOffs, typeof(LSA_TRANSLATED_NAME));
elemOffs += Marshal.SizeOf(typeof(LSA_TRANSLATED_NAME));

LSA_UNICODE_STRING name = lsaNames[i].Name;
retNames[i] = name.Buffer.Substring(0, name.Length / 2);

if (!currentDomain.Contains(lsaNames[i].DomainIndex))
{
domainCount = domainCount + 1;
currentDomain.Add(lsaNames[i].DomainIndex);
}

}

string[] domainPtrNames = new string[count];

LSA_REFERENCED_DOMAIN_LIST[] lsaDomainNames = new LSA_REFERENCED_DOMAIN_LIST[count];

for (int i = 0, elemOffs = (int)domains; i < count; i++)
{
lsaDomainNames[i] = (LSA_REFERENCED_DOMAIN_LIST)Marshal.PtrToStructure((LSA_HANDLE)elemOffs, typeof(LSA_REFERENCED_DOMAIN_LIST));
elemOffs += Marshal.SizeOf(typeof(LSA_REFERENCED_DOMAIN_LIST));
}

LSA_TRUST_INFORMATION[] lsaDomainName = new LSA_TRUST_INFORMATION[count];
string[] domainNames = new string[domainCount];

for (int i = 0, elemOffs = (int)lsaDomainNames[i].Domains; i < domainCount; i++)
{
lsaDomainName[i] = (LSA_TRUST_INFORMATION)Marshal.PtrToStructure((LSA_HANDLE)elemOffs, typeof(LSA_TRUST_INFORMATION));
elemOffs += Marshal.SizeOf(typeof(LSA_TRUST_INFORMATION));

LSA_UNICODE_STRING tempDomain = lsaDomainName[i].Name;
//if(tempDomain.Buffer != null)
//{
domainNames[i] = tempDomain.Buffer.Substring(0, tempDomain.Length / 2);
//}
}

//string[] domainUserName = new string[count];
ArrayList domainUserName = new ArrayList();

for (int i = 0; i < lsaNames.Length; i++)
{
//domainUserName[i] = domainNames[lsaNames[i].DomainIndex] + "\\" + retNames[i];
domainUserName.Add(domainNames[lsaNames[i].DomainIndex] + "\\" + retNames[i]);
}


Win32Sec.LsaFreeMemory(buffer);
Win32Sec.LsaFreeMemory(domains);
Win32Sec.LsaFreeMemory(names);

//return retNames;
//return domainNames;
return domainUserName;
}

public void AddPrivileges(string account, string privilege)
{
IntPtr pSid = GetSIDInformation(account);
LSA_UNICODE_STRING[] privileges = new LSA_UNICODE_STRING[1];
privileges[0] = InitLsaString(privilege);
uint ret = Win32Sec.LsaAddAccountRights(lsaHandle, pSid, privileges, 1);

if (ret == 0)
{
if (this._writeToConsole)
{
Console.WriteLine("Added: {0} to {1} successfully.", account, privilege);
}
return;
}

if (ret == STATUS_ACCESS_DENIED)
{
throw new UnauthorizedAccessException();
}
if ((ret == STATUS_INSUFFICIENT_RESOURCES) || (ret == STATUS_NO_MEMORY))
{
throw new OutOfMemoryException();
}
throw new Win32Exception(Win32Sec.LsaNtStatusToWinError((int)ret));
}

public void RemovePrivileges(string account, string privilege)
{
IntPtr pSid = GetSIDInformation(account);
LSA_UNICODE_STRING[] privileges = new LSA_UNICODE_STRING[1];
privileges[0] = InitLsaString(privilege);
uint ret = Win32Sec.LsaRemoveAccountRights(lsaHandle, pSid, false, privileges, 1);

if (ret == 0)
{
if (this._writeToConsole)
{
Console.WriteLine("Removed: {0} from {1} successfully.", account, privilege);
}
return;
}
if (ret == STATUS_ACCESS_DENIED)
{
throw new UnauthorizedAccessException();
}
if ((ret == STATUS_INSUFFICIENT_RESOURCES) || (ret == STATUS_NO_MEMORY))
{
throw new OutOfMemoryException();
}
throw new Win32Exception(Win32Sec.LsaNtStatusToWinError((int)ret));
}

public void Dispose()
{
if (lsaHandle != IntPtr.Zero)
{
Win32Sec.LsaClose(lsaHandle);
lsaHandle = IntPtr.Zero;
}
GC.SuppressFinalize(this);
}
~LsaWrapper()
{
Dispose();
}
// helper functions

IntPtr GetSIDInformation(string account)
{
LSA_UNICODE_STRING[] names = new LSA_UNICODE_STRING[1];
LSA_TRANSLATED_SID2 lts;
IntPtr tsids = IntPtr.Zero;
IntPtr tdom = IntPtr.Zero;
names[0] = InitLsaString(account);
lts.Sid = IntPtr.Zero;
int ret = Win32Sec.LsaLookupNames2(lsaHandle, 0, 1, names, ref tdom, ref tsids);
if (ret != 0)
throw new Win32Exception(Win32Sec.LsaNtStatusToWinError(ret));
lts = (LSA_TRANSLATED_SID2)Marshal.PtrToStructure(tsids,
typeof(LSA_TRANSLATED_SID2));
Win32Sec.LsaFreeMemory(tsids);
Win32Sec.LsaFreeMemory(tdom);
return lts.Sid;
}

static LSA_UNICODE_STRING InitLsaString(string s)
{
// Unicode strings max. 32KB
if (s.Length > 0x7ffe)
throw new ArgumentException("String too long");
LSA_UNICODE_STRING lus = new LSA_UNICODE_STRING();
lus.Buffer = s;
lus.Length = (ushort)(s.Length * sizeof(char));
lus.MaximumLength = (ushort)(lus.Length + sizeof(char));

// If unicode issues then do this instead of previous two line
//lus.Length = (ushort)(s.Length * 2); // Unicode char is 2 bytes
//lus.MaximumLength = (ushort)(lus.Length + 2)

return lus;
}

public bool WriteToConsole
{
set { this._writeToConsole = value; }
}
}
}