Friday, December 9, 2011

SelectSingleNode / SelectNodes

The selectSingleNode method returns a Node object for the first descendant node to match the specified pattern. The one parameter of this method is an XSL pattern query. If no match is made, it returns null. This method is similar to theselectNodes method, but returns only the first node to match the pattern rather than all of them.



// Load the document and set the root element.
XmlDocument doc = new XmlDocument();
doc.Load("bookstore.xml");
XmlNode root = doc.DocumentElement;

// Add the namespace.
XmlNamespaceManager nsmgr = new XmlNamespaceManager(doc.NameTable);
nsmgr.AddNamespace("bk", "urn:newbooks-schema");

// Select and display the first node in which the author's 
// last name is Kingsolver.
XmlNode node = root.SelectSingleNode(
    "descendant::bk:book[bk:author/bk:last-name='Kingsolver']", nsmgr);
Console.WriteLine(node.InnerXml);
----------------
The primary means of reading and writing in C# 2.0 is done through the XmlDocument class. You can load most of your settings directly into the XmlDocument through the XmlReader it accepts.

Loading XML Directly

XmlDocument document = new XmlDocument();
document.LoadXml("");

Loading XML From a File

XmlDocument document = new XmlDocument();
document.Load(@"C:\Path\To\xmldoc.xml");
// Or using an XmlReader/XmlTextReader
XmlReader reader = XmlReader.Create(@"C:\Path\To\xmldoc.xml");
document.Load(reader);
I find the easiest/fastest way to read an XML document is by using XPath.

Reading an XML Document using XPath (Using XmlDocument which allows us to edit)

XmlDocument document = new XmlDocument();
document.LoadXml("");
// Select a single node
XmlNode node = document.SelectSingleNode("/People/Person[@Name = 'Nick']");
// Select a list of nodes
XmlNodeList nodes = document.SelectNodes("/People/Person");
If you need to work with XSD documents to validate an XML document you can use this.

Validating XML Documents against XSD Schemas

XmlReaderSettings settings = new XmlReaderSettings();
settings.ValidateType = ValidationType.Schema;
settings.Schemas.Add("", pathToXsd); // targetNamespace, pathToXsd
XmlReader reader = XmlReader.Create(pathToXml, settings);
XmlDocument document = new XmlDocument();
try {
    document.Load(reader);
} catch (XmlSchemaValidationException ex) { Trace.WriteLine(ex.Message); }

Validating XML against XSD at each Node (UPDATE 1)

XmlReaderSettings settings = new XmlReaderSettings();
settings.ValidateType = ValidationType.Schema;
settings.Schemas.Add("", pathToXsd); // targetNamespace, pathToXsd
settings.ValidationEventHandler += new ValidationEventHandler(settings_ValidationEventHandler);
XmlReader reader = XmlReader.Create(pathToXml, settings);
while (reader.Read()) { }
private void settings_ValidationEventHandler(object sender, ValidationEventArgs args)
{
    // e.Message, e.Severity (warning, error), e.Error
    // or you can access the reader if you have access to it
    // reader.LineNumber, reader.LinePosition.. etc
}

Writing an XML Document (manually)

XmlWriter writer = XmlWriter.Create(pathToOutput);
writer.WriteStartDocument();
writer.WriteStartElement("People");

writer.WriteStartElement("Person");
writer.WriteAttributeString("Name", "Nick");
writer.WriteEndElement();

writer.WriteStartElement("Person");
writer.WriteStartAttribute("Name");
writer.WriteValue("Nick");
writer.WriteEndAttribute();
writer.WriteEndElement();

writer.WriteEndElement();
writer.WriteEndDocument();

writer.Flush();
(UPDATE 1)
In .NET 3.5, you use XDocument to perform similar tasks. The difference however is you have the advantage of performing Linq Queries to select the exact data you need. With the addition of object initializers you can create a query that even returns objects of your own definition right in the query itself.
    XDocument doc = XDocument.Load(pathToXml);
    List<Person> people = (from xnode in xdoc.Element("People").Elements("Person")
                       select new Person
                       {
                           Name = xnode.Attribute("Name").Value
                       }).ToList();
(UPDATE 2)
A nice way in .NET 3.5 is to use XDocument to create XML is below. This makes the code appear in a similar pattern to the desired output.
XDocument doc =
        new XDocument(
              new XDeclaration("1.0", Encoding.UTF8.HeaderName, String.Empty),
              new XComment("Xml Document"),
              new XElement("catalog",
                    new XElement("book",
                          new XAttribute("id", "bk001"),
                                new XElement("title", "Book Title")
                    )
              )
        );
creates


  < span=""> id="bk001"
    </span><span class="pln" style="margin-top: 0px; margin-right: 0px; margin-bottom: 0px; margin-left: 0px; padding-top: 0px; padding-right: 0px; padding-bottom: 0px; padding-left: 0px; border-top-width: 0px; border-right-width: 0px; border-bottom-width: 0px; border-left-width: 0px; border-style: initial; border-color: initial; vertical-align: baseline; background-image: initial; background-attachment: initial; background-origin: initial; background-clip: initial; background-color: transparent; ">Book Title</span><span class="tag" style="margin-top: 0px; margin-right: 0px; margin-bottom: 0px; margin-left: 0px; padding-top: 0px; padding-right: 0px; padding-bottom: 0px; padding-left: 0px; border-top-width: 0px; border-right-width: 0px; border-bottom-width: 0px; border-left-width: 0px; border-style: initial; border-color: initial; vertical-align: baseline; background-image: initial; background-attachment: initial; background-origin: initial; background-clip: initial; background-color: transparent; color: rgb(128, 0, 0); ">
  

All else fails, you can check out this MSDN article that has many examples that I've discussed here and more. http://msdn.microsoft.com/en-us/library/aa468556.aspx
-----------------------------------------

Synonym - Dec 2011


mull 2  (ml)
v. mulledmull·ingmulls
v.tr.
To go over extensively in the mind; ponder.
v.intr.
To ruminate; ponder: mull over a plan.

[Probably Middle English mollen, mullento moisten, crumble; see moil.]


mull 3  (ml)
n.
A soft thin muslin used in dresses and for trimmings.

[Short for mulmull, from Hindi malmal.]
Mull  (ml)
An island of western Scotland in the Inner Hebrides. It is separated from the mainland on the northeast by the Sound of Mull.

mull 1  (ml)
tr.v. mulledmull·ingmulls
To heat and spice (wine, for example).

[Origin unknown.]


skep·ti·cal also scep·ti·cal  (skpt-kl)

adj.
1. Marked by or given to doubt; questioning: a skeptical attitude; skeptical of political promises.
2. Relating to or characteristic of skeptics or skepticism.
-----------



re·luc·tant/riˈləktənt/

Adjective:
Unwilling and hesitant; disinclined.
Synonyms:
unwilling - loath - loth - averse


per·co·late/ˈpərkəˌlāt/

Verb:
  1. (of a liquid or gas) Filter gradually through a porous surface or substance.
  2. (of information or an idea or feeling) Spread gradually through an area or group of people.
Synonyms:
filter - filtrate - strain - infiltrate - seep - ooze
per·co·late  (pûrk-lt)
v. per·co·lat·edper·co·lat·ingper·co·lates
v.tr.
1. To cause (liquid, for example) to pass through a porous substance or small holes; filter.
2. To pass or ooze through: Water percolated the sand.
3. To make (coffee) in a percolator.
v.intr.
1. To drain or seep through a porous material or filter.
2. Informal To become lively or active.
3. Informal To spread slowly or gradually.
n. (-lt, -lt)
A liquid that has been percolated.


rid·dance/ˈridns/

Noun:
The action of getting rid of something troublesome.
Synonyms:
deliverance - release - liberation - rescue - relief


Noun1.percolate - the product of percolationpercolate - the product of percolation        
filtrate - the product of filtration; a gas or liquid that has been passed through a filter
Verb1.percolate - permeate or penetrate gradually; "the fertilizer leached into the ground"
dribbletricklefilter - run or flow slowly, as in drops or in an unsteady stream; "water trickled onto the lawn from the broken hose"; "reports began to dribble in"
2.percolate - spread gradually; "Light percolated into our house in the morning"
diffusefan outspread outspread - move outward; "The soldiers fanned out"
3.percolate - prepare in a percolator; "percolate coffee"
percolate - cause (a solvent) to pass through a permeable substance in order to extract a soluble constituent
4.percolate - cause (a solvent) to pass through a permeable substance in order to extract a soluble constituent
percolate - prepare in a percolator; "percolate coffee"
5.percolate - pass through; "Water permeates sand easily"
penetrateperforate - pass into or through, often by overcoming resistance; "The bullet penetrated her chest"
infiltrate - pass into or through by filtering or permeating; "the substance infiltrated the material"
infiltrate - cause (a liquid) to enter by penetrating the interstices
6.percolate - gain or regain energy; "I picked up after a nap"
convalescerecoverrecuperate - get over an illness or shock; "The patient is recuperating"























Wednesday, December 7, 2011

C# WebClient Tutorial


You want to use the WebClient class in the System.Net namespace to download web pages and files using the C# language targeting the .NET Framework. This class makes it possible to easily download web pages for testing, allowing you to automate important tests for important web sites. Here we look at the WebClient class.
Key point:Use WebClient to download files on the Internet.

Example 1

First, to use the WebClient class in your C# code you need to either use the fully specified name System.Net.WebClient or include the System.Net namespace with a using directive. This example uses the namespace and creates a new WebClient object instance and sets its user agent as Internet Explorer 6. This WebClient will then download a page and the server will think it is Internet Explorer 6, allowing you to test this case.
Program that uses client user-agent [C#]

using System;
using System.Net;

class Program
{
    static void Main()
    {
 // Create web client simulating IE6.
 using (WebClient client = new WebClient())
 {
     client.Headers["User-Agent"] = "Mozilla/4.0 (Compatible; Windows NT 5.1; MSIE 6.0)" +
  " (compatible; MSIE 6.0; Windows NT 5.1; .NET CLR 1.1.4322; .NET CLR 2.0.50727)";

     // Download data.
     byte[] arr = client.DownloadData("http://www.dotnetperls.com/");

     // Write values.
     Console.WriteLine("--- WebClient result ---");
     Console.WriteLine(arr.Length);
 }
    }
}

Output

--- WebClient result ---
6585
Simulating user-agent header. You can add a new HTTP header to your WebClients download request by assigning an entry in the Headers collection. You can also use the WebHeaderCollection returned by Headers and call the Add, Remove, Set and Count methods on it.
Getting byte arrays. The DownloadData instance method on the WebClient is called and its reference return value is assigned to a new byte array reference. Internally, the DownloadData method will allocate the bytes on the managed heap. When you assign the result to the variable, you are doing a bitwise copy of the reference to that data.
Disposing of WebClient. The program shows that you can use the 'using' statement to ensure that the system resources for the WebClient are cleaned up by the system by placing them on the finalization queue. This is critical for longer programs but not needed for very short and trivial programs.

Friday, December 2, 2011

The Hard Truth About How Success Really Works


The Hard Truth About How Success Really Works

Here's what's getting in your way when you attempt (and fail) to hit those "reach" goals.

5 Unusual Ways to Become a Better Speaker


5 Unusual Ways to Become a Better Speaker

The art of captivating an audience can take years to develop. Since you don't have that long, here are some quick tips to improve overnight.



You’ve been asked to speak at an important event. It’s a great opportunity and you should be thrilled—but since you rarely speak, especially in a formal setting, all you can think about is bombing.
Unfortunately, captivating an audience is definitely a skill that takes years to develop and hone. Since you don’t have that kind of time, here are five unconventional ways to become a better speaker almost overnight:
1. Share an emotional story. Many speakers tell self-deprecating stories but few can resist including the Tom Cruise “talk to me Goose” moment (4:20, NSFW) when all your mistakes and poor decisions and ill-fated tower flybys over an Admiral’s daughter finally came to a head and transformed you into the wonderful person you are today.
Admitting a mistake is great but not when used simply to show how far you’ve come. Instead just tell a story that relates to your topic and let your emotions show. If you were sad, say so. If you cried, say so. If you felt remorse, let it show. When you share real feelings you create an immediate and lasting connection with the audience. Emotion trumps speaking skills every time.
2. Pause for 8 to 10 seconds. There’s a weird phenomena that occurs when you stop talking. Pause for two or three seconds, the audience assume you lost your place. Pause for five seconds and the audience begins to think the pause is intentional... and starts wondering why. Pause for ten seconds and even the people who were immersed in Angry Birds can’t resist looking up.
Then when you start speaking again, the audience naturally 1) assumes the pause was intentional and 2) decides you’re actually a confident and accomplished speaker. Like nature a poor speaker abhors a vacuum and rushes to fill it, and only confident speakers—like you—feel secure in silence. While it won’t be easy, take one long pause to gather your thoughts and the audience will automatically give you speaker bonus points.
3. Ask a question the audience—and you—can’t answer. Speakers ask questionsto engage the audience but that technique is often forced and tends to work about as well as this. Instead ask a question you know the audience can’t answer and then say,” That’s okay. I can’t either.” Explain why you can’t and then talk about what you do know. Most speakers have all the answers; the fact you don’t—and are willing to admit it—not only humanizes you but makes the audience pay greater attention to what you do know.
4. Find one thing no one knows. I’ve never heard someone say, “I was at this presentation the other day and the guy’s Gantt chart was amazing...” I have heard someone say, “Did you know when you blush the lining of your stomach also turns red?” Find a surprising fact or an unusual analogy that relates to your topic. Audiences love to cock their heads and think, “Hmmm...”
5. Never think “sales.” Most businesspeople assume they should capitalize on a speaking engagement to try to promote a product or service, win new clients, and build a wider network. Don’t. Thinking in terms of sales only adds additional pressure to what is already a stressful situation. Put all your focus on ensuring the audience will benefit from what you say; never try to accomplish more than one thing.
And don’t worry that you’ll be missing out on an opportunity: When you help people make their professional or personal lives better, you’ve done all the selling you’ll need to do.

9 Things That Motivate Employees More Than Money


9 Things That Motivate Employees More Than Money

Don't show 'em the money (even if you have it). Here are nine better ways to boost morale.


The ability to motivate employees is one of the greatest skills an entrepreneur can possess. Two years ago, I realized I didn’t have this skill. So I hired a CEO who did.
Josh had 12 years in the corporate world, which included running a major department at Comcast. I knew he was seasoned, but I was still skeptical at first. We were going through some tough growing pains, and I thought that a lack of cash would make it extremely difficult to improve the company morale.
I was wrong.
With his help and the help of the great team leaders he put in place, Josh not only rebuilt the culture, but also created a passionate, hard-working team that is as committed to growing and improving the company as I am. 
Here are nine things I learned from him:
  1. Be generous with praise. Everyone wants it and it’s one of the easiest things to give. Plus, praise from the CEO goes a lot farther than you might think. Praise every improvement that you see your team members make. Once you’re comfortable delivering praise one-on-one to an employee, try praising them in front of others.  
  2. Get rid of the managers. Projects without project managers? That doesn’t seem right! Try it. Removing the project lead or supervisor and empowering your staff to work together as a team rather then everyone reporting to one individual can do wonders. Think about it. What’s worse than letting your supervisor down? Letting your team down! Allowing people to work together as a team, on an equal level with their co-workers, will often produce better projects faster. People will come in early, stay late, and devote more of their energy to solving problems.  
  3. Make your ideas theirs. People hate being told what to do. Instead of telling people what you want done; ask them in a way that will make them feel like they came up with the idea. “I’d like you to do it this way” turns into “Do you think it’s a good idea if we do it this way?”  
  4. Never criticize or correct. No one, and I mean no one, wants to hear that they did something wrong. If you’re looking for a de-motivator, this is it. Try an indirect approach to get people to improve, learn from their mistakes, and fix them. Ask, “Was that the best way to approach the problem? Why not? Have any ideas on what you could have done differently?” Then you’re having a conversation and talking through solutions, not pointing a finger.  
  5. Make everyone a leader. Highlight your top performers’ strengths and let them know that because of their excellence, you want them to be the example for others. You’ll set the bar high and they’ll be motivated to live up to their reputation as a leader.  
  6. Take an employee to lunch once a week. Surprise them. Don’t make an announcement that you’re establishing a new policy. Literally walk up to one of your employees, and invite them to lunch with you. It’s an easy way to remind them that you notice and appreciate their work.  
  7. Give recognition and small rewards. These two things come in many forms: Give a shout out to someone in a company meeting for what she has accomplished. Run contests or internal games and keep track of the results on a whiteboard that everyone can see. Tangible awards that don’t break the bank can work too. Try things like dinner, trophies, spa services, and plaques. 
  8. Throw company parties. Doing things as a group can go a long way. Have a company picnic. Organize birthday parties. Hold a happy hour. Don’t just wait until the holidays to do a company activity; organize events throughout the year to remind your staff that you’re all in it together.
  9. Share the rewards—and the pain. When your company does well, celebrate. This is the best time to let everyone know that you’re thankful for their hard work. Go out of your way to show how far you will go when people help your company succeed. If there are disappointments, share those too. If you expect high performance, your team deserves to know where the company stands. Be honest and transparent.