<?xml version='1.0' encoding='UTF-8'?><rss xmlns:atom="http://www.w3.org/2005/Atom" xmlns:openSearch="http://a9.com/-/spec/opensearchrss/1.0/" xmlns:blogger="http://schemas.google.com/blogger/2008" xmlns:georss="http://www.georss.org/georss" xmlns:gd="http://schemas.google.com/g/2005" xmlns:thr="http://purl.org/syndication/thread/1.0" version="2.0"><channel><atom:id>tag:blogger.com,1999:blog-59384554657271185</atom:id><lastBuildDate>Wed, 22 Jan 2025 23:24:47 +0000</lastBuildDate><category>Python</category><category>Microsoft Pex</category><category>R Programming Language</category><category>NoSQL</category><category>Microsoft Roslyn</category><category>NUnit</category><category>Syntax Trees</category><category>Unit testing</category><category>CSDP</category><category>JSON</category><category>Microsoft Dynamics CRM 2011</category><category>Parameterized Unit Tests</category><category>Redis</category><category>SWEBOK</category><category>Software Engineering Education</category><category>Statistics</category><category>Unit Tests</category><category>Z3</category><category>Compilers</category><category>MSMQ</category><category>MongoDB</category><category>WCF</category><category>Apache Cassandra</category><category>Business Intelligence Development Studio</category><category>Business Intelligence Development Studio CRM Report Authoring Extension</category><category>Cassandra</category><category>Dynamics CRM Plug-in Registration Tool</category><category>Early Binding</category><category>FetchXML</category><category>Interview Questions</category><category>JPF</category><category>Late Binding</category><category>Microsoft Dynamics CRM Dashboards</category><category>Microsoft Dynamics CRM Forms</category><category>Microsoft Dynamics CRM SiteMap</category><category>Microsoft Dynamics CRM Solution Configuration Page</category><category>Microsoft Excel</category><category>Model Checking</category><category>Peer-to-Peer</category><category>Plug-ins</category><category>PostgreSQL</category><category>Programming Thoughts</category><category>Requirements Engineering</category><category>SMT-LIB</category><category>SQL</category><category>SQL Server Reporting Services</category><category>Satiability Modulo Theories</category><category>SharePoint 2010</category><category>SharePoint 2013</category><category>SharePoint Designer 2010</category><category>Web Resources</category><title>Midnight Researcher Notes</title><description></description><link>http://ebeid-soliman.blogspot.com/</link><managingEditor>noreply@blogger.com (Ebeid Soliman ElSayed)</managingEditor><generator>Blogger</generator><openSearch:totalResults>84</openSearch:totalResults><openSearch:startIndex>1</openSearch:startIndex><openSearch:itemsPerPage>25</openSearch:itemsPerPage><item><guid isPermaLink="false">tag:blogger.com,1999:blog-59384554657271185.post-6637037736883256950</guid><pubDate>Fri, 23 Aug 2013 22:56:00 +0000</pubDate><atom:updated>2013-08-27T12:31:43.770-05:00</atom:updated><category domain="http://www.blogger.com/atom/ns#">Microsoft Roslyn</category><category domain="http://www.blogger.com/atom/ns#">Syntax Trees</category><title>Syntax Modification using Microsoft Roslyn</title><description>&lt;p&gt;In the previous two posts we just used the analysis capabilities of Microsoft &lt;a title=&quot;Microsoft&amp;reg; &amp;ldquo;Roslyn&amp;rdquo; CTP&quot; href=&quot;http://msdn.microsoft.com/en-us/vstudio/roslyn.aspx&quot; target=&quot;_blank&quot;&gt;Roslyn&lt;/a&gt;. In other words, we only get information about the code under inspection, we never changed it. In this post we going to change the code through Roslyn. &lt;/p&gt; &lt;p&gt;Before we start we need to highlight that data structures that represent code under inspection in Roslyn APIs are immutable. This means that it cannot be changed after they are created (in order to safely share them between tools). This applies to syntax trees, compilations, symbols, semantic models, and every other data structure in the Roslyn API. Instead of modification, new objects are created based on specified differences to the old ones.&lt;/p&gt; &lt;h3&gt;Creating and Modifying Trees&lt;/h3&gt; &lt;p&gt;We used &lt;em&gt;SyntaxTree&lt;/em&gt; before to create syntax trees from a code snippet. For creating a syntax tree bit-by-bit, you have to compose syntax nodes hierarchically in a bottom-up fashion. To create &lt;em&gt;SyntaxNodes&lt;/em&gt; you must use the &lt;em&gt;Syntax&lt;/em&gt; class factory methods. For each kind of node, token, or trivia there is a factory method which can be used to create an instance of that type.&lt;/p&gt; &lt;p&gt;In the following example we going to replace a using directive by a new one we create.&lt;/p&gt;&lt;pre class=&quot;prettyprint lang-cs&quot;&gt;using System;&lt;br /&gt;using System.Collections.Generic;&lt;br /&gt;using System.Linq;&lt;br /&gt;using System.Text;&lt;br /&gt;using Roslyn.Compilers;&lt;br /&gt;using Roslyn.Compilers.CSharp;&lt;br /&gt;using Roslyn.Services;&lt;br /&gt;using Roslyn.Services.CSharp;&lt;br /&gt;&lt;br /&gt;namespace RoslynDemo4&lt;br /&gt;{&lt;br /&gt;    class Program&lt;br /&gt;    {&lt;br /&gt;        static void Main(string[] args)&lt;br /&gt;        {&lt;br /&gt;            SyntaxTree tree = SyntaxTree.ParseText(&lt;br /&gt;@&quot;using System;&lt;br /&gt;using System.Collections;&lt;br /&gt;using System.Linq;&lt;br /&gt;using System.Text;&lt;br /&gt; &lt;br /&gt;namespace HelloWorld&lt;br /&gt;{&lt;br /&gt;    class Program&lt;br /&gt;    {&lt;br /&gt;        static void Main(string[] args)&lt;br /&gt;        {&lt;br /&gt;            Console.WriteLine(&quot;&quot;Hello, World!&quot;&quot;);&lt;br /&gt;        }&lt;br /&gt;    }&lt;br /&gt;}&quot;);&lt;br /&gt;&lt;br /&gt;            var root = (CompilationUnitSyntax)tree.GetRoot();&lt;br /&gt;            // Get the old Using directive [using System.Collections;]&lt;br /&gt;            var oldUsing = root.Usings[1];&lt;br /&gt;&lt;br /&gt;            // Construct the new Using directive&lt;br /&gt;            NameSyntax name = Syntax.IdentifierName(&quot;System&quot;);&lt;br /&gt;            name = Syntax.QualifiedName(name, Syntax.IdentifierName(&quot;Collections&quot;));&lt;br /&gt;            name = Syntax.QualifiedName(name, Syntax.IdentifierName(&quot;Generic&quot;));&lt;br /&gt;            var newUsing = oldUsing.WithName(name);&lt;br /&gt;&lt;br /&gt;            // Replace the old Using directive by the new Using directive&lt;br /&gt;            root = root.ReplaceNode(oldUsing, newUsing);&lt;br /&gt;&lt;br /&gt;            SyntaxTree newTree = SyntaxTree.Create(root);&lt;br /&gt;            Console.WriteLine(newTree.ToString());&lt;br /&gt;            Console.ReadLine();&lt;br /&gt;        }&lt;br /&gt;    }&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;p&gt;&lt;em&gt;NameSyntax&lt;/em&gt; is the base class for the following names that can appear in C# code: &lt;br /&gt;&lt;ul&gt;&lt;br /&gt;&lt;li&gt;&lt;em&gt;IdentifierNameSyntax&lt;/em&gt; which represents simple single identifier names like &lt;b&gt;System&lt;/b&gt; and &lt;em&gt;Roslyn&lt;/em&gt; &lt;br /&gt;&lt;li&gt;&lt;em&gt;GenericNameSyntax&lt;/em&gt; which represents a generic type or method name such as &lt;em&gt;List&amp;lt;int&amp;gt;&lt;/em&gt; &lt;br /&gt;&lt;li&gt;&lt;em&gt;QualifiedNameSyntax&lt;/em&gt; which represents a qualified name of the form &amp;lt;left-name&amp;gt;.&amp;lt;right-identifier-or-generic-name&amp;gt; such as &lt;em&gt;System.IO&lt;/em&gt;&lt;/li&gt;&lt;/ul&gt;&lt;br /&gt;&lt;p&gt;In our example we constructed a NameSyntax to represent System.Collections.Generic incrementally. Then we used the ReplaceNode method to replace the &lt;em&gt;&lt;font color=&quot;#0000ff&quot;&gt;using System.Collections;&lt;/font&gt;&lt;/em&gt; directive with the &lt;font color=&quot;#0000ff&quot;&gt;&lt;em&gt;using System.Collections.Generic; &lt;/em&gt;&lt;/font&gt;&lt;font color=&quot;#000000&quot;&gt;directive. We then constructed a new SyntaxTree using the modified root and print it. You should see the modified HelloWorld program:&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEh08zTkPcT1UebAHLez2iTsFKlvGG9AnVsiDgNPMoWoyl9qqCZdRe0X337hrGekks8JVpkoXdeA9cSEhmcmkPV-wOIa5aUg2DjXFxjZUhXcVAXokpFZeQUcqdM6n4JK0oAbmes6rQ5i6w/s1600-h/fileFProjectsRoslynDemo4RoslynDemo4binDebugRoslynDemo4.EXE_2013-08-23_09-38-56%25255B4%25255D.png&quot;&gt;&lt;img style=&quot;background-image: none; border-right-width: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px&quot; title=&quot;fileFProjectsRoslynDemo4RoslynDemo4binDebugRoslynDemo4.EXE_2013-08-23_09-38-56&quot; border=&quot;0&quot; alt=&quot;fileFProjectsRoslynDemo4RoslynDemo4binDebugRoslynDemo4.EXE_2013-08-23_09-38-56&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEi1IuLVhZBZ6LN3WoRjDZGQPFsHwpWdJ7PbZ9HyvaszSBrvPu4cfql-tZlZgpJF7BeJzceHf73Kd4NkspNta3iRKCPAfz2PZvyRIEblt9Bw9mFnehW02qiwvBvrArX5cZUvxKwdxuDxhQ/?imgmax=800&quot; width=&quot;480&quot; height=&quot;246&quot;&gt;&lt;/a&gt;&lt;/font&gt;&lt;/p&gt;&lt;br /&gt;&lt;h3&gt;Modifying Syntax Trees using SyntaxRewriters&lt;/h3&gt;&lt;br /&gt;&lt;p&gt;In a previous &lt;a title=&quot;Getting started with Microsoft Roslyn Syntax Analysis&quot; href=&quot;http://ebeid-soliman.blogspot.com/2013/08/getting-started-with-microsoft-roslyn.html&quot; target=&quot;_blank&quot;&gt;post&lt;/a&gt; we implemented our &lt;em&gt;SyntaxWalker&lt;/em&gt;. Now we going to use the same technique and implement our &lt;em&gt;SyntaxRewriter&lt;/em&gt;. Both SyntaxWalker and SyntaxRewriter are subclasses of SyntaxVisitor which recursively visit every node in the syntax tree starting from the passed node. The &lt;em&gt;SyntaxRewriter&lt;/em&gt; class can be used to apply a transformation to a specific type of &lt;em&gt;SyntaxNode&lt;/em&gt;&lt;strong&gt;.&lt;/strong&gt; It is also possible&lt;b&gt; &lt;/b&gt;to apply a set of transformations to multiple types of &lt;em&gt;SyntaxNode&lt;/em&gt; wherever they appear in a syntax tree. It uses &lt;a title=&quot;Depth-first search [Wikipedia]&quot; href=&quot;http://en.wikipedia.org/wiki/Depth-first_search&quot; target=&quot;_blank&quot;&gt;depth-first search&lt;/a&gt; algorithm for SyntaxTree traversal.&lt;/p&gt;&lt;br /&gt;&lt;p&gt;In the following example we will implement our own &lt;em&gt;SyntaxRewriter&lt;/em&gt; which will replace all variable declaration types with the &lt;em&gt;var&lt;/em&gt; type. Create a new Console application and add a new class myRewriter to it. Edit the myRewriter.cs to look like:&lt;/p&gt;&lt;pre class=&quot;prettyprint lang-cs&quot;&gt;using System;&lt;br /&gt;using Roslyn.Compilers;&lt;br /&gt;using Roslyn.Compilers.CSharp;&lt;br /&gt;&lt;br /&gt;namespace RoslynDemo5&lt;br /&gt;{&lt;br /&gt;    class myRewriter : SyntaxRewriter&lt;br /&gt;    {&lt;br /&gt;        private readonly SemanticModel SemanticModel;&lt;br /&gt;&lt;br /&gt;        public myRewriter(SemanticModel semanticModel)&lt;br /&gt;        {&lt;br /&gt;            this.SemanticModel = semanticModel;&lt;br /&gt;        }&lt;br /&gt;&lt;br /&gt;        public override SyntaxNode VisitLocalDeclarationStatement(LocalDeclarationStatementSyntax node)&lt;br /&gt;        {&lt;br /&gt;            // To avoid the case of multiple variables in a single declaration like the following one&lt;br /&gt;            // Type variable1 = expression1,&lt;br /&gt;            //      variable2 = expression2;&lt;br /&gt;            if (node.Declaration.Variables.Count &amp;gt; 1)&lt;br /&gt;            {&lt;br /&gt;                return node;&lt;br /&gt;            }&lt;br /&gt;&lt;br /&gt;            // To avoid the case of case of a declation without an initializer like the following&lt;br /&gt;            // Type variable;&lt;br /&gt;            if (node.Declaration.Variables[0].Initializer == null)&lt;br /&gt;            {&lt;br /&gt;                return node;&lt;br /&gt;            }&lt;br /&gt;            &lt;br /&gt;            // Get the first varaible in the declation&lt;br /&gt;            VariableDeclaratorSyntax declarator = node.Declaration.Variables.First(); &lt;br /&gt;            // Get the Type used in the declaration&lt;br /&gt;            TypeSyntax variableTypeName = node.Declaration.Type;&lt;br /&gt;            // Bind the Type used in the declaration to a Symbol&lt;br /&gt;            TypeSymbol variableType = (TypeSymbol)SemanticModel.GetSymbolInfo(variableTypeName).Symbol;&lt;br /&gt;            // Get the whole intialization expression&lt;br /&gt;            TypeInfo initializerInfo = SemanticModel.GetTypeInfo(declarator.Initializer.Value);&lt;br /&gt;            if (variableType == initializerInfo.Type)&lt;br /&gt;            {&lt;br /&gt;                // Constructing a new Type with the same leading/trailing in the old type to maintain vertical whitespace and indentation&lt;br /&gt;                TypeSyntax varTypeName = Syntax.IdentifierName(&quot;var&quot;).&lt;br /&gt;                    WithLeadingTrivia(&lt;br /&gt;                    variableTypeName.GetLeadingTrivia()&lt;br /&gt;                    ).&lt;br /&gt;                    WithTrailingTrivia(&lt;br /&gt;                    variableTypeName.GetTrailingTrivia()&lt;br /&gt;                    );&lt;br /&gt;                // Do the replacement and return the new node&lt;br /&gt;                return node.ReplaceNode(variableTypeName, varTypeName);&lt;br /&gt;            }&lt;br /&gt;            else&lt;br /&gt;            {&lt;br /&gt;                return node;&lt;br /&gt;            }&lt;br /&gt;        }&lt;br /&gt;    }&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;p&gt;myRewriter class is simply inheriting from &lt;em&gt;SyntaxRewriter&lt;/em&gt; class and implments the &lt;em&gt;VisitLocalDeclarationStatment()&lt;/em&gt; method. This method is called by the &lt;em&gt;Visit&lt;/em&gt; method on &lt;em&gt;SyntaxRewriter&lt;/em&gt;, which recursively visits a node and each of its children. The &lt;em&gt;VisitLocalDeclarationStatment &lt;/em&gt;method is called on local declaration statements only. It tokes the starting SyntaxNode, if you passed the tree root (as we will do) it will visit the the local declaration statements that exists in the whole program.&lt;/p&gt;&lt;br /&gt;&lt;p&gt;Our rewriter takes the semantic model under inspection in the constructor.&lt;/p&gt;&lt;br /&gt;&lt;p&gt;In the &lt;em&gt;VisitLocalDeclarationStatment &lt;/em&gt;method we check the declaration statement to filter out the cases that are not within our interest. For these cases we return the node unchanged.&lt;/p&gt;&lt;br /&gt;&lt;p&gt;For the cases we interested in, we retrieve the variable and the type used for its declaration. Get a symbol for the type and the whole initialization expression.&lt;/p&gt;&lt;br /&gt;&lt;p&gt;Then we check that the type used in the declaration is the type used in the initialization to avoid the situations where the declaration may be casting the initializer expression to a base class or interface. Removing the explicit type in these cases would change the semantics of a program.&lt;/p&gt;&lt;br /&gt;&lt;p&gt;Then we construct a new TypeSyntax representing the var type with any leading or trailing tivia (white spaces and tabs) to conserve the indentation. Then we replace the node and return the new node.&lt;/p&gt;&lt;br /&gt;&lt;p&gt;Let’s go back to our Main method in the Program.cs file. In order to use the myRewriter class, edit the Main method to look like:&lt;/p&gt;&lt;pre class=&quot;prettyprint lang-cs&quot;&gt; static void Main(string[] args)&lt;br /&gt;        {&lt;br /&gt;            // Create a test Compilation of our current project&lt;br /&gt;            Compilation test = CreateTestCompilation();&lt;br /&gt;&lt;br /&gt;            // Loop on each SyntaxTree in the Compilation&lt;br /&gt;            foreach (SyntaxTree sourceTree in test.SyntaxTrees)&lt;br /&gt;            {&lt;br /&gt;                // Get the tree SemanticModel&lt;br /&gt;                SemanticModel model = test.GetSemanticModel(sourceTree);&lt;br /&gt;                // intialize myRewriter using the tree SemanticModel&lt;br /&gt;                myRewriter rewriter = new myRewriter(model);&lt;br /&gt;                // put our rewriter into action&lt;br /&gt;                SyntaxNode newSource = rewriter.Visit(sourceTree.GetRoot());&lt;br /&gt;&lt;br /&gt;                if (newSource != sourceTree.GetRoot())&lt;br /&gt;                    Console.WriteLine(newSource.GetText().ToString());&lt;br /&gt;                Console.ReadLine();&lt;br /&gt;            }&lt;br /&gt;        }&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;p&gt;Here we create a test &lt;em&gt;Compilation&lt;/em&gt; using CreateTestCompilation method, which we will add soon. We then loop for each &lt;em&gt;SyntaxTree&lt;/em&gt; in this test Compilation. For each SyntaxTree we get the &lt;em&gt;SemanticModel&lt;/em&gt; and pass it to our myRewriter constructor. Then we call the &lt;em&gt;Visit()&lt;/em&gt; method on the SyntaxTree root. This will cause our VisitLocalDeclarationStatement method to be called and do its syntax transformation task. If the new SyntaxTree is different than the old SyntaxTree, this means that we did syntax modifications and we print the new code.&lt;/p&gt;&lt;br /&gt;&lt;p&gt;Now it add the following method to your code inside Program.cs.&lt;/p&gt;&lt;pre class=&quot;prettyprint lang-cs&quot;&gt;private static Compilation CreateTestCompilation()&lt;br /&gt;        {&lt;br /&gt;            SyntaxTree programTree = SyntaxTree.ParseFile(@&quot;..\..\Program.cs&quot;); &lt;br /&gt;            SyntaxTree rewriterTree = SyntaxTree.ParseFile(@&quot;..\..\myRewriter.cs&quot;);&lt;br /&gt;&lt;br /&gt;            List&lt;syntaxtree&gt; sourceTrees = new List&lt;syntaxtree&gt;();&lt;br /&gt;            sourceTrees.Add(programTree);&lt;br /&gt;            sourceTrees.Add(rewriterTree);&lt;br /&gt;&lt;br /&gt;            MetadataReference mscorlib = MetadataReference.CreateAssemblyReference(&quot;mscorlib&quot;);&lt;br /&gt;            MetadataReference roslynCompilers = MetadataReference.CreateAssemblyReference(&quot;Roslyn.Compilers&quot;);&lt;br /&gt;            MetadataReference csCompiler = MetadataReference.CreateAssemblyReference(&quot;Roslyn.Compilers.CSharp&quot;);&lt;br /&gt;&lt;br /&gt;            List&lt;metadatareference&gt; references = new List&lt;metadatareference&gt;();&lt;br /&gt;            references.Add(mscorlib);&lt;br /&gt;            references.Add(roslynCompilers);&lt;br /&gt;            references.Add(csCompiler);&lt;br /&gt;&lt;br /&gt;            return Compilation.Create(&quot;TransformationCS&quot;, null, sourceTrees, references);&lt;br /&gt;&lt;br /&gt;        }&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;p&gt;This method basically creates two &lt;em&gt;SyntaxTree&lt;/em&gt;s of our project code. Then make a list of the required references for these source code files. Then it sum it all in the factory method &lt;em&gt;Compilation.Create()&lt;/em&gt; and return the resulted Compilation object.&lt;/p&gt;&lt;br /&gt;&lt;p&gt;When you run the project, you will see a modified version of the Program.cs file. Notice that our myRewriter class replaced the type used in all variables declarations to be of type &lt;em&gt;var&lt;/em&gt;.&lt;/p&gt;&lt;br /&gt;&lt;p&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiXUCVs_w6NYB1tIy3qbWHlgGzTGn-TIDUPpJHuJhfkcU5bqHTSAlw6gyt1ZnYsF5oX6ta0fdq5Yhz6t67xYIxovK6RJTg6E_hWBtJEpoXaEg39pTrzSsZhRKrZjPb4eqGVBZ4hEG708Q/s1600-h/fileFProjectsRoslynDemo5RoslynDemo5binDebugRoslynDemo5.EXE_2013-08-23_13-28-40%25255B4%25255D.png&quot;&gt;&lt;img style=&quot;background-image: none; border-bottom: 0px; border-left: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top: 0px; border-right: 0px; padding-top: 0px&quot; title=&quot;fileFProjectsRoslynDemo5RoslynDemo5binDebugRoslynDemo5.EXE_2013-08-23_13-28-40&quot; border=&quot;0&quot; alt=&quot;fileFProjectsRoslynDemo5RoslynDemo5binDebugRoslynDemo5.EXE_2013-08-23_13-28-40&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjecm38p6yJ4rvSvjZqrlsw1T0VUAFksT42PdSvpALdp29KePkpeQjP_IxbJQESqKO1GIJEQMYgFSdYwwF3HC-onhkB4oBfeR-6qU4hAlRH6aApq0ZkpXLGibybZkvz2f1G5WH4X9Ij8g/?imgmax=800&quot; width=&quot;566&quot; height=&quot;530&quot;&gt;&lt;/a&gt;&lt;/p&gt;&lt;br /&gt;&lt;p&gt;pressing Enter will bring the modified version of myRewriter.cs file, which have the same kind of change.&lt;/p&gt;&lt;br /&gt;&lt;p&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEg6DzlpmKEKsZO1My-03wFEmonzExZGdKutESfbfXkQ4NkQEmsPigijbX8EvQrqJFWEGFQQMKetHEHz_hhApqtTAAlv-HeROi_GMnAWlRoLULDBIORwSeYqnLUUo0yRxDwFLj7Gy5j3tg/s1600-h/fileFProjectsRoslynDemo5RoslynDemo5binDebugRoslynDemo5.EXE_2013-08-23_17-33-15%25255B4%25255D.png&quot;&gt;&lt;img style=&quot;background-image: none; border-bottom: 0px; border-left: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top: 0px; border-right: 0px; padding-top: 0px&quot; title=&quot;fileFProjectsRoslynDemo5RoslynDemo5binDebugRoslynDemo5.EXE_2013-08-23_17-33-15&quot; border=&quot;0&quot; alt=&quot;fileFProjectsRoslynDemo5RoslynDemo5binDebugRoslynDemo5.EXE_2013-08-23_17-33-15&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEg8_PvcB4HxkkYzafS62Q5tA71r8EsxKd_eEaIoxH6_RAcaZZcf7p_mEJzqCpjwo6wVlydJ3QHolgNAqE5Z-a16XAkLHMixsPYivG2tEU_fJ1omaCutBMnIZ-T6rVlGg5oemmivMfrhEQ/?imgmax=800&quot; width=&quot;579&quot; height=&quot;530&quot;&gt;&lt;/a&gt;&lt;/p&gt;&lt;br /&gt;&lt;br /&gt;&lt;p&gt;We have used the Roslyn Compiler APIs to write our own &lt;em&gt;SyntaxRewriter&lt;/em&gt; that searches all files in a C# project for certain syntactic pattern, analyzes the semantics of source code that matches that pattern, and transforms it. &lt;/p&gt;&lt;br /&gt;&lt;p&gt;Now you can grab a paper and pencil, and start designing the next big thing in refactoring tools industry :)&lt;/p&gt;  </description><link>http://ebeid-soliman.blogspot.com/2013/08/getting-started-with-microsoft-roslyn_9468.html</link><author>noreply@blogger.com (Ebeid Soliman ElSayed)</author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEi1IuLVhZBZ6LN3WoRjDZGQPFsHwpWdJ7PbZ9HyvaszSBrvPu4cfql-tZlZgpJF7BeJzceHf73Kd4NkspNta3iRKCPAfz2PZvyRIEblt9Bw9mFnehW02qiwvBvrArX5cZUvxKwdxuDxhQ/s72-c?imgmax=800" height="72" width="72"/></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-59384554657271185.post-1982455477794956829</guid><pubDate>Thu, 22 Aug 2013 18:11:00 +0000</pubDate><atom:updated>2013-08-27T12:32:08.562-05:00</atom:updated><category domain="http://www.blogger.com/atom/ns#">Microsoft Roslyn</category><category domain="http://www.blogger.com/atom/ns#">Syntax Trees</category><title>Semantic Analysis using Microsoft Roslyn</title><description>&lt;p&gt;In a previous &lt;a title=&quot;Getting Started with Microsoft Rosyln Syntax Analysis&quot; href=&quot;http://ebeid-soliman.blogspot.com/2013/08/getting-started-with-microsoft-roslyn.html&quot; target=&quot;_blank&quot;&gt;post&lt;/a&gt; we talked about using Microsoft Rosyln Syntax API to deal with syntax text in terms of SyntaxTrees and SyntaxNodes. But as we we all know, a single source code or code snippet can’t make a useful program. 99% of the time we end up with many source code files that depend on so many externals: assembly references, namespace imports, or other code files. The meaning (semantic) of SyntaxNodes depend heavily on these externals and may change due changes in these externals even if its enclosing source code file have not been changed.&lt;/p&gt; &lt;p&gt;The &lt;em&gt;Compilation&lt;/em&gt; class help us deal with source text in the context of its dependents and externals. A &lt;em&gt;Compilation&lt;/em&gt; is analogous to a single project as seen by the compiler and represents everything needed to compile a Visual Basic or C# program such as assembly references, compiler options, and the set of source files to be compiled. With this context you can reason about the meaning of code. &lt;em&gt;Compilations&lt;/em&gt; allow you to find &lt;em&gt;Symbols&lt;/em&gt; – entities such as types, namespaces, members, and variables which names and other expressions refer to. The process of associating names and expressions with &lt;em&gt;Symbols&lt;/em&gt; is called &lt;em&gt;Binding&lt;/em&gt;.&lt;/p&gt; &lt;h3&gt;Creating a Compilation&lt;/h3&gt; &lt;p&gt;In this following example we will create a SyntaxTree for our traditional HelloWorld program. Then we created a &lt;em&gt;Compilation&lt;/em&gt; out of this &lt;em&gt;SyntaxTree&lt;/em&gt; and added a reference to MS Core Library. &lt;/p&gt;&lt;pre class=&quot;prettyprint lang-cs&quot;&gt;using System;&lt;br /&gt;using System.Collections.Generic;&lt;br /&gt;using System.Linq;&lt;br /&gt;using System.Text;&lt;br /&gt;using Roslyn.Compilers;&lt;br /&gt;using Roslyn.Compilers.CSharp;&lt;br /&gt;using Roslyn.Services;&lt;br /&gt;using Roslyn.Services.CSharp;&lt;br /&gt;&lt;br /&gt;namespace RoslynDemo3&lt;br /&gt;{&lt;br /&gt;    class Program&lt;br /&gt;    {&lt;br /&gt;        static void Main(string[] args)&lt;br /&gt;        {&lt;br /&gt;            SyntaxTree tree = SyntaxTree.ParseText(&lt;br /&gt;@&quot;using System;&lt;br /&gt;using System.Collections.Generic;&lt;br /&gt;using System.Text;&lt;br /&gt; &lt;br /&gt;namespace HelloWorld&lt;br /&gt;{&lt;br /&gt;    class Program&lt;br /&gt;    {&lt;br /&gt;        static void Main(string[] args)&lt;br /&gt;        {&lt;br /&gt;            Console.WriteLine(&quot;&quot;Hello, World!&quot;&quot;);&lt;br /&gt;        }&lt;br /&gt;    }&lt;br /&gt;}&quot;);&lt;br /&gt;&lt;br /&gt;            var root = (CompilationUnitSyntax)tree.GetRoot();&lt;br /&gt;&lt;br /&gt;            Compilation compilation = Compilation.Create(&quot;HelloWorld&quot;)&lt;br /&gt;                             .AddReferences(MetadataReference.CreateAssemblyReference(&quot;mscorlib&quot;))&lt;br /&gt;                             .AddSyntaxTrees(tree);&lt;br /&gt;&lt;br /&gt;            foreach (MetadataReference reference in compilation.ExternalReferences)&lt;br /&gt;                Console.WriteLine(reference.Display);&lt;br /&gt;&lt;br /&gt;            Console.ReadLine();&lt;br /&gt;        }&lt;br /&gt;    }&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;p&gt;You can supply all the syntax trees, assembly references, and options in one call or you can spread them out over multiple calls. To add the reference we just used the metadata name, which is the same name you find when you add a reference through Visual Studio’s Reference Manager.&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjlG8hl6M60F-RXpALLD15LMJw1rPAUMhBS22zbXU46lr9CHPhbehLnsM-xaGRMj4ngWsjOcfMLWgNjFirA4W4Pc12GfdvL5u4XjLQnn7MQCAjrRBV2V_QWYMIdH5AInCEFJOomG8FhMg/s1600-h/Reference%252520Manager%252520-%252520RoslynDemo3_2013-08-22_09-54-14%25255B4%25255D.png&quot;&gt;&lt;img style=&quot;background-image: none; border-right-width: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px&quot; title=&quot;Reference Manager - RoslynDemo3_2013-08-22_09-54-14&quot; border=&quot;0&quot; alt=&quot;Reference Manager - RoslynDemo3_2013-08-22_09-54-14&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjJ_WRr_RsW749DfhmU_msIzc9caCaENjF4alD0Q75m2Q7aSIEEebgF_EQM3LFa0Td94DkGPSVkrpmeDL0_3TvcSmuj4cnqwuefEVJwIMIGtFOXW6cLZRch48eD7LETDKtEBHdzW3Pm1A/?imgmax=800&quot; width=&quot;472&quot; height=&quot;117&quot;&gt;&lt;/a&gt;&lt;/p&gt;&lt;br /&gt;&lt;p&gt;Now when you run your program, you should get an output similar to the following:&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjPzoBhkHEg9vsk1187IMz6zxAUymR3gibhlaFKMFAeuwAxzU3Vfc613zLKael3WzniaLmDv_HHbyXfAQWw7pOZ2Rp2pPNll3HwjRSgiW3X3heMLEaTszN2tQJHvDCKh7c8Nmv1MdaRxw/s1600-h/FProjectsRoslynDemo3RoslynDemo3binDebugRoslynDemo3.exe_2013-08-22_10-00-45%25255B4%25255D.png&quot;&gt;&lt;img style=&quot;background-image: none; border-right-width: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px&quot; title=&quot;FProjectsRoslynDemo3RoslynDemo3binDebugRoslynDemo3.exe_2013-08-22_10-00-45&quot; border=&quot;0&quot; alt=&quot;FProjectsRoslynDemo3RoslynDemo3binDebugRoslynDemo3.exe_2013-08-22_10-00-45&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEglpjg8gTf8C9rXZHJEDgU7x0lhAlM38ikWQVh4g_QUJHMZ9hkRsVQFca1w4YcVmeYt9QVsm62Q7KusBZdpmgtW6BgtouJBpja1XoIFGYTbzeXts_fOT9jWqqXoAeFkJScWIMNrhqfWTw/?imgmax=800&quot; width=&quot;562&quot; height=&quot;52&quot;&gt;&lt;/a&gt;&lt;/p&gt;&lt;br /&gt;&lt;h3&gt;The SemanticModel&lt;/h3&gt;&lt;br /&gt;&lt;p&gt;Once we have a &lt;em&gt;Compilation&lt;/em&gt; we can get a &lt;em&gt;SemanticModel&lt;/em&gt; for any &lt;em&gt;SyntaxTree&lt;/em&gt; in that &lt;b&gt;&lt;em&gt;Compilation&lt;/em&gt;&lt;/b&gt;. &lt;strong&gt;SemanticModel&lt;/strong&gt;s can be queried to answer questions like “What names are in scope at this location?” “What members are accessible from this method?” “What variables are used in this block of text?” and “What does this name/expression refer to?”&lt;/p&gt;&lt;br /&gt;&lt;p&gt;In the following example we going to modify our example a little bit. We will get the semantic model of our HelloWorld program. Then use this model to get semantic Symbol that represents the first using statement (of type NameSpaceSymbol). Then we use that symbol to get a list of namespaces inside the System namespace.&lt;/p&gt;&lt;pre class=&quot;prettyprint lang-cs&quot;&gt;using System;&lt;br /&gt;using System.Collections.Generic;&lt;br /&gt;using System.Linq;&lt;br /&gt;using System.Text;&lt;br /&gt;using Roslyn.Compilers;&lt;br /&gt;using Roslyn.Compilers.CSharp;&lt;br /&gt;using Roslyn.Services;&lt;br /&gt;using Roslyn.Services.CSharp;&lt;br /&gt;&lt;br /&gt;namespace RoslynDemo3&lt;br /&gt;{&lt;br /&gt;    class Program&lt;br /&gt;    {&lt;br /&gt;        static void Main(string[] args)&lt;br /&gt;        {&lt;br /&gt;            SyntaxTree tree = SyntaxTree.ParseText(&lt;br /&gt;@&quot;using System;&lt;br /&gt;using System.Collections.Generic;&lt;br /&gt;using System.Text;&lt;br /&gt; &lt;br /&gt;namespace HelloWorld&lt;br /&gt;{&lt;br /&gt;    class Program&lt;br /&gt;    {&lt;br /&gt;        static void Main(string[] args)&lt;br /&gt;        {&lt;br /&gt;            Console.WriteLine(&quot;&quot;Hello, World!&quot;&quot;);&lt;br /&gt;        }&lt;br /&gt;    }&lt;br /&gt;}&quot;);&lt;br /&gt;&lt;br /&gt;            var root = (CompilationUnitSyntax)tree.GetRoot();&lt;br /&gt;&lt;br /&gt;            Compilation compilation = Compilation.Create(&quot;HelloWorld&quot;)&lt;br /&gt;                             .AddReferences(MetadataReference.CreateAssemblyReference(&quot;mscorlib&quot;))&lt;br /&gt;                             .AddSyntaxTrees(tree);&lt;br /&gt;&lt;br /&gt;            var model = compilation.GetSemanticModel(tree);&lt;br /&gt;            var nameInfo = model.GetSymbolInfo(root.Usings[0].Name);&lt;br /&gt;            var systemSymbol = (NamespaceSymbol)nameInfo.Symbol;&lt;br /&gt;&lt;br /&gt;            foreach (var ns in systemSymbol.GetNamespaceMembers())&lt;br /&gt;                Console.WriteLine(ns.Name);&lt;br /&gt;            Console.ReadLine();&lt;br /&gt;        }&lt;br /&gt;    }&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;p&gt;When you run the above code you should get an output like the following:&lt;/p&gt;&lt;br /&gt;&lt;p&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhTS_Ac9CuyMjQsXKPpshENFEuFMrKfJdpXoBNVNVwcly0lMEMH6L7at4-2vnJHDhf_YMYhqSrG6-Sl7OYrhcyKlfwId4NgNW5gjGgZNoeOIyNxThQR_aVVK-Ni4pTOXOcuf57hSmIJ3g/s1600-h/FProjectsRoslynDemo3RoslynDemo3binDebugRoslynDemo3.exe_2013-08-22_13-23-45%25255B2%25255D.png&quot;&gt;&lt;img style=&quot;background-image: none; border-right-width: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px&quot; title=&quot;FProjectsRoslynDemo3RoslynDemo3binDebugRoslynDemo3.exe_2013-08-22_13-23-45&quot; border=&quot;0&quot; alt=&quot;FProjectsRoslynDemo3RoslynDemo3binDebugRoslynDemo3.exe_2013-08-22_13-23-45&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjRKVQdEUyjjXns7R1IFFR2-bleHREUsESwW5Dzs9VHVCi9DARW4VaBwU_lz-AKljxT0wyjVhpdFHQTVC2AND-ddsz2YQPCX26xCNW6fpiFlh7wSfJ1Jo12dbDYDdlyV1c17hSSk1atVA/?imgmax=800&quot; width=&quot;123&quot; height=&quot;196&quot;&gt;&lt;/a&gt;&lt;/p&gt;&lt;br /&gt;&lt;p&gt;You can also use the query methods we showed in the previous &lt;a title=&quot;Getting started with Microsoft Roslyn Syntax Analysis&quot; href=&quot;http://ebeid-soliman.blogspot.com/2013/08/getting-started-with-microsoft-roslyn.html&quot; target=&quot;_blank&quot;&gt;post&lt;/a&gt; to retrieve a certain node and then use the semantic model to get more information about that node. You could use the code below to get the node that represent the “Hello, World!” string in our code snippet, get information about its symbol type (System.String) , and even get information about the assembly that contains this type.&lt;/p&gt;&lt;pre class=&quot;prettyprint lang-cs&quot;&gt;            var helloWorldString = root.DescendantNodes()&lt;br /&gt;                                       .OfType&lt;literalexpressionsyntax&gt;()&lt;br /&gt;                                       .First();&lt;br /&gt;            var literalInfo = model.GetTypeInfo(helloWorldString);&lt;br /&gt;            Console.WriteLine(literalInfo.Type.ContainingAssembly.BaseName);&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;p&gt;or enumerate the public methods of the &lt;em&gt;System.String&lt;/em&gt; class&lt;/p&gt;&lt;pre class=&quot;prettyprint lang-cs&quot;&gt;            var stringTypeSymbol = (NamedTypeSymbol)literalInfo.Type;&lt;br /&gt; &lt;br /&gt;            Console.Clear();&lt;br /&gt;            foreach (var name in (from method in stringTypeSymbol.GetMembers()&lt;br /&gt;                                                              .OfType&lt;methodsymbol&gt;()&lt;br /&gt;                               where method.ReturnType == stringTypeSymbol &amp;amp;&amp;amp;&lt;br /&gt;                                     method.DeclaredAccessibility == &lt;br /&gt;                                                Accessibility.Public&lt;br /&gt;                               select method.Name).Distinct())&lt;br /&gt;            {&lt;br /&gt;                Console.WriteLine(name);&lt;br /&gt;            }&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;p&gt;Somehow, we just scratched the surface of sematic analysis in this post. using both syntax and semantic analysis we can do more advanced and meaningful code focused tasks (which we will do in the next post).&lt;/p&gt;  </description><link>http://ebeid-soliman.blogspot.com/2013/08/getting-started-with-microsoft-roslyn_22.html</link><author>noreply@blogger.com (Ebeid Soliman ElSayed)</author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjJ_WRr_RsW749DfhmU_msIzc9caCaENjF4alD0Q75m2Q7aSIEEebgF_EQM3LFa0Td94DkGPSVkrpmeDL0_3TvcSmuj4cnqwuefEVJwIMIGtFOXW6cLZRch48eD7LETDKtEBHdzW3Pm1A/s72-c?imgmax=800" height="72" width="72"/></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-59384554657271185.post-8492979314992483465</guid><pubDate>Tue, 20 Aug 2013 20:49:00 +0000</pubDate><atom:updated>2013-08-27T12:32:23.977-05:00</atom:updated><category domain="http://www.blogger.com/atom/ns#">Compilers</category><category domain="http://www.blogger.com/atom/ns#">Microsoft Roslyn</category><category domain="http://www.blogger.com/atom/ns#">Syntax Trees</category><title>Syntax Analysis using Microsoft Roslyn</title><description>&lt;p&gt;In a previous &lt;a href=&quot;http://ebeid-soliman.blogspot.com/2013/08/overview-of-microsoft-roslyn-first.html&quot; target=&quot;_blank&quot;&gt;post&lt;/a&gt; we talked about Microsoft &lt;a title=&quot;Microsoft&amp;reg; &amp;ldquo;Roslyn&amp;rdquo; CTP&quot; href=&quot;http://msdn.microsoft.com/en-us/vstudio/roslyn.aspx&quot; target=&quot;_blank&quot;&gt;Roslyn&lt;/a&gt;. In this post will get our hands dirty with Roslyn syntax analysis in order to develop our first code-focused program. We will see how the SyntaxTree of HelloWorld program look like and how we can traverse and query it.&lt;/p&gt; &lt;p&gt;The&lt;b&gt; Syntax API&lt;/b&gt; exposes the syntax trees the compilers use to understand Visual Basic and C# programs. They are produced by the same parser that runs when a project is built or a developer hits F5. The four primary building blocks of syntax trees are:&lt;/p&gt; &lt;ul&gt; &lt;li&gt;The &lt;b&gt;SyntaxTree&lt;/b&gt; class, an instance of which represents an entire parse tree.  &lt;li&gt;The &lt;b&gt;SyntaxNode&lt;/b&gt; class, instances of which represent syntactic constructs such as declarations, statements, clauses, and expressions.  &lt;li&gt;The &lt;b&gt;SyntaxToken&lt;/b&gt; structure, which represents an individual keyword, identifier, operator, or punctuation.  &lt;li&gt;And lastly the &lt;b&gt;SyntaxTrivia&lt;/b&gt; structure, which represents syntactically insignificant bits of information such as the whitespace between tokens, preprocessor directives, and comments.&lt;/li&gt;&lt;/ul&gt; &lt;h3&gt;Traversing Syntax Trees&lt;/h3&gt; &lt;p&gt;First, download Microsoft Roslyn CTP from &lt;a title=&quot;Microsoft Download Center&quot; href=&quot;http://www.microsoft.com/en-us/download/details.aspx?id=34685&quot; target=&quot;_blank&quot;&gt;here&lt;/a&gt;. and Install it.You will need &lt;a href=&quot;http://go.microsoft.com/fwlink/?linkid=255983&quot; target=&quot;_blank&quot;&gt;Visual Studio 2012&lt;/a&gt; and &lt;a href=&quot;http://go.microsoft.com/?linkid=9810482&quot; target=&quot;_blank&quot;&gt;Visual Studio 2012 SDK&lt;/a&gt; in order to install Roslyn.&lt;/p&gt; &lt;p&gt;Now open your Visual Studio 2012 and create a new Console Application project. Add the following to your project references&lt;/p&gt; &lt;h3&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEguF3b9tYuwvwMfE2vvp0KL_YIaq28_oor3VHGE7dlU3UGcMMoH52QSpU273WVOwLpnNj9V76tT-PTIPqq086kh_xgD-Z8VnpYmEr0PoyFErG3tuOkVvs9UFYbZjtb3H2yaCQPtIs1X_w/s1600-h/Reference%252520Manager%252520-%252520RoslynDemo1_2013-08-19_15-25-47%25255B3%25255D.png&quot;&gt;&lt;img style=&quot;background-image: none; border-right-width: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px&quot; title=&quot;Reference Manager - RoslynDemo1_2013-08-19_15-25-47&quot; border=&quot;0&quot; alt=&quot;Reference Manager - RoslynDemo1_2013-08-19_15-25-47&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiL9nDDypBvR5aSH1yTHC9Pg3qUBmyuZzoESTX0ZAIRt3duLZnUat27I7JSoH00lZrBBLWkfuk49i6BmlzT_bMFmrD6bs_Y5iS0BFknDpw5SxTl3rsRsM5ymOfyRYc3S-8xCxTuejZgPg/?imgmax=800&quot; width=&quot;525&quot; height=&quot;215&quot;&gt;&lt;/a&gt; &lt;/h3&gt; &lt;p&gt;Now edit your code to look like:&lt;/p&gt;&lt;pre class=&quot;prettyprint lang-cs&quot;&gt;using System;&lt;br /&gt;using System;&lt;br /&gt;using Roslyn.Compilers;&lt;br /&gt;using Roslyn.Compilers.CSharp;&lt;br /&gt;&lt;br /&gt;namespace RoslynDemo1&lt;br /&gt;{&lt;br /&gt;    class Program&lt;br /&gt;    {&lt;br /&gt;        static void Main(string[] args)&lt;br /&gt;        {&lt;br /&gt;            SyntaxTree tree = SyntaxTree.ParseText(&lt;br /&gt;                @&quot;using System;&lt;br /&gt; &lt;br /&gt;                namespace HelloWorld&lt;br /&gt;                {&lt;br /&gt;                    class Program&lt;br /&gt;                    {&lt;br /&gt;                        static void Main(string[] args)&lt;br /&gt;                        {&lt;br /&gt;                            Console.WriteLine(&quot;&quot;Hello, World!&quot;&quot;);&lt;br /&gt;                        }&lt;br /&gt;                    }&lt;br /&gt;                }&quot;);&lt;br /&gt;&lt;br /&gt;            foreach (SyntaxNode node in tree.GetRoot().ChildNodesAndTokens())&lt;br /&gt;                PrintSyntaxTree(node);&lt;br /&gt;&lt;br /&gt;            Console.ReadLine();&lt;br /&gt;        }&lt;br /&gt;        static void PrintSyntaxTree(SyntaxNode node)&lt;br /&gt;        {&lt;br /&gt;            if (node != null)&lt;br /&gt;            {&lt;br /&gt;                Console.WriteLine(node.Kind + &quot; | &quot; + node.ToString());&lt;br /&gt;                foreach (SyntaxNode child in node.ChildNodes())&lt;br /&gt;                    PrintSyntaxTree(child);&lt;br /&gt;            }&lt;br /&gt;        }&lt;br /&gt;    }&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;p&gt;Now, run our program. You should see an output similar to the following:&lt;/p&gt;&lt;br /&gt;&lt;p&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEg_fDDkBlx8mZ1LzZrcbJnWI2uoiFbiado1WAKA5ANgDVa29kpNv7XeX2SoBAfgm87xd1Wq1Qy32an7ZqqkLVH2QBTYeVUN2D8CcbmJundWElkJ-aBjopSP6s3-27gcUb7zGTFUkIC6tw/s1600-h/fileFProjectsRoslynDemo1RoslynDemo1binDebugRoslynDemo1.EXE_2013-08-20_15-24-06%25255B3%25255D.png&quot;&gt;&lt;img style=&quot;background-image: none; border-right-width: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px&quot; title=&quot;fileFProjectsRoslynDemo1RoslynDemo1binDebugRoslynDemo1.EXE_2013-08-20_15-24-06&quot; border=&quot;0&quot; alt=&quot;fileFProjectsRoslynDemo1RoslynDemo1binDebugRoslynDemo1.EXE_2013-08-20_15-24-06&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEikuHdEXKinbsZYxeFu1woRzzw1Y2mgnsg1oHgJ8l5h8j7QIqB49kUneQ4EcqDqomKsWYfyT4fetvKqJi0CO7wRfCtYL4mRyfHAOMjJs0aQ8iXtQeB8f929sckmpAgwFFeiBvW668PPfw/?imgmax=800&quot; width=&quot;397&quot; height=&quot;405&quot;&gt;&lt;/a&gt;&lt;/p&gt;&lt;br /&gt;&lt;p&gt;Now let’s explain what we already did. First, we included the needed namespaces. The common Syntax APIs are found in the Roslyn.Compilers and the Roslyn.Compilers.Common namespace, while the language specific Syntax APIs are found in Roslyn.Compilers.CSharp and Roslyn.Compilers.VisualBasic.&lt;/p&gt;&lt;br /&gt;&lt;p&gt;Second, we tried to get a syntax tree corresponding to our HelloWorld program using the &lt;em&gt;SyntaxTree.ParseText&lt;/em&gt; function, which produces a syntax tree by parsing the passed source code.&lt;/p&gt;&lt;br /&gt;&lt;p&gt;Third, in order to traverse the syntax tree we get its root, then get its child nodes. Then loop on these child nodes and their children recursively to print its kind and the string representation. C# node kind is on of the kinds in enum &lt;em&gt;Roslyn.Compilers.CSharp.SymbolKind&lt;/em&gt;.&lt;/p&gt;&lt;br /&gt;&lt;p&gt;Inside the PrintSyntaxTree method, by playing in the order of node printing and the recursive call, you can apply your tree traversal logic. You can also inspect specific elements of the tree:&lt;/p&gt;&lt;pre class=&quot;prettyprint lang-cs&quot;&gt;var root = (CompilationUnitSyntax)tree.GetRoot(); &lt;br /&gt;var helloWorldDeclaration = (NamespaceDeclarationSyntax)root.Members[0];&lt;br /&gt;var programDeclaration = (TypeDeclarationSyntax)helloWorldDeclaration.Members[0];&lt;br /&gt;var mainDeclaration = (MethodDeclarationSyntax)programDeclaration.Members[0];&lt;br /&gt;var argsParameter = mainDeclaration.ParameterList.Parameters[0];&lt;br /&gt;Console.WriteLine(argsParameter.ToString() );&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;h3&gt;Query Methods&lt;/h3&gt;&lt;br /&gt;&lt;p&gt;In addition to traversing syntax trees you can also explore the syntax tree using the query methods defined on &lt;em&gt;SyntaxNode&lt;/em&gt;. These methods are similar to XPath. You can also use these methods with LINQ to quickly find things in a tree. For example, the following statements uses a LINQ expression and the &lt;b&gt;DescendantNodes&lt;/b&gt; method to locate the same parameter as in the previous example:&lt;/p&gt;&lt;pre class=&quot;prettyprint lang-cs&quot;&gt;            var firstParameters = from methodDeclaration in root.DescendantNodes()&lt;br /&gt;                                                    .OfType&lt;methoddeclarationsyntax&gt;()&lt;br /&gt;                                  where methodDeclaration.Identifier.ValueText == &quot;Main&quot;&lt;br /&gt;                                  select methodDeclaration.ParameterList.Parameters.First();&lt;br /&gt;&lt;br /&gt;            var argsParameter2 = firstParameters.Single();&lt;br /&gt;            Console.WriteLine(argsParameter2.ToString());&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;h3&gt;SyntaxWalkers&lt;/h3&gt;&lt;br /&gt;&lt;p&gt;If you want to find all nodes of a specific type in a syntax tree, for example, every property declaration in a file, you can do that by extending the &lt;em&gt;SyntaxWalker&lt;/em&gt; class and overriding the &lt;em&gt;VisitPropertyDeclaration&lt;/em&gt;&lt;strong&gt; &lt;/strong&gt;method, you can process every property declaration in a syntax tree without knowing its structure beforehand.&lt;/p&gt;&lt;br /&gt;&lt;p&gt;Now let’s implement, as an example, a SyntaxWalker that examines the entire syntax tree and collects any using directives it find which aren’t importing a System namespace.&lt;/p&gt;&lt;br /&gt;&lt;p&gt;Create a new C# Console application and edit it to look like:&lt;/p&gt;&lt;pre class=&quot;prettyprint lang-cs&quot;&gt;using System;&lt;br /&gt;using Roslyn.Compilers;&lt;br /&gt;using Roslyn.Compilers.CSharp;&lt;br /&gt;&lt;br /&gt;namespace RoslynDemo2&lt;br /&gt;{&lt;br /&gt;    class Program&lt;br /&gt;    {&lt;br /&gt;        static void Main(string[] args)&lt;br /&gt;        {&lt;br /&gt;            SyntaxTree tree = SyntaxTree.ParseText(&lt;br /&gt;@&quot;using System;&lt;br /&gt;using System.Collections.Generic;&lt;br /&gt;using System.Linq;&lt;br /&gt;using System.Text;&lt;br /&gt;using Roslyn.Compilers;&lt;br /&gt;using Roslyn.Compilers.CSharp;&lt;br /&gt; &lt;br /&gt;namespace TopLevel&lt;br /&gt;{&lt;br /&gt;    using Microsoft;&lt;br /&gt;    using System.ComponentModel;&lt;br /&gt; &lt;br /&gt;    namespace Child1&lt;br /&gt;    {&lt;br /&gt;        using Microsoft.Win32;&lt;br /&gt;        using System.Runtime.InteropServices;&lt;br /&gt; &lt;br /&gt;        class Foo { }&lt;br /&gt;    }&lt;br /&gt; &lt;br /&gt;    namespace Child2&lt;br /&gt;    {&lt;br /&gt;        using System.CodeDom;&lt;br /&gt;        using Microsoft.CSharp;&lt;br /&gt; &lt;br /&gt;        class Bar { }&lt;br /&gt;    }&lt;br /&gt;}&quot;);&lt;br /&gt;&lt;br /&gt;            var root = (CompilationUnitSyntax)tree.GetRoot();&lt;br /&gt;        }&lt;br /&gt;    }&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;p&gt;As you noticed, this source text contains &lt;b&gt;using&lt;/b&gt; directives scattered across four different locations: the file-level, in the top-level namespace, and in the two nested namespaces.&lt;/p&gt;&lt;br /&gt;&lt;p&gt;Now, add a new class to your project and edit it to look like the next code. Basically we inherit from the &lt;em&gt;SyntaxWalker&lt;/em&gt; class, and over the &lt;em&gt;VisitUsingDirective&lt;/em&gt; method. This method is called by &lt;em&gt;Visit&lt;/em&gt; method, which recursively visits a node and each of its children. VisitUsingDirective method is called for using directives only, inside it we collect the namespaces that starts with “System.” but not equal to “System”.&lt;/p&gt;&lt;pre class=&quot;prettyprint lang-cs&quot;&gt;using System;&lt;br /&gt;using System.Collections.Generic;&lt;br /&gt;using System.Linq;&lt;br /&gt;using System.Text;&lt;br /&gt;using Roslyn.Compilers;&lt;br /&gt;using Roslyn.Compilers.CSharp;&lt;br /&gt;&lt;br /&gt;namespace RoslynDemo2&lt;br /&gt;{&lt;br /&gt;    class myWalker : SyntaxWalker   &lt;br /&gt;    {&lt;br /&gt;        public readonly List&lt;usingdirectivesyntax&gt; Usings = new List&lt;usingdirectivesyntax&gt;();&lt;br /&gt;&lt;br /&gt;        public override void VisitUsingDirective(UsingDirectiveSyntax node)&lt;br /&gt;        {&lt;br /&gt;            if (node.Name.GetText().ToString() != &quot;System&quot; &amp;amp;&amp;amp;&lt;br /&gt;                !node.Name.GetText().ToString().StartsWith(&quot;System.&quot;))&lt;br /&gt;            {&lt;br /&gt;                this.Usings.Add(node);&lt;br /&gt;            }&lt;br /&gt;        }&lt;br /&gt;    }&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;p&gt;Now let’s go back to the &lt;em&gt;Main&lt;/em&gt; method and use our walker by adding the following code snippet to the end of Main method. Basically it passes the syntax tree root to &lt;em&gt;myWalker.Visit&lt;/em&gt; method, which internally call the &lt;em&gt;VisitUsingDirective &lt;/em&gt;method. Then we loop and print the collected usings.&lt;/p&gt;&lt;br /&gt;&lt;p&gt;When you run your program, you should see an output similar to the following:&lt;/p&gt;&lt;br /&gt;&lt;p&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEi3ztSpRMD3_GkKRYHcGryLCG7GEycYoRG5Wz_aAc9trP70ARPdfoJaqR_oBWGEUfL5L5scp3IaPLsi7OQNpXNITdtrgavbHalryjMursMWvZasSyjo9zdqn_8I_GzZxJC9e9VkiWHGLg/s1600-h/fileFProjectsRoslynDemo2RoslynDemo2binDebugRoslynDemo2.EXE_2013-08-21_14-30-03%25255B2%25255D.png&quot;&gt;&lt;img style=&quot;background-image: none; border-bottom: 0px; border-left: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top: 0px; border-right: 0px; padding-top: 0px&quot; title=&quot;fileFProjectsRoslynDemo2RoslynDemo2binDebugRoslynDemo2.EXE_2013-08-21_14-30-03&quot; border=&quot;0&quot; alt=&quot;fileFProjectsRoslynDemo2RoslynDemo2binDebugRoslynDemo2.EXE_2013-08-21_14-30-03&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEj0j45bLI4Z8n9mrb59ZvyvAN1j0-7orNy-yiZsj1XCwcEUudYUSKrjQAr8hivQuBVfK45SOcHmP9E0gC-s9CD_SYEQuuEgZjhXj2mj_uNMlVfPEdnEYl4et7-8nMsJxveVea0IGO59KQ/?imgmax=800&quot; width=&quot;199&quot; height=&quot;76&quot;&gt;&lt;/a&gt;&lt;/p&gt;&lt;br /&gt;&lt;p&gt;In this post we gave a quick example about obtaining a SyntaxTree of HelloWorld program and explored its nodes. We also built a SyntaxWalker that walk the syntax tree and collect the nodes of our interest only. Later we will see how to fully manipulate SyntaxNodes and SyntaxTrees.&lt;/p&gt;  </description><link>http://ebeid-soliman.blogspot.com/2013/08/getting-started-with-microsoft-roslyn.html</link><author>noreply@blogger.com (Ebeid Soliman ElSayed)</author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiL9nDDypBvR5aSH1yTHC9Pg3qUBmyuZzoESTX0ZAIRt3duLZnUat27I7JSoH00lZrBBLWkfuk49i6BmlzT_bMFmrD6bs_Y5iS0BFknDpw5SxTl3rsRsM5ymOfyRYc3S-8xCxTuejZgPg/s72-c?imgmax=800" height="72" width="72"/></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-59384554657271185.post-2040788486976081351</guid><pubDate>Tue, 20 Aug 2013 02:00:00 +0000</pubDate><atom:updated>2013-08-19T14:46:24.964-05:00</atom:updated><category domain="http://www.blogger.com/atom/ns#">Compilers</category><category domain="http://www.blogger.com/atom/ns#">Microsoft Roslyn</category><category domain="http://www.blogger.com/atom/ns#">Syntax Trees</category><title>Overview of Microsoft Roslyn – The first compiler-as-service product.</title><description>&lt;h3&gt;Introduction&lt;/h3&gt; &lt;p&gt;From developer perspective, compilers are black boxes -- source code goes in one end, magic happens in the middle, and object files or assemblies come out the other end. During their job, compilers build up a deep understanding of our code. For decades this valuable information was unreachable.&lt;/p&gt; &lt;p&gt;The &lt;a title=&quot;Microsoft&amp;reg; &amp;ldquo;Roslyn&amp;rdquo; CTP&quot; href=&quot;http://msdn.microsoft.com/en-us/vstudio/roslyn.aspx&quot; target=&quot;_blank&quot;&gt;Roslyn project&lt;/a&gt; aims to open compilers for developers and offer it as services. Through Roslyn, compilers become services with APIs that can be used for code related tasks in your tools and applications.&lt;/p&gt; &lt;p&gt;In order to understand the APIs that Roslyn offers, we need to understand the general compiler phases:&lt;/p&gt; &lt;ol&gt; &lt;li&gt;&lt;strong&gt;The parse phase&lt;/strong&gt; where source is tokenized and parsed into syntax that follows the language grammar.  &lt;li&gt;&lt;strong&gt;The declaration phase&lt;/strong&gt; where declarations from source and imported metadata are analyzed to form named symbols.  &lt;li&gt;&lt;strong&gt;The binding phase&lt;/strong&gt; where identifiers in the code are matched to symbols.  &lt;li&gt;&lt;strong&gt;The emitting phase&lt;/strong&gt; where all the information built up by the compiler is emitted as an assembly.&lt;/li&gt;&lt;/ol&gt; &lt;p&gt;For each phase of these phases, Roslyn provides a set of APIs to access its services and an object model that allow access to the information at that phase. &lt;/p&gt; &lt;ol&gt; &lt;li&gt;The parsing phase is exposed as a syntax tree  &lt;li&gt;The declaration phase as a hierarchical symbol table  &lt;li&gt;The binding phase as a model that exposes the result of the compiler’s semantic analysis  &lt;li&gt;The emit phase as an API that produces IL byte codes.&lt;/li&gt;&lt;/ol&gt; &lt;p&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjjkcQZnD8Dr-ke1q3pSIVNaumaJyVFZJyDSB0wnuEkCste7jPWkqlfCCIVzffoNUDCBxpkpJVZMPElFzVhcyMhaFTQdOjdgJjupq4dvKg1Mt8lxGs2LHYlIf9nmA0hjv2HVOpwHYa-sQ/s1600-h/image%25255B1%25255D.png&quot;&gt;&lt;img style=&quot;background-image: none; border-bottom: 0px; border-left: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top: 0px; border-right: 0px; padding-top: 0px&quot; title=&quot;image&quot; border=&quot;0&quot; alt=&quot;image&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEigm8ZflgjuRBH1fUhjMnrEHnWS72bZ2o52_i1qSCd_5ayccne6K7S4ZB1rxGbGqPPBPiCH2-tawEhu0qNNoT8A-CJ9tdYWPPUEhgEobj7HADy9J_6FBHvrZHkjk7Vd6jbs_EbE_oMuqg/?imgmax=800&quot; width=&quot;608&quot; height=&quot;330&quot;&gt;&lt;/a&gt;&lt;/p&gt; &lt;h3&gt;Rosyln API Layers&lt;/h3&gt; &lt;p&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgLXgjHPvpjAwJ71PbPYlppU-cAkqGPT6i8jV8uEve50At3ahH3LV_TDoonQVm4aMInGsRrfoR0vcYAFHvhnBT2sEnNYla8mDnmTNEajMrbAQbZd8Zoc1A1uvIm0AOhPJOfMVZ6GDjoOw/s1600-h/image%25255B13%25255D.png&quot;&gt;&lt;img style=&quot;background-image: none; border-right-width: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px&quot; title=&quot;image&quot; border=&quot;0&quot; alt=&quot;image&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhocT_STU2BmUA5tHTHJ0DBoEDaMeeJJ26pCqV6Il1TY1a_UObJCdP0nFf96U7NEEQoA8UcOJf9D-JNg0JWyJkhpFW7b9CGvoYnhlejrXvWHehntiZTnmMIN599lE0jqcbNJKaDcGTQ5Q/?imgmax=800&quot; width=&quot;344&quot; height=&quot;90&quot;&gt;&lt;/a&gt;&lt;/p&gt; &lt;ol&gt; &lt;li&gt;&lt;strong&gt;Compiler APIs&lt;/strong&gt; contains a representation of a single invocation of a compiler (including assembly references, compiler options, and source code files) which provides the object models that corresponds to the compiler pahases.  &lt;ol&gt; &lt;li&gt;&lt;strong&gt;Scripting APIs&lt;/strong&gt; represents a runtime execution context for C# or VB piece of code. It contains a scripting engine that allows evaluation of expressions and statements as top-level constructs in programs.&lt;/li&gt;&lt;/ol&gt; &lt;li&gt;&lt;strong&gt;Services APIs&lt;/strong&gt; represents the starting point for doing code analysis and refactoring over entire solutions by organizing all the information about the projects in a solution into single object model, offering you direct access to the compiler layer object models without needing to parse files, configure options or manage project to project dependencies. In addition, the services layer surfaces a set of commonly used APIs used when implementing code analysis and refactoring tools that function &lt;em&gt;within a host environment&lt;/em&gt; like the Visual Studio IDE.  &lt;li&gt;&lt;strong&gt;Editor Services APIs&lt;/strong&gt; allows a user to easily extend Visual Studio IDE features (such as IntelliSense, refactorings, and code formatting). This layer has a dependency on the Visual Studio text editor and the Visual Studio software development kit (SDK).&lt;/li&gt;&lt;/ol&gt; &lt;h3&gt;Working with Syntax&lt;/h3&gt; &lt;p&gt;The fundamental data structure exposed by the Compiler APIs is the syntax tree. It represents the lexical and syntactic structure of source code, No part of the source code is understood without it first being identified. These trees enable tools to manipulate source code without editing it as text.&lt;/p&gt; &lt;h4&gt;Syntax Trees Attributes&lt;/h4&gt; &lt;p&gt;Syntax trees have three key attributes: &lt;/p&gt; &lt;ol&gt; &lt;li&gt;&lt;strong&gt;Full fidelity &lt;/strong&gt;which means that the syntax tree contains every piece of information found in the source text, every grammatical construct, every lexical token, and everything else in between including whitespace, comments, and preprocessor directives.  &lt;li&gt;&lt;strong&gt;Round-trippable&lt;/strong&gt; which means that it can be traced back to the text it was parsed from and get the text representation of the sub-tree rooted at that node. This means that syntax trees can be used as a way to construct and edit source text. By creating a tree you have by implication created the equivalent source code, and by editing a syntax tree, making a new tree out of changes to an existing tree, you have effectively edited the source code.  &lt;li&gt;&lt;strong&gt;Immutable and thread-safe which&lt;/strong&gt; means that after a tree is obtained, it is a snapshot of the current state of the code, and never changes. This allows multiple users to interact with the same syntax tree at the same time in different threads without locking or duplication. &lt;/li&gt;&lt;/ol&gt; &lt;h4&gt;Syntax Tree Elements&lt;/h4&gt; &lt;p&gt;Each syntax tree is made up of &lt;i&gt;nodes, tokens,&lt;/i&gt; and &lt;i&gt;trivia.&lt;/i&gt;&lt;/p&gt; &lt;ul&gt; &lt;li&gt;&lt;strong&gt;Syntax Nodes&lt;/strong&gt;: the primary elements of syntax trees. It represent syntactic constructs such as declarations, statements, clauses, and expressions. They are non-terminal nodes in the syntax tree, which means they always have other nodes and tokens as children. Each category of syntax nodes is represented by a separate class derived from &lt;em&gt;SyntaxNode&lt;/em&gt;. &lt;/li&gt; &lt;ul&gt; &lt;li&gt;&lt;em&gt;Parent&lt;/em&gt; property returns the node parent. &lt;li&gt;&lt;em&gt;ChildNodes()&lt;/em&gt; returns a list of child nodes in sequential order based on its position in the source text. This list does not contain tokens. &lt;li&gt;&lt;em&gt;DescendantNodes(), DescendantTokens(), and DescendantTrivia()&lt;/em&gt; returns a list of child nodes in sequential order based on its position in the source text. &lt;li&gt;Each syntax node subclass exposes all the same children through strongly typed properties.&lt;/li&gt; &lt;ul&gt; &lt;li&gt;&lt;em&gt;BinaryExpressionSyntax&lt;/em&gt; node class&lt;/li&gt; &lt;ul&gt; &lt;li&gt;Property &lt;em&gt;Left/Right&lt;/em&gt; of type &lt;em&gt;ExpressionSyntax&lt;/em&gt; &lt;li&gt;Property &lt;em&gt;OperatorToken &lt;/em&gt;of type &lt;em&gt;SyntaxToken&lt;/em&gt;&lt;/li&gt;&lt;/ul&gt; &lt;li&gt;IfStatementSyntax node class&lt;/li&gt; &lt;ul&gt; &lt;li&gt;Optional property &lt;em&gt;ElseClauseSyntax&lt;/em&gt; which returns null if the child is not present.&lt;/li&gt;&lt;/ul&gt;&lt;/ul&gt;&lt;/ul&gt; &lt;li&gt;&lt;strong&gt;Syntax Tokens&lt;/strong&gt; are the terminals of the language grammar, representing the smallest syntactic fragments of the code. They are never parents of other nodes or tokens. Syntax tokens consist of keywords, identifiers, literals, and punctuation. &lt;li&gt;&lt;strong&gt;Syntax Trivia&lt;/strong&gt; represent the parts of the source text that are largely insignificant for normal understanding of the code, such as whitespace, comments, and preprocessor directives. Because trivia are not part of the normal language syntax and can appear anywhere between any two tokens, they are not included in the syntax tree as a child of a node. you can access them through token’s &lt;em&gt;LeadingTrivia&lt;/em&gt; or &lt;em&gt;TrailingTrivia&lt;/em&gt; collections. &lt;li&gt;&lt;strong&gt;Spans&lt;/strong&gt; In order to make each node knows its position within the source text, each node has two properties of type &lt;em&gt;TextSpan&lt;/em&gt;. A TextSpan object is the beginning position and a count of characters, both represented as integers. Each node has two TextSpan properties:&lt;/li&gt; &lt;ul&gt; &lt;li&gt;The &lt;em&gt;Span&lt;/em&gt; property is the text span from the start of the first token in the node’s sub-tree to the end of the last token. This span does not include any leading or trailing trivia. &lt;li&gt;The &lt;em&gt;FullSpan&lt;/em&gt; property is the text span that includes the node’s normal span, plus the span of any leading or trailing trivia.&lt;/li&gt;&lt;/ul&gt; &lt;li&gt;&lt;strong&gt;Kinds&lt;/strong&gt; Each node, token, or trivia has a &lt;em&gt;Kind&lt;/em&gt; property, of type &lt;em&gt;SyntaxKind&lt;/em&gt;, that identifies the exact syntax element represented. The Kind property allows for easy disambiguation of syntax node types that share the same node class. &lt;li&gt;&lt;strong&gt;Errors&lt;/strong&gt; When the parser encounters code that does not conform to the defined syntax of the language, it uses one of two techniques to create a syntax tree.&lt;/li&gt; &lt;ul&gt; &lt;li&gt;If the parser expects a particular kind of token, but does not find it, it may insert a &lt;i&gt;missing token&lt;/i&gt; into the syntax tree in the location that the token was expected. A missing token represents the actual token that was expected, but it has an empty span, and its &lt;em&gt;IsMissing&lt;/em&gt; property returns true. &lt;li&gt;The parser may skip tokens until it finds one where it can continue parsing. In this case, the skipped tokens that were skipped are attached as a trivia node with the kind &lt;em&gt;SkippedTokens&lt;/em&gt;. &lt;/li&gt;&lt;/ul&gt;&lt;/ul&gt; &lt;p&gt;In this post we explored Microsoft Roslyn, an interesting product that offer the compiler as a service and opens a lot of doors in front of developers to develop code-focused tools and applications. In later posts we will gradually show Roslyn in action.&lt;/p&gt;  </description><link>http://ebeid-soliman.blogspot.com/2013/08/overview-of-microsoft-roslyn-first.html</link><author>noreply@blogger.com (Ebeid Soliman ElSayed)</author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEigm8ZflgjuRBH1fUhjMnrEHnWS72bZ2o52_i1qSCd_5ayccne6K7S4ZB1rxGbGqPPBPiCH2-tawEhu0qNNoT8A-CJ9tdYWPPUEhgEobj7HADy9J_6FBHvrZHkjk7Vd6jbs_EbE_oMuqg/s72-c?imgmax=800" height="72" width="72"/><thr:total>0</thr:total><georss:featurename>College Station, TX, USA</georss:featurename><georss:point>30.627977 -96.334406800000011</georss:point><georss:box>30.4092775 -96.6571303 30.8466765 -96.011683300000016</georss:box></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-59384554657271185.post-9074763932893251227</guid><pubDate>Tue, 13 Aug 2013 18:43:00 +0000</pubDate><atom:updated>2013-08-13T13:43:33.205-05:00</atom:updated><category domain="http://www.blogger.com/atom/ns#">Microsoft Pex</category><title>How to debug your Pex parameterized unit tests</title><description>&lt;p&gt;We talked before about &lt;a title=&quot;Getting started with Microsoft Pex&quot; href=&quot;http://ebeid-soliman.blogspot.com/2013/04/getting-started-with-microsoft-pex.html&quot; target=&quot;_blank&quot;&gt;Microsoft Pex&lt;/a&gt;, and &lt;a title=&quot;Why Pex Choose These Inputs&quot; href=&quot;http://ebeid-soliman.blogspot.com/2013/04/why-pex-choose-these-inputs.html&quot; target=&quot;_blank&quot;&gt;how it choose the shown inputs&lt;/a&gt;. We then talked more about &lt;a title=&quot;Microsoft Pex: Understanding Assumptions, Assertions, and Test-Case Failures&quot; href=&quot;http://ebeid-soliman.blogspot.com/2013/04/microsoft-pex-understanding-assumptions.html&quot; target=&quot;_blank&quot;&gt;building blocks of parameterized unit tests&lt;/a&gt; and its &lt;a title=&quot;Parameterized Test Patterns using Microsoft Pex&quot; href=&quot;http://ebeid-soliman.blogspot.com/2013/05/parameterized-test-patterns-using.html&quot; target=&quot;_blank&quot;&gt;patterns&lt;/a&gt;.&lt;/p&gt; &lt;p&gt;What we missed till now is how to debug your parameterized unit tests. In order to debug your parameterized unit tests, do the following:&lt;/p&gt; &lt;ul&gt; &lt;li&gt;Go to Tools &amp;gt;&amp;gt; Options &amp;gt;&amp;gt; Pex &amp;gt;&amp;gt; Diagnostic.&lt;/li&gt; &lt;li&gt;Change the &lt;em&gt;BreakOnStart&lt;/em&gt; option to &lt;em&gt;True.&lt;/em&gt;&lt;/li&gt;&lt;/ul&gt; &lt;p&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgfjj0As1W5DnJHPq6nqYDIxi-HX_TXxruEvloqBQLG8h0pTbYUAZ8DTJGuTUxSCtipVixFtlubjEQSegFaMniwQjdXXKMgP1TpxHgt3xXeNXD-qzO3-Mfag-Ou5ek0SQB_aKf44vGm-A/s1600-h/Options_2013-08-13_13-01-05%25255B4%25255D.png&quot;&gt;&lt;img style=&quot;background-image: none; border-bottom: 0px; border-left: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top: 0px; border-right: 0px; padding-top: 0px&quot; title=&quot;Options_2013-08-13_13-01-05&quot; border=&quot;0&quot; alt=&quot;Options_2013-08-13_13-01-05&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEixeR3zghTBtxNaC__zrvvK5IF4NCjt9Qbtk06Pz38iMZzXNlkQITRkFCWr9_fgzTnxx97po3idxTHKReET7dw5OFYkbt2-5rE3M3g04vypjCvAPBxp8Me7VrgNTBiSq6KphZfbScAxLg/?imgmax=800&quot; width=&quot;551&quot; height=&quot;341&quot;&gt;&lt;/a&gt;&lt;/p&gt; &lt;ul&gt; &lt;li&gt;Now set a break point at any line of code inside your parameterized unit test.&lt;/li&gt; &lt;li&gt;Right click inside your parameterized unit test and select &lt;em&gt;Run Pex Explorations&lt;/em&gt;.&lt;/li&gt; &lt;li&gt;You will see a dialog popping asking to attach a debugger.&lt;/li&gt; &lt;li&gt;Select your current Visual Studio instance.&lt;/li&gt;&lt;/ul&gt; &lt;p&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEglFrIXq9Rohfv9pGbHOVZyGLmUPFrt8NWs6hwoSqFYAANYPFRGZ7LG_NCSTMTM6aGqKq_ia4sYlSY_mIzmx4loePKu8Y8jya5UFNV7K0EOyoF8FaN6fm1ZmTMJVSsRP2YtvJO-Dzikig/s1600-h/Visual%252520Studio%252520Just-In-Time%252520Debugger_2013-08-13_13-17-20%25255B3%25255D.png&quot;&gt;&lt;img style=&quot;background-image: none; border-bottom: 0px; border-left: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top: 0px; border-right: 0px; padding-top: 0px&quot; title=&quot;Visual Studio Just-In-Time Debugger_2013-08-13_13-17-20&quot; border=&quot;0&quot; alt=&quot;Visual Studio Just-In-Time Debugger_2013-08-13_13-17-20&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhtqYUYkzFmWx9ec7Cfn5cTWi8YD40Xqml_VRQvEg53c57MO_rj3CfBtCIrcRLK7-Gelvi0ONYynwQuGpDU1wtFFReG_qkPv39B-mLvzgIP_Ax34Q__T593DfQ8UtGR97DY1JN4wUXPOQ/?imgmax=800&quot; width=&quot;378&quot; height=&quot;417&quot;&gt;&lt;/a&gt;&lt;/p&gt; &lt;ul&gt; &lt;li&gt;Once attached, press F5.&lt;/li&gt; &lt;li&gt;Now Visual Studio debugger will jump to your break point in the parameterized unit test and stop there. You can now step through you parameterized unit test code.&lt;/li&gt;&lt;/ul&gt; &lt;p&gt;You will notice that parameter’s values are &lt;a title=&quot;Why Pex Choose These Inputs&quot; href=&quot;http://ebeid-soliman.blogspot.com/2013/04/why-pex-choose-these-inputs.html&quot; target=&quot;_blank&quot;&gt;those selected by Pex&lt;/a&gt;. The debugger will run the parameterized unit test for each input value(s) chosen by Pex, So you can inspect the PUT behavior against a specific input value.&lt;/p&gt;  </description><link>http://ebeid-soliman.blogspot.com/2013/08/how-to-debug-your-pex-parameterized.html</link><author>noreply@blogger.com (Ebeid Soliman ElSayed)</author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEixeR3zghTBtxNaC__zrvvK5IF4NCjt9Qbtk06Pz38iMZzXNlkQITRkFCWr9_fgzTnxx97po3idxTHKReET7dw5OFYkbt2-5rE3M3g04vypjCvAPBxp8Me7VrgNTBiSq6KphZfbScAxLg/s72-c?imgmax=800" height="72" width="72"/></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-59384554657271185.post-1053702483261378276</guid><pubDate>Thu, 01 Aug 2013 21:24:00 +0000</pubDate><atom:updated>2013-08-13T13:00:02.463-05:00</atom:updated><category domain="http://www.blogger.com/atom/ns#">Microsoft Pex</category><category domain="http://www.blogger.com/atom/ns#">SMT-LIB</category><category domain="http://www.blogger.com/atom/ns#">Z3</category><title>Convert Microsoft Pex path conditions from Z3 native format to SMT-LIB</title><description>&lt;p&gt;We talked before about &lt;a title=&quot;Get path conditions from Microsoft Pex&quot; href=&quot;http://ebeid-soliman.blogspot.com/2013/07/get-path-conditions-from-microsoft-pex.html&quot; target=&quot;_blank&quot;&gt;getting the code path conditions from Microsoft Pex&lt;/a&gt; as in &lt;a title=&quot;Z3 : An Efficient Theorem Prover&quot; href=&quot;http://research.microsoft.com/en-us/um/redmond/projects/z3/old/index.html&quot; target=&quot;_blank&quot;&gt;Z3&lt;/a&gt; native format(.z3 file).&lt;/p&gt; &lt;p&gt;Sometimes you may need to convert from Z3 native format to &lt;a title=&quot;SMT-LIB The Satisfiability Modulo Theories Library&quot; href=&quot;http://www.smt-lib.org/&quot; target=&quot;_blank&quot;&gt;SMT-LIB&lt;/a&gt; standard. You can do that using the &lt;a title=&quot;The Z3 Constraint Solver, a developer perspective&quot; href=&quot;http://ebeid-soliman.blogspot.com/2013/07/the-z3-constraint-solver-developer.html&quot; target=&quot;_blank&quot;&gt;Z3 C# APIs&lt;/a&gt;. The only trick here is: you have to use the Microsoft.Z3.dll that come with your current Microsoft Pex installation (C:\Program Files\Microsoft Pex\bin\Microsoft.Z3.dll).&lt;/p&gt; &lt;p&gt;To show how it works, let’s create a new C# console application. Add refeerence to Microsoft.Z3.dll that come with your Pex installation.&lt;/p&gt; &lt;p&gt;Edit your code to look like:&lt;/p&gt;&lt;pre class=&quot;prettyprint lang-cs&quot;&gt;using System;&lt;br /&gt;using System.IO;&lt;br /&gt;using Microsoft.Z3;&lt;br /&gt;&lt;br /&gt;namespace Z3ToSMTLIB&lt;br /&gt;{&lt;br /&gt;    class Program&lt;br /&gt;    {&lt;br /&gt;        static void Main(string[] args)&lt;br /&gt;        {&lt;br /&gt;            if(args.Length == 0)&lt;br /&gt;                Console.WriteLine(&quot;Please provide input file name.&quot;);&lt;br /&gt;            if (!File.Exists(args[0]))&lt;br /&gt;                Console.WriteLine(&quot;The specified file doesn&#39;t exist.&quot;);&lt;br /&gt;            using (Context ctx = new Context(new Config()))&lt;br /&gt;            {&lt;br /&gt;                string SMTLIB= ctx.ParseZ3File(args[0]).ToString();&lt;br /&gt;                StreamWriter writer = new StreamWriter(args[0].TrimEnd(&quot;z3&quot;.ToCharArray()) + &quot;SMTLIB&quot;);&lt;br /&gt;                writer.Write(SMTLIB);&lt;br /&gt;                writer.Close();&lt;br /&gt;            }&lt;br /&gt;        }&lt;br /&gt;    }&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;p&gt;Right click your project in the solution explorer and select Add &amp;gt;&amp;gt; New Item &amp;gt;&amp;gt; select Application Configuration File &amp;gt;&amp;gt; click Add. Edit the newly created App.config file to look like: &lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhDFir3uWQTBNdINWC7WGe-KTvh_KIIdB9cL5amlukymT_JFLqyamCwHLLZ0xNTCIKMSj4M8gqCrEwUqzYz9MwUaP5X_zsQKOfx-TUAzgXrJY_-myQXmq5LGyEbL-gpyj8e18IT6p8KDA/s1600-h/Z3ToSMTLIB%252520-%252520Microsoft%252520Visual%252520Studio_2013-08-13_12-58-55%25255B4%25255D.png&quot;&gt;&lt;img style=&quot;background-image: none; border-bottom: 0px; border-left: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top: 0px; border-right: 0px; padding-top: 0px&quot; title=&quot;Z3ToSMTLIB - Microsoft Visual Studio_2013-08-13_12-58-55&quot; border=&quot;0&quot; alt=&quot;Z3ToSMTLIB - Microsoft Visual Studio_2013-08-13_12-58-55&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjIIBTYqdv02bwLhrPKdgDQ_Dwni-RwhhpYIYQLMB-fxRzfumYmTSuZzI-gECM_hLDCIAMP83IA_G7OT9lYKaXXOLsrOJh3eEh-1AlofKmAHgdMjuz9QIqnPqGseGyXHkk0DlDDX6fDpA/?imgmax=800&quot; width=&quot;562&quot; height=&quot;127&quot;&gt;&lt;/a&gt;Now you can run your code and pass a file in Z3 native format and get a file in SMT-LIB format. This SMT-LIB format opens a lot of possibilities that we will explore later. &lt;/p&gt;  </description><link>http://ebeid-soliman.blogspot.com/2013/08/convert-microsoft-pex-path-conditions.html</link><author>noreply@blogger.com (Ebeid Soliman ElSayed)</author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjIIBTYqdv02bwLhrPKdgDQ_Dwni-RwhhpYIYQLMB-fxRzfumYmTSuZzI-gECM_hLDCIAMP83IA_G7OT9lYKaXXOLsrOJh3eEh-1AlofKmAHgdMjuz9QIqnPqGseGyXHkk0DlDDX6fDpA/s72-c?imgmax=800" height="72" width="72"/></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-59384554657271185.post-1325923284266296577</guid><pubDate>Tue, 30 Jul 2013 11:30:00 +0000</pubDate><atom:updated>2013-08-13T12:23:43.430-05:00</atom:updated><category domain="http://www.blogger.com/atom/ns#">Satiability Modulo Theories</category><category domain="http://www.blogger.com/atom/ns#">Z3</category><title>The Z3 Constraint Solver, a developer perspective</title><description>&lt;p&gt;&lt;a title=&quot;Z3 : An Efficient Theorem Prover&quot; href=&quot;http://research.microsoft.com/en-us/um/redmond/projects/z3/old/&quot; target=&quot;_blank&quot;&gt;Z3&lt;/a&gt; is a high-performance SMT solver developed at &lt;a title=&quot;Microsoft Research&quot; href=&quot;http://research.microsoft.com/en-us/&quot; target=&quot;_blank&quot;&gt;Microsoft Research&lt;/a&gt;. It have been integrated with many many tools that came out from Microsoft for program analysis, testing, and verification.&lt;/p&gt; &lt;h4&gt;What SAT means ?&lt;/h4&gt; &lt;p&gt;SAT refers to Boolean satisfiability problem where we want to determine if there exists an interpretation that satisfies a given Boolean formula. In other words, it establishes if the variables of a given Boolean formula can be assigned in such a way as to make the formula evaluate to true.&lt;/p&gt; &lt;h4&gt;What SMT means ?&lt;/h4&gt; &lt;p&gt;SMT stands for Satiability Modulo Theories. SMT instance is a formula in first-order logic, where some functions and predicates have additional interpretations. SMT problem is a decision problem of determining whether such a formula is satisfiable or not.&lt;/p&gt; &lt;p&gt;An SMT instance is a generalization of a Boolean SAT instance in which various sets of variables are replaced by predicates over a suitable set of non-binary variables.&lt;/p&gt; &lt;p&gt;These predicates are classified according to the theory they belong to. For instance, linear inequalities over real variables are evaluated using the rules of the theory of linear real arithmetic.&lt;/p&gt; &lt;h4&gt;What SMT solver means ?&lt;/h4&gt; &lt;p&gt;The goal of an SMT solver is to determine whether an SMT instance can evaluate to true or not. The same analog applies for SAT solvers.&lt;/p&gt; &lt;h4&gt;SMT solvers&lt;/h4&gt; &lt;p&gt;There is a lot of SMT solvers available but there is only one SMT solver with C# APIs, it is Z3. For a list of available SMT solvers, refer to this &lt;a title=&quot;Satisfiability Modulo Theories&quot; href=&quot;http://en.wikipedia.org/wiki/Satisfiability_Modulo_Theories&quot; target=&quot;_blank&quot;&gt;page&lt;/a&gt;. &lt;/p&gt; &lt;h4&gt;Download Z3&lt;/h4&gt; &lt;p&gt;You can download Z3 from &lt;a href=&quot;http://z3.codeplex.com/&quot;&gt;http://z3.codeplex.com/&lt;/a&gt; . I downloaded Z3 4.3.0 and extracted it to C:\z3.&lt;/p&gt; &lt;h4&gt;C# Example&lt;/h4&gt; &lt;p&gt;In the following example we going to let Z3 solve the following equation system: &lt;/p&gt; &lt;ul&gt; &lt;li&gt;x &amp;gt; 0  &lt;li&gt;y = x + 1&amp;nbsp; &lt;li&gt;y &amp;lt; 3&lt;/li&gt;&lt;/ul&gt; &lt;p&gt;Solving the equations means finding values for x and y that make the whole formula evaluates to true.&lt;/p&gt; &lt;ul&gt; &lt;li&gt;Let’s create a new console application project in Visual Studio.  &lt;li&gt;Add reference to &lt;em&gt;Microsoft.Z3.dll&lt;/em&gt; which is located in the bin directory of the Z3 installation directory.  &lt;li&gt;Copy the file libz3.dll from the bin directory of the Z3 installation directory to your project build directory.  &lt;li&gt;Now edit your code to look like the following:&lt;/li&gt;&lt;/ul&gt;&lt;pre class=&quot;prettyprint lang-cs&quot;&gt;using System;&lt;br&gt;using Microsoft.Z3;&lt;br&gt;&lt;br&gt;namespace Z3Demo1&lt;br&gt;{&lt;br&gt;    class Program&lt;br&gt;    {&lt;br&gt;        static void Main(string[] args)&lt;br&gt;        {&lt;br&gt;            using (Context ctx = new Context())&lt;br&gt;            {&lt;br&gt;                Expr x = ctx.MkConst(&quot;x&quot;, ctx.MkIntSort());&lt;br&gt;                Expr y = ctx.MkConst(&quot;y&quot;, ctx.MkIntSort());&lt;br&gt;                Expr zero = ctx.MkNumeral(0, ctx.MkIntSort());&lt;br&gt;                Expr one = ctx.MkNumeral(1, ctx.MkIntSort());&lt;br&gt;                Expr three = ctx.MkNumeral(3, ctx.MkIntSort());&lt;br&gt;                &lt;br&gt;                Solver s = ctx.MkSolver();&lt;br&gt;                s.Assert(ctx.MkAnd(ctx.MkGt((ArithExpr)x, (ArithExpr)zero), ctx.MkEq((ArithExpr)y, &lt;br&gt;                    ctx.MkAdd((ArithExpr)x, (ArithExpr)one)), ctx.MkLt((ArithExpr)y, (ArithExpr)three)));&lt;br&gt;                Console.WriteLine(s.Check());&lt;br&gt;&lt;br&gt;                Model m = s.Model;&lt;br&gt;                foreach (FuncDecl d in m.Decls)&lt;br&gt;                        Console.WriteLine(d.Name + &quot; -&amp;gt; &quot; + m.ConstInterp(d));&lt;br&gt;                    &lt;br&gt;                Console.ReadLine();&lt;br&gt;            }&lt;br&gt;        }&lt;br&gt;    }&lt;br&gt;}&lt;br&gt;&lt;/pre&gt;&lt;br&gt;&lt;br /&gt;&lt;p&gt;Now let’s run the code above and see the output. The solver says the equation system is satisfiable and then gives us the x and y values that satisfy.&lt;/p&gt;&lt;br&gt;&lt;br /&gt;&lt;p&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiu0HTaYst4r7GuSUoJxJGZH1ti_NqNDVLHJdAFqtfIGx4idkK2U77zuel-i-KVdhl4PDK_lDkZJCHGwPz0WnChInpI4g5kQx8Qy8s-T3LC7_0_ApcstzWbwBWSPmlYsskrI2jjabWRLg/s1600-h/fileFProjectsZ3Demo1Z3Demo1binDebugZ3Demo1.EXE_2013-07-29_08-51-07%25255B3%25255D.png&quot;&gt;&lt;img style=&quot;background-image: none; border-right-width: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px&quot; title=&quot;fileFProjectsZ3Demo1Z3Demo1binDebugZ3Demo1.EXE_2013-07-29_08-51-07&quot; border=&quot;0&quot; alt=&quot;fileFProjectsZ3Demo1Z3Demo1binDebugZ3Demo1.EXE_2013-07-29_08-51-07&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgpR3EBJ0UFoGRqJJ5Q35JQE2umnMuqADKOulB_vOEouzZIwhyphenhyphenszBspFd8cb9J4JgeYxZq0_gZtyzHPUI_phUZ_9f7XMvrUX4wkdvN9Rm3D7kLCdRoT0RBY7kU9OxBWigB7UoSjQWfaqQ/?imgmax=800&quot; width=&quot;134&quot; height=&quot;84&quot;&gt;&lt;/a&gt;&lt;/p&gt;&lt;br&gt;&lt;br /&gt;&lt;h4&gt;How it works ?&lt;/h4&gt;&lt;br&gt;&lt;br /&gt;&lt;p&gt;To interact with Z3 through C#, you need a &lt;a title=&quot;Context Class Reference&quot; href=&quot;http://research.microsoft.com/en-us/um/redmond/projects/z3/class_microsoft_1_1_z3_1_1_context.html&quot; target=&quot;_blank&quot;&gt;Context&lt;/a&gt; object. Variables and numerals in your equations are modeled as &lt;a title=&quot;Expr Class Reference&quot; href=&quot;http://research.microsoft.com/en-us/um/redmond/projects/z3/class_microsoft_1_1_z3_1_1_expr.html&quot; target=&quot;_blank&quot;&gt;Expr&lt;/a&gt; objects. You get these objects using member functions in the Context object (MkConts(), MkNumeral(),….). You construct your operand using member functions in the Context object (MkGt(), MkAdd(), MkLt(),…). To solve all the equations together you need to hock them up using AND operator, which is implemented using Context.MkAnd(). After hocking everything in one AND, you pass that the solver through &lt;a title=&quot;Solver Class Reference&quot; href=&quot;http://research.microsoft.com/en-us/um/redmond/projects/z3/class_microsoft_1_1_z3_1_1_solver.html&quot; target=&quot;_blank&quot;&gt;Solver&lt;/a&gt;.Assert(). And as you may guessed, you obtain this Solver using Context.MkSolver().&lt;/p&gt;&lt;br&gt;&lt;br /&gt;&lt;p&gt;Solver.Check() will tell you whether this equation system can be solved or not. To get the variables’ assignments that the come up with, get a Model object Solver.Model. Then use the Delcs collection to get all symbols that have an interpretation in the model. Model.ConstInterp() will get the symbol assigned value.&lt;/p&gt;&lt;br&gt;&lt;br /&gt;&lt;p&gt;In this post we briefly introduced SAT, SMT, and their solvers. Then we explored the only SMT solver that written in C# and had a C# API. Now you can play with as many equations as you want and check them for satisfiability and even got the solution values.&lt;/p&gt;  </description><link>http://ebeid-soliman.blogspot.com/2013/07/the-z3-constraint-solver-developer.html</link><author>noreply@blogger.com (Ebeid Soliman ElSayed)</author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgpR3EBJ0UFoGRqJJ5Q35JQE2umnMuqADKOulB_vOEouzZIwhyphenhyphenszBspFd8cb9J4JgeYxZq0_gZtyzHPUI_phUZ_9f7XMvrUX4wkdvN9Rm3D7kLCdRoT0RBY7kU9OxBWigB7UoSjQWfaqQ/s72-c?imgmax=800" height="72" width="72"/></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-59384554657271185.post-5936124692632596654</guid><pubDate>Wed, 24 Jul 2013 22:26:00 +0000</pubDate><atom:updated>2013-07-24T17:26:43.825-05:00</atom:updated><category domain="http://www.blogger.com/atom/ns#">Microsoft Pex</category><category domain="http://www.blogger.com/atom/ns#">Z3</category><title>Get path conditions from Microsoft Pex</title><description>&lt;p&gt;We talked in a previous &lt;a title=&quot;Why Pex Choose These Inputs&quot; href=&quot;http://ebeid-soliman.blogspot.com/2013/04/why-pex-choose-these-inputs.html&quot; target=&quot;_blank&quot;&gt;post&lt;/a&gt; about Microsoft Pex and how it choose values to explore your code through symbolically executing it and getting all its paths. A code path is the represented by all the conditions that have to be satisfied in order to make the code execution go to this path. Your code conditional statements will lead to different paths according to different input values. Test cases generated by Pex represents the code behavior for specific input values that lead to specific code path.&lt;/p&gt; &lt;p&gt;Within the parameterized unit test You can use the method &lt;strong&gt;GetPathConditionString&lt;/strong&gt; of the &lt;strong&gt;PexSymbolicValue&lt;/strong&gt; class to obtain a textual representation of the current path condition, a predicate (condition) that characterizes an execution path (below, column with title Condition) .&lt;/p&gt; &lt;p&gt;&lt;img title=&quot;ConsoleApplication2 - Microsoft Visual Studio_2013-04-25_11-49-50&quot; border=&quot;0&quot; alt=&quot;ConsoleApplication2 - Microsoft Visual Studio_2013-04-25_11-49-50&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhLzc2HFYSUpl9taRgSYa0aqpTJpEv2p7b3XtUWeM3ZtLaiNDNZhm2sQdl62w_NRzGoH03-1Vmj-t-k-u5tHaIT2jpVj7ZoFa_pvD_-pL9-Al0erDyGiYNRa8wqn9qR13yRXNBtR9ZXEg/?imgmax=800&quot; width=&quot;539&quot; height=&quot;232&quot;&gt;&lt;/p&gt; &lt;p&gt;Methods &lt;strong&gt;ToRawString&lt;/strong&gt; and &lt;strong&gt;GetRawPathConditionString&lt;/strong&gt; of the &lt;strong&gt;PexSymbolicValue &lt;/strong&gt;class return expressions representing symbolic values and the path condition, formatted as &lt;a href=&quot;http://en.wikipedia.org/wiki/S-expression&quot;&gt;S-expressions&lt;/a&gt;.&lt;/p&gt; &lt;p&gt;As we know, Pex uses the Z3 SMT solver behind the scenes. If you want to get the path conditions before being passed to Z3, do the following:&lt;/p&gt; &lt;ol&gt; &lt;li&gt;Create an environment variable with name &lt;strong&gt;z3_logdir&lt;/strong&gt; and value &lt;strong&gt;c:\z3_logdir&lt;/strong&gt; (or any other directory you want)&lt;/li&gt; &lt;li&gt;Create an environment variable with name &lt;strong&gt;z3_loglevel&lt;/strong&gt; and value &lt;strong&gt;constraintsandmodel&lt;/strong&gt; .&lt;/li&gt;&lt;/ol&gt; &lt;p&gt;Now, Pex will create *.z3 files in subdirectories in the &lt;em&gt;z3_logdir&lt;/em&gt; you specified in step 1. These files are in Z3 native format and can be later passed to Z3. For more information about this format, refer to &lt;a title=&quot;Z3 native input format&quot; href=&quot;http://research.microsoft.com/en-us/um/people/leonardo/z3_doc/group__z3native.html&quot; target=&quot;_blank&quot;&gt;Z3 online documentation&lt;/a&gt;.&lt;/p&gt; &lt;p&gt;In future posts we will talk more about the Z3 native format and what we can do with it.&lt;/p&gt;  </description><link>http://ebeid-soliman.blogspot.com/2013/07/get-path-conditions-from-microsoft-pex.html</link><author>noreply@blogger.com (Ebeid Soliman ElSayed)</author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhLzc2HFYSUpl9taRgSYa0aqpTJpEv2p7b3XtUWeM3ZtLaiNDNZhm2sQdl62w_NRzGoH03-1Vmj-t-k-u5tHaIT2jpVj7ZoFa_pvD_-pL9-Al0erDyGiYNRa8wqn9qR13yRXNBtR9ZXEg/s72-c?imgmax=800" height="72" width="72"/></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-59384554657271185.post-3596697447652063456</guid><pubDate>Tue, 23 Jul 2013 22:36:00 +0000</pubDate><atom:updated>2013-07-23T17:40:45.250-05:00</atom:updated><category domain="http://www.blogger.com/atom/ns#">SharePoint 2013</category><title>Bring “Sign in as Different User” back to SharePoint 2013</title><description>&lt;p&gt;If you new to SharePoint 2013 like me and get confused looking for “Sign in as a Different User” menu command, don’t worry it is not there by design but we can easily bring it back.&lt;/p&gt; &lt;p&gt;Do the following steps to get the link back:&lt;/p&gt; &lt;ul&gt; &lt;li&gt;Locate the file \15\TEMPLATE\CONTROLTEMPLATES\Welcome.ascx and open it for editing.  &lt;li&gt;Add the following snippet before the existing element that have id of “ID_RequestAccess”. &lt;/li&gt;&lt;/ul&gt; &lt;pre class=&quot;prettyprint lang-html&quot;&gt;&lt;br /&gt;&lt;SharePoint:MenuItemTemplate runat=&quot;server&quot; ID=&quot;ID_LoginAsDifferentUser&quot;&lt;br /&gt; Text=&quot;&lt;%$Resources:wss,personalactions_loginasdifferentuser%&gt;&quot;&lt;br /&gt; Description=&quot;&lt;%$Resources:wss,personalactions_loginasdifferentuserdescription%&gt;&quot;&lt;br /&gt; MenuGroupId=&quot;100&quot;&lt;br /&gt; Sequence=&quot;100&quot;&lt;br /&gt; UseShortId=&quot;true&quot;&lt;br /&gt; /&gt;&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;p&gt;Save and close the file. Now you should get the link “Sign in as Different User” back.&lt;/p&gt;  </description><link>http://ebeid-soliman.blogspot.com/2013/07/bring-sign-in-as-different-user-back-to.html</link><author>noreply@blogger.com (Ebeid Soliman ElSayed)</author></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-59384554657271185.post-3147025565333079798</guid><pubDate>Wed, 17 Jul 2013 15:20:00 +0000</pubDate><atom:updated>2013-07-17T10:20:55.849-05:00</atom:updated><category domain="http://www.blogger.com/atom/ns#">SharePoint 2010</category><category domain="http://www.blogger.com/atom/ns#">SharePoint Designer 2010</category><title>Create a new Web Part Page with Quick Launch menu</title><description>&lt;p&gt;This post is about a simple task we do daily in SharePoint 2010, creating a new Web Part page. Every time we need a new Web Part page, we go to &lt;em&gt;All Site Content&lt;/em&gt; &amp;gt; &lt;em&gt;Create&lt;/em&gt; &amp;gt; &lt;em&gt;Web Part Page &lt;/em&gt;&amp;gt; &lt;em&gt;Create&lt;/em&gt;. Now we have a Web Part page but no quick launch menu on the left.&lt;/p&gt; &lt;p&gt;To show the quick launch menu on the new created page: &lt;/p&gt; &lt;ul&gt; &lt;li&gt;Open the page for editing in SharePoint 2010.&lt;/li&gt; &lt;li&gt;Switch to the Code view.&lt;/li&gt; &lt;li&gt;Click on the Advanced Mode button on the ribbon.&lt;/li&gt; &lt;li&gt;Now look for the following code snippet and delete it.&lt;/li&gt;&lt;/ul&gt; &lt;blockquote&gt; &lt;p&gt;&lt;font color=&quot;#0000ff&quot;&gt;&amp;lt;SharePoint:UIVersionedContent ID=&quot;WebPartPageHideQLStyles&quot; UIVersion=&quot;4&quot;runat=&quot;server&quot;&amp;gt;&lt;br&gt;&amp;lt;ContentTemplate&amp;gt;&lt;br&gt;body # {s4-leftpanel&lt;br&gt;display: none;&lt;br&gt;}&lt;br&gt;. s4 {ca-&lt;br&gt;margin-left: 0px;&lt;br&gt;}&lt;br&gt;&amp;lt;/ style&amp;gt;&lt;br&gt;&amp;lt;/ ContentTemplate&amp;gt;&lt;br&gt;&amp;lt;/ SharePoint: UIVersionedContent&amp;gt;&lt;/font&gt;&lt;/p&gt;&lt;/blockquote&gt; &lt;ul&gt; &lt;li&gt;Now look for the following snippet and delete it.&lt;/li&gt;&lt;/ul&gt; &lt;blockquote&gt; &lt;p&gt;&lt;font color=&quot;#0000ff&quot;&gt;&amp;lt;asp:Content ContentPlaceHolderId=&quot;PlaceHolderLeftNavBar&quot; runat=&quot;server&quot;&amp;gt;&lt;br&gt;&amp;lt;/ asp: Content&amp;gt;&lt;/font&gt;&lt;/p&gt;&lt;/blockquote&gt; &lt;ul&gt; &lt;li&gt;Save and Close&lt;/li&gt;&lt;/ul&gt; &lt;p&gt;Now when you open the page, the quick launch navigation will be there.&lt;/p&gt;  </description><link>http://ebeid-soliman.blogspot.com/2013/07/create-new-web-part-page-with-quick.html</link><author>noreply@blogger.com (Ebeid Soliman ElSayed)</author></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-59384554657271185.post-8218800317562840497</guid><pubDate>Fri, 12 Jul 2013 22:15:00 +0000</pubDate><atom:updated>2013-07-16T16:34:00.464-05:00</atom:updated><category domain="http://www.blogger.com/atom/ns#">JSON</category><category domain="http://www.blogger.com/atom/ns#">MongoDB</category><category domain="http://www.blogger.com/atom/ns#">NoSQL</category><title>Getting Started with MongoDB – Part 2</title><description>&lt;p&gt;In the previous post we explored the basics of MongoDB. In this post we going to dig deeper in MongoDB.&lt;/p&gt; &lt;h3&gt;Indexing&lt;/h3&gt; &lt;p&gt;Whenever a new collection is created, MongoDB automatically creates an index by the &lt;em&gt;_id &lt;/em&gt;field. These indexes can be found in the system.indexes collection. You can show all indexes in the database using &lt;font color=&quot;#0000ff&quot;&gt;db.system.indexes.find()&lt;/font&gt; . Most queries will include more fields than just the _id, so we need to make indexes on those fields.&lt;/p&gt; &lt;p&gt;Before creating more indexes, let’s see what is the performance of a sample query without creating any indexes other than the automatically created one for _id. Create the following function to generate random phone numbers.&lt;/p&gt; &lt;blockquote&gt; &lt;p&gt;&lt;font color=&quot;#0000ff&quot;&gt;function (area,start,stop) {&lt;br&gt;for(var i=start; i &amp;lt; stop; i++) {&lt;br&gt;var country = 1 + ((Math.random() * 8) &amp;lt;&amp;lt; 0);&lt;br&gt;var num = (country * 1e10) + (area * 1e7) + i;&lt;br&gt;db.phones.insert({&lt;br&gt;_id: num,&lt;br&gt;components: {&lt;br&gt;country: country,&lt;br&gt;area: area,&lt;br&gt;prefix: (i * 1e-4) &amp;lt;&amp;lt; 0,&lt;br&gt;number: i&lt;br&gt;},&lt;br&gt;display: &quot;+&quot; + country + &quot; &quot; + area + &quot;-&quot; + i&lt;br&gt;});&lt;/font&gt;&lt;/p&gt;&lt;/blockquote&gt; &lt;p&gt;Run the function with a three-digit area code (like 800) and a range of seven digit numbers (5,550,000 to 5,650,000)&lt;/p&gt; &lt;blockquote&gt; &lt;p&gt;&lt;font color=&quot;#0000ff&quot;&gt;populatePhones( 800, 5550000, 5650000 )&lt;/font&gt;&lt;/p&gt;&lt;/blockquote&gt; &lt;p&gt;Now we expecting to see a new index created for our new collection.&lt;/p&gt; &lt;blockquote&gt; &lt;p&gt;&lt;font color=&quot;#0000ff&quot;&gt;&amp;gt; db.system.indexes.find()&lt;br&gt;{ &quot;v&quot; : 1, &quot;key&quot; : { &quot;_id&quot; : 1 }, &quot;ns&quot; : &quot;newdb.towns&quot;, &quot;name&quot; : &quot;_id_&quot; }&lt;br&gt;{ &quot;v&quot; : 1, &quot;key&quot; : { &quot;_id&quot; : 1 }, &quot;ns&quot; : &quot;newdb.countries&quot;, &quot;name&quot; : &quot;_id_&quot; }&lt;br&gt;{ &quot;v&quot; : 1, &quot;key&quot; : { &quot;_id&quot; : 1 }, &quot;ns&quot; : &quot;newdb.phones&quot;, &quot;name&quot; : &quot;_id_&quot; }&lt;/font&gt;&lt;/p&gt;&lt;/blockquote&gt; &lt;p&gt;Now let’s check the query without an index. The explain() method is used to output details of a given operation and can help us here.&lt;/p&gt; &lt;blockquote&gt; &lt;p&gt;&lt;font color=&quot;#0000ff&quot;&gt;&amp;gt; db.phones.find( { display : &quot;+1 800-5650001&quot; } ).explain()&lt;br&gt;{&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &quot;cursor&quot; : &quot;&lt;strong&gt;&lt;u&gt;BasicCursor&lt;/u&gt;&lt;/strong&gt;&quot;,&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &quot;isMultiKey&quot; : false,&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &quot;n&quot; : 0,&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &quot;nscannedObjects&quot; : 100000,&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &quot;nscanned&quot; : 100000,&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &quot;nscannedObjectsAllPlans&quot; : 100000,&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &quot;nscannedAllPlans&quot; : 100000,&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &quot;scanAndOrder&quot; : false,&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &quot;indexOnly&quot; : false,&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &quot;nYields&quot; : 0,&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &quot;nChunkSkips&quot; : 0,&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &quot;millis&quot; : &lt;strong&gt;&lt;u&gt;134&lt;/u&gt;&lt;/strong&gt;,&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &quot;indexBounds&quot; : {&lt;/font&gt;&lt;/p&gt;&lt;/blockquote&gt; &lt;blockquote&gt; &lt;p&gt;&lt;font color=&quot;#0000ff&quot;&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; },&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &quot;server&quot; : &quot;ESOLIMAN:27017&quot;&lt;br&gt;}&lt;/font&gt;&lt;/p&gt;&lt;/blockquote&gt; &lt;p&gt;Just to make things simple, we will look at the millis field only which gives the milliseconds needed to complete the query. Now it is 134.&lt;/p&gt; &lt;p&gt;Now we going to create an index and see how it improves our query execution time. We create an index by calling &lt;strong&gt;ensureIndex(fields,options)&lt;/strong&gt; on the collection. The fields parameter is an object containing the fields to be indexed against. The options parameter describes the type of index to make. On production environments, creating an index on a large collection can be slow and resource-intensive, you should create them in off-peak times. In our case we going to build a unique index on the display field and we will drop duplicate entries.&lt;/p&gt; &lt;blockquote&gt; &lt;p&gt;&lt;font color=&quot;#0000ff&quot;&gt;&amp;gt; db.phones.ensureIndex(&lt;br&gt;... { display : 1 },&lt;br&gt;... { unique : true, dropDups : true }&lt;br&gt;... )&lt;/font&gt;&lt;/p&gt;&lt;/blockquote&gt; &lt;p&gt;lets try explain() of find() and see the new value for millis field. Query execution time improved, from 134 down to 16.&lt;/p&gt; &lt;blockquote&gt; &lt;p&gt;&lt;font color=&quot;#0000ff&quot;&gt;&amp;gt; db.phones.find( { display : &quot;+1 800-5650001&quot; } ).explain()&lt;br&gt;{&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &quot;cursor&quot; : &quot;&lt;strong&gt;&lt;u&gt;BtreeCursor display_1&lt;/u&gt;&lt;/strong&gt;&quot;,&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &quot;isMultiKey&quot; : false,&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &quot;n&quot; : 0,&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &quot;nscannedObjects&quot; : 0,&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &quot;nscanned&quot; : 0,&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &quot;nscannedObjectsAllPlans&quot; : 0,&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &quot;nscannedAllPlans&quot; : 0,&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &quot;scanAndOrder&quot; : false,&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &quot;indexOnly&quot; : false,&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &quot;nYields&quot; : 0,&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &quot;nChunkSkips&quot; : 0,&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &quot;millis&quot; : &lt;strong&gt;&lt;u&gt;16&lt;/u&gt;&lt;/strong&gt;,&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &quot;indexBounds&quot; : {&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &quot;display&quot; : [&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; [&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &quot;+1 800-5650001&quot;,&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &quot;+1 800-5650001&quot;&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; ]&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; ]&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; },&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &quot;server&quot; : &quot;ESOLIMAN:27017&quot;&lt;br&gt;}&lt;/font&gt;&lt;/p&gt;&lt;/blockquote&gt; &lt;p&gt;Notice the cursor changed from a Basic to a B-tree cursor. MongoDB is no longer doing&lt;br&gt;a full collection scan but instead walking the tree to retrieve the value.&lt;/p&gt; &lt;p&gt;Mongo can build your index on nested values: &lt;font color=&quot;#0000ff&quot;&gt;db.phones.ensureIndex({ &quot;components.area&quot;: 1 }, { background : 1 })&lt;/font&gt;&lt;/p&gt; &lt;h3&gt;Aggregations&lt;/h3&gt; &lt;p&gt;&lt;strong&gt;count()&lt;/strong&gt; counts the number of matching documents. It takes a query and returns a number.&lt;/p&gt; &lt;blockquote&gt; &lt;p&gt;&lt;font color=&quot;#0000ff&quot;&gt;&amp;gt; db.phones.count({&#39;components.number&#39;: { $gt : 5599999 } })&lt;br&gt;100000&lt;/font&gt;&lt;/p&gt;&lt;/blockquote&gt; &lt;p&gt;&lt;font color=&quot;#000000&quot;&gt;&lt;strong&gt;distinct()&lt;/strong&gt; returns each matching value where one or more exists.&lt;/font&gt;&lt;/p&gt; &lt;blockquote&gt; &lt;p&gt;&lt;font color=&quot;#0000ff&quot;&gt;&amp;gt; db.phones.distinct(&#39;components.number&#39;, {&#39;components.number&#39;: { $lt : 5550005 } })&lt;br&gt;[ 5550000, 5550001, 5550002, 5550003, 5550004 ]&lt;/font&gt;&lt;/p&gt;&lt;/blockquote&gt; &lt;p&gt;&lt;font color=&quot;#000000&quot;&gt;&lt;strong&gt;group()&lt;/strong&gt; groups documents in a collection by the specified keys and performs simple aggregation functions such as computing counts and sums. It is similar to GROUP BY in SQL. It accepts the following parameters&lt;/font&gt;&lt;/p&gt; &lt;ul&gt; &lt;li&gt;&lt;em&gt;key&lt;/em&gt; – Specifies one or more document fields to group by.&lt;/li&gt; &lt;li&gt;&lt;em&gt;reduce&lt;/em&gt; – Specifies a function for the group operation perform on the documents during the grouping operation, such as compute a sum or a count. The aggregation function takes two arguments: the current document and the aggregate result for the previous documents in the group.&lt;/li&gt; &lt;li&gt;&lt;em&gt;initial&lt;/em&gt; – Initializes the aggregation result document.&lt;/li&gt; &lt;li&gt;&lt;em&gt;keyf&lt;/em&gt; – Optional. Alternative to the key field. Specifies a function that creates a “key object” for use as the grouping key. Use the keyf instead of key to group by calculated fields rather than existing document fields. Like HAVING in SQL.&lt;/li&gt; &lt;li&gt;&lt;em&gt;cond&lt;/em&gt; – Optional. Specifies the selection criteria to determine which documents in the collection to process. If you omit the cond field, db.collection.group() processes all the documents in the collection for the group operation.&lt;/li&gt; &lt;li&gt;&lt;em&gt;finalize&lt;/em&gt; – Optional. Specifies a function that runs each item in the result set before db.collection.group() returns the final value. This function can either modify the result document or replace the result document as a whole.&lt;/li&gt;&lt;/ul&gt; &lt;blockquote&gt; &lt;p&gt;&lt;font color=&quot;#0000ff&quot;&gt;&amp;gt; db.phones.group({&lt;br&gt;... initial : { count : 0 },&lt;br&gt;... reduce : function(phone, output) { output.count++; },&lt;br&gt;... cond : { &#39;components.number&#39; : { $gt : 5599999 } },&lt;br&gt;... key : { &#39;components.area&#39; : true }&lt;br&gt;... })&lt;br&gt;[&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; {&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &quot;components.area&quot; : 800,&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &quot;count&quot; : 50000&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; },&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; {&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &quot;components.area&quot; : 855,&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &quot;count&quot; : 50000&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; }&lt;br&gt;]&lt;/font&gt;&lt;/p&gt;&lt;/blockquote&gt; &lt;p&gt;The first thing we did here was set an initial object with a field named count set to 0—fields created here will appear in the output. Next we describe what to do with this field by declaring a reduce function that adds one for every document we encounter. Finally, we gave group a condition restricting which documents to reduce over.&lt;/p&gt; &lt;h3&gt;Server-Side Commands&lt;/h3&gt; &lt;p&gt;All queries and operations we did till now, execute on the client side. The db object provides a command named eval(), which passes the given function to the server. This dramatically reduces the communication between client and server. It is similar to stored procedures in SQL.&lt;/p&gt; &lt;p&gt;There is a also a set of prebuilt commands that can be executed on the server. Use &lt;font color=&quot;#0000ff&quot;&gt;db.listCommands()&lt;/font&gt; to get a list of these &lt;a title=&quot;db.listCommands()&quot; href=&quot;http://docs.mongodb.org/manual/reference/method/db.listCommands/#db.listCommands&quot; target=&quot;_blank&quot;&gt;commands&lt;/a&gt;. To run any command on the server use &lt;font color=&quot;#0000ff&quot;&gt;db.runCommand()&lt;/font&gt; like &lt;font color=&quot;#0000ff&quot;&gt;db.runCommand({ &quot;count&quot; : &quot;phones&quot; })&lt;/font&gt;&lt;/p&gt; &lt;p&gt;&lt;font color=&quot;#000000&quot;&gt;Although it is not recommended, you can &lt;a title=&quot;Store a JavaScript function on the Server&quot; href=&quot;http://docs.mongodb.org/manual/tutorial/store-javascript-function-on-server/&quot; target=&quot;_blank&quot;&gt;store a JavaScript function on the server&lt;/a&gt; for later reuse.&lt;/font&gt;&lt;/p&gt; &lt;h3&gt;MapReduce&lt;/h3&gt; &lt;p&gt;&lt;font color=&quot;#000000&quot;&gt;&lt;a title=&quot;MapReduce: Simplified Data Processing on Large Clusters&quot; href=&quot;http://research.google.com/archive/mapreduce.html&quot; target=&quot;_blank&quot;&gt;MapReduce&lt;/a&gt; is a framework for parallelizing problems. Generally speaking the parallelization happens on two steps:&lt;/font&gt;&lt;/p&gt; &lt;ul&gt; &lt;li&gt;&lt;b&gt;&quot;Map&quot; step:&lt;/b&gt; The master node takes the input, divides it into smaller sub-problems, and distributes them to worker nodes. A worker node may do this again in turn, leading to a multi-level &lt;a href=&quot;http://en.wikipedia.org/wiki/Tree_(data_structure)&quot;&gt;tree&lt;/a&gt; structure. The worker node processes the smaller problem, and passes the answer back to its master node.&lt;/li&gt; &lt;li&gt;&lt;b&gt;&quot;Reduce&quot; step:&lt;/b&gt; The master node then collects the answers to all the sub-problems and combines them in some way to form the output – the answer to the problem it was originally trying to solve.&lt;/li&gt;&lt;/ul&gt; &lt;p&gt;To show the MapReduce framework in action, let’s build on the phones collections that we created previously. Let’s generate a report that counts all phone numbers that contain the same digits for each country.&lt;/p&gt; &lt;p&gt;First we create a &lt;em&gt;helper&lt;/em&gt; function that extracts an array of all distinct numbers (this step is not a MapReduce step).&lt;/p&gt; &lt;blockquote&gt; &lt;p&gt;&lt;font color=&quot;#0000ff&quot;&gt;&amp;gt; distinctDigits = function(phone) {&lt;br&gt;... var&lt;br&gt;... number = phone.components.number + &#39;&#39;,&lt;br&gt;... seen = [],&lt;br&gt;... result = [],&lt;br&gt;... i = number.length;&lt;br&gt;... while(i--) {&lt;br&gt;...&amp;nbsp; seen[+number[i]] = 1;&lt;br&gt;...&amp;nbsp; }&lt;br&gt;... for (i=0; i&amp;lt;10; i++) {&lt;br&gt;...&amp;nbsp; if (seen[i]) {&lt;br&gt;...&amp;nbsp;&amp;nbsp; result[result.length] = i;&lt;br&gt;...&amp;nbsp;&amp;nbsp; }&lt;br&gt;...&amp;nbsp; }&lt;br&gt;... return result;&lt;br&gt;... }&lt;/font&gt;&lt;/p&gt;&lt;/blockquote&gt; &lt;blockquote&gt; &lt;p&gt;&lt;font color=&quot;#0000ff&quot;&gt;&amp;gt; db.eval(&quot;distinctDigits(db.phones.findOne({ &#39;components.number&#39; : 5551213 }))&quot;)&lt;br&gt;[ 1, 2, 3, 5 ]&lt;/font&gt;&lt;/p&gt;&lt;/blockquote&gt; &lt;p&gt;Now let’s find find distinct numbers of each country. Since we need to query by country later, we will add the distinct digits array and country as compound key. For each distinct digits array in each country, we will add a count field that hold the value 1. &lt;/p&gt; &lt;blockquote&gt; &lt;p&gt;&lt;font color=&quot;#0000ff&quot;&gt;&amp;gt; map = function() {&lt;br&gt;... var digits = distinctDigits(this);&lt;br&gt;... emit( { digits : digits, country : this.components.country } , { count : 1 } );&lt;br&gt;... }&lt;/font&gt;&lt;/p&gt;&lt;/blockquote&gt; &lt;p&gt;The reducer function will all these 1s that have been emitted from the map function.&lt;/p&gt; &lt;blockquote&gt; &lt;p&gt;&lt;font color=&quot;#0000ff&quot;&gt;&amp;gt;reduce = function(key, values) {&lt;br&gt;... var total = 0;&lt;br&gt;... for(var i=0; i&amp;lt;values.length; i++) {&lt;br&gt;...&amp;nbsp; total += values[i].count;&lt;br&gt;...&amp;nbsp; }&lt;br&gt;...&amp;nbsp; return { count : total };&lt;br&gt;... }&lt;/font&gt;&lt;/p&gt;&lt;/blockquote&gt; &lt;p&gt;Now it is time to put all pieces together and start the whole thing (the input collection, map function, reduce function, output collection).&lt;/p&gt; &lt;blockquote&gt; &lt;p&gt;&lt;font color=&quot;#0000ff&quot;&gt;&amp;gt; results = db.runCommand({&lt;br&gt;... mapReduce : &#39;phones&#39;,&lt;br&gt;... map : map,&lt;br&gt;... reduce : reduce,&lt;br&gt;... out : &#39;phones.report&#39;&lt;br&gt;... })&lt;br&gt;{&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &quot;result&quot; : &quot;phones.report&quot;,&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &quot;timeMillis&quot; : 21084,&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &quot;counts&quot; : {&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &quot;input&quot; : 200000,&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &quot;emit&quot; : 200000,&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &quot;reduce&quot; : 48469,&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &quot;output&quot; : 3489&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; },&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &quot;ok&quot; : 1&lt;br&gt;}&lt;/font&gt;&lt;/p&gt;&lt;/blockquote&gt; &lt;p&gt;Now you can query the output collection like any other collection&lt;/p&gt; &lt;blockquote&gt; &lt;p&gt;&lt;font color=&quot;#0000ff&quot;&gt;&amp;gt; db.phones.report.find()&lt;br&gt;{ &quot;_id&quot; : { &quot;digits&quot; : [&amp;nbsp; 0,&amp;nbsp; 1,&amp;nbsp; 2,&amp;nbsp; 3,&amp;nbsp; 4,&amp;nbsp; 5,&amp;nbsp; 6 ], &quot;country&quot; : 1 }, &quot;value&quot; : { &quot;count&quot; : 37 } }&lt;br&gt;{ &quot;_id&quot; : { &quot;digits&quot; : [&amp;nbsp; 0,&amp;nbsp; 1,&amp;nbsp; 2,&amp;nbsp; 3,&amp;nbsp; 4,&amp;nbsp; 5,&amp;nbsp; 6 ], &quot;country&quot; : 2 }, &quot;value&quot; : { &quot;count&quot; : 23 } }&lt;br&gt;{ &quot;_id&quot; : { &quot;digits&quot; : [&amp;nbsp; 0,&amp;nbsp; 1,&amp;nbsp; 2,&amp;nbsp; 3,&amp;nbsp; 4,&amp;nbsp; 5,&amp;nbsp; 6 ], &quot;country&quot; : 3 }, &quot;value&quot; : { &quot;count&quot; : 17 } }&lt;br&gt;{ &quot;_id&quot; : { &quot;digits&quot; : [&amp;nbsp; 0,&amp;nbsp; 1,&amp;nbsp; 2,&amp;nbsp; 3,&amp;nbsp; 4,&amp;nbsp; 5,&amp;nbsp; 6 ], &quot;country&quot; : 4 }, &quot;value&quot; : { &quot;count&quot; : 29 } }&lt;br&gt;{ &quot;_id&quot; : { &quot;digits&quot; : [&amp;nbsp; 0,&amp;nbsp; 1,&amp;nbsp; 2,&amp;nbsp; 3,&amp;nbsp; 4,&amp;nbsp; 5,&amp;nbsp; 6 ], &quot;country&quot; : 5 }, &quot;value&quot; : { &quot;count&quot; : 34 } }&lt;br&gt;{ &quot;_id&quot; : { &quot;digits&quot; : [&amp;nbsp; 0,&amp;nbsp; 1,&amp;nbsp; 2,&amp;nbsp; 3,&amp;nbsp; 4,&amp;nbsp; 5,&amp;nbsp; 6 ], &quot;country&quot; : 6 }, &quot;value&quot; : { &quot;count&quot; : 35 } }&lt;br&gt;{ &quot;_id&quot; : { &quot;digits&quot; : [&amp;nbsp; 0,&amp;nbsp; 1,&amp;nbsp; 2,&amp;nbsp; 3,&amp;nbsp; 4,&amp;nbsp; 5,&amp;nbsp; 6 ], &quot;country&quot; : 7 }, &quot;value&quot; : { &quot;count&quot; : 33 } }&lt;br&gt;{ &quot;_id&quot; : { &quot;digits&quot; : [&amp;nbsp; 0,&amp;nbsp; 1,&amp;nbsp; 2,&amp;nbsp; 3,&amp;nbsp; 4,&amp;nbsp; 5,&amp;nbsp; 6 ], &quot;country&quot; : 8 }, &quot;value&quot; : { &quot;count&quot; : 32 } }&lt;br&gt;{ &quot;_id&quot; : { &quot;digits&quot; : [&amp;nbsp; 0,&amp;nbsp; 1,&amp;nbsp; 2,&amp;nbsp; 3,&amp;nbsp; 5 ], &quot;country&quot; : 1 }, &quot;value&quot; : { &quot;count&quot; : 5 } }&lt;br&gt;{ &quot;_id&quot; : { &quot;digits&quot; : [&amp;nbsp; 0,&amp;nbsp; 1,&amp;nbsp; 2,&amp;nbsp; 3,&amp;nbsp; 5 ], &quot;country&quot; : 2 }, &quot;value&quot; : { &quot;count&quot; : 7 } }&lt;br&gt;{ &quot;_id&quot; : { &quot;digits&quot; : [&amp;nbsp; 0,&amp;nbsp; 1,&amp;nbsp; 2,&amp;nbsp; 3,&amp;nbsp; 5 ], &quot;country&quot; : 3 }, &quot;value&quot; : { &quot;count&quot; : 3 } }&lt;br&gt;{ &quot;_id&quot; : { &quot;digits&quot; : [&amp;nbsp; 0,&amp;nbsp; 1,&amp;nbsp; 2,&amp;nbsp; 3,&amp;nbsp; 5 ], &quot;country&quot; : 4 }, &quot;value&quot; : { &quot;count&quot; : 6 } }&lt;br&gt;{ &quot;_id&quot; : { &quot;digits&quot; : [&amp;nbsp; 0,&amp;nbsp; 1,&amp;nbsp; 2,&amp;nbsp; 3,&amp;nbsp; 5 ], &quot;country&quot; : 5 }, &quot;value&quot; : { &quot;count&quot; : 5 } }&lt;br&gt;{ &quot;_id&quot; : { &quot;digits&quot; : [&amp;nbsp; 0,&amp;nbsp; 1,&amp;nbsp; 2,&amp;nbsp; 3,&amp;nbsp; 5 ], &quot;country&quot; : 6 }, &quot;value&quot; : { &quot;count&quot; : 10 } }&lt;br&gt;{ &quot;_id&quot; : { &quot;digits&quot; : [&amp;nbsp; 0,&amp;nbsp; 1,&amp;nbsp; 2,&amp;nbsp; 3,&amp;nbsp; 5 ], &quot;country&quot; : 7 }, &quot;value&quot; : { &quot;count&quot; : 5 } }&lt;br&gt;{ &quot;_id&quot; : { &quot;digits&quot; : [&amp;nbsp; 0,&amp;nbsp; 1,&amp;nbsp; 2,&amp;nbsp; 3,&amp;nbsp; 5 ], &quot;country&quot; : 8 }, &quot;value&quot; : { &quot;count&quot; : 7 } }&lt;br&gt;{ &quot;_id&quot; : { &quot;digits&quot; : [&amp;nbsp; 0,&amp;nbsp; 1,&amp;nbsp; 2,&amp;nbsp; 3,&amp;nbsp; 5,&amp;nbsp; 6 ], &quot;country&quot; : 1 }, &quot;value&quot; : { &quot;count&quot; : 95 } }&lt;br&gt;{ &quot;_id&quot; : { &quot;digits&quot; : [&amp;nbsp; 0,&amp;nbsp; 1,&amp;nbsp; 2,&amp;nbsp; 3,&amp;nbsp; 5,&amp;nbsp; 6 ], &quot;country&quot; : 2 }, &quot;value&quot; : { &quot;count&quot; : 104 } }&lt;br&gt;{ &quot;_id&quot; : { &quot;digits&quot; : [&amp;nbsp; 0,&amp;nbsp; 1,&amp;nbsp; 2,&amp;nbsp; 3,&amp;nbsp; 5,&amp;nbsp; 6 ], &quot;country&quot; : 3 }, &quot;value&quot; : { &quot;count&quot; : 108 } }&lt;br&gt;{ &quot;_id&quot; : { &quot;digits&quot; : [&amp;nbsp; 0,&amp;nbsp; 1,&amp;nbsp; 2,&amp;nbsp; 3,&amp;nbsp; 5,&amp;nbsp; 6 ], &quot;country&quot; : 4 }, &quot;value&quot; : { &quot;count&quot; : 113 } }&lt;br&gt;Type &quot;it&quot; for more&lt;/font&gt;&lt;/p&gt;&lt;/blockquote&gt; &lt;p&gt;or&lt;/p&gt; &lt;blockquote&gt; &lt;p&gt;&lt;font color=&quot;#0000ff&quot;&gt;&amp;gt; db.phones.report.find({&#39;_id.country&#39; : 8})&lt;br&gt;{ &quot;_id&quot; : { &quot;digits&quot; : [&amp;nbsp; 0,&amp;nbsp; 1,&amp;nbsp; 2,&amp;nbsp; 3,&amp;nbsp; 4,&amp;nbsp; 5,&amp;nbsp; 6 ], &quot;country&quot; : 8 }, &quot;value&quot; : { &quot;count&quot; : 32 } }&lt;br&gt;{ &quot;_id&quot; : { &quot;digits&quot; : [&amp;nbsp; 0,&amp;nbsp; 1,&amp;nbsp; 2,&amp;nbsp; 3,&amp;nbsp; 5 ], &quot;country&quot; : 8 }, &quot;value&quot; : { &quot;count&quot; : 7 } }&lt;br&gt;{ &quot;_id&quot; : { &quot;digits&quot; : [&amp;nbsp; 0,&amp;nbsp; 1,&amp;nbsp; 2,&amp;nbsp; 3,&amp;nbsp; 5,&amp;nbsp; 6 ], &quot;country&quot; : 8 }, &quot;value&quot; : { &quot;count&quot; : 127 } }&lt;br&gt;{ &quot;_id&quot; : { &quot;digits&quot; : [&amp;nbsp; 0,&amp;nbsp; 1,&amp;nbsp; 2,&amp;nbsp; 3,&amp;nbsp; 5,&amp;nbsp; 6,&amp;nbsp; 7 ], &quot;country&quot; : 8 }, &quot;value&quot; : { &quot;count&quot; : 28 } }&lt;br&gt;{ &quot;_id&quot; : { &quot;digits&quot; : [&amp;nbsp; 0,&amp;nbsp; 1,&amp;nbsp; 2,&amp;nbsp; 3,&amp;nbsp; 5,&amp;nbsp; 6,&amp;nbsp; 8 ], &quot;country&quot; : 8 }, &quot;value&quot; : { &quot;count&quot; : 27 } }&lt;br&gt;{ &quot;_id&quot; : { &quot;digits&quot; : [&amp;nbsp; 0,&amp;nbsp; 1,&amp;nbsp; 2,&amp;nbsp; 3,&amp;nbsp; 5,&amp;nbsp; 6,&amp;nbsp; 9 ], &quot;country&quot; : 8 }, &quot;value&quot; : { &quot;count&quot; : 29 } }&lt;br&gt;{ &quot;_id&quot; : { &quot;digits&quot; : [&amp;nbsp; 0,&amp;nbsp; 1,&amp;nbsp; 2,&amp;nbsp; 3,&amp;nbsp; 5,&amp;nbsp; 7 ], &quot;country&quot; : 8 }, &quot;value&quot; : { &quot;count&quot; : 10 } }&lt;br&gt;{ &quot;_id&quot; : { &quot;digits&quot; : [&amp;nbsp; 0,&amp;nbsp; 1,&amp;nbsp; 2,&amp;nbsp; 3,&amp;nbsp; 5,&amp;nbsp; 8 ], &quot;country&quot; : 8 }, &quot;value&quot; : { &quot;count&quot; : 7 } }&lt;br&gt;{ &quot;_id&quot; : { &quot;digits&quot; : [&amp;nbsp; 0,&amp;nbsp; 1,&amp;nbsp; 2,&amp;nbsp; 3,&amp;nbsp; 5,&amp;nbsp; 9 ], &quot;country&quot; : 8 }, &quot;value&quot; : { &quot;count&quot; : 8 } }&lt;br&gt;{ &quot;_id&quot; : { &quot;digits&quot; : [&amp;nbsp; 0,&amp;nbsp; 1,&amp;nbsp; 2,&amp;nbsp; 4,&amp;nbsp; 5 ], &quot;country&quot; : 8 }, &quot;value&quot; : { &quot;count&quot; : 3 } }&lt;br&gt;{ &quot;_id&quot; : { &quot;digits&quot; : [&amp;nbsp; 0,&amp;nbsp; 1,&amp;nbsp; 2,&amp;nbsp; 4,&amp;nbsp; 5,&amp;nbsp; 6 ], &quot;country&quot; : 8 }, &quot;value&quot; : { &quot;count&quot; : 121 } }&lt;br&gt;{ &quot;_id&quot; : { &quot;digits&quot; : [&amp;nbsp; 0,&amp;nbsp; 1,&amp;nbsp; 2,&amp;nbsp; 4,&amp;nbsp; 5,&amp;nbsp; 6,&amp;nbsp; 7 ], &quot;country&quot; : 8 }, &quot;value&quot; : { &quot;count&quot; : 25 } }&lt;br&gt;{ &quot;_id&quot; : { &quot;digits&quot; : [&amp;nbsp; 0,&amp;nbsp; 1,&amp;nbsp; 2,&amp;nbsp; 4,&amp;nbsp; 5,&amp;nbsp; 6,&amp;nbsp; 8 ], &quot;country&quot; : 8 }, &quot;value&quot; : { &quot;count&quot; : 27 } }&lt;br&gt;{ &quot;_id&quot; : { &quot;digits&quot; : [&amp;nbsp; 0,&amp;nbsp; 1,&amp;nbsp; 2,&amp;nbsp; 4,&amp;nbsp; 5,&amp;nbsp; 6,&amp;nbsp; 9 ], &quot;country&quot; : 8 }, &quot;value&quot; : { &quot;count&quot; : 17 } }&lt;br&gt;{ &quot;_id&quot; : { &quot;digits&quot; : [&amp;nbsp; 0,&amp;nbsp; 1,&amp;nbsp; 2,&amp;nbsp; 4,&amp;nbsp; 5,&amp;nbsp; 7 ], &quot;country&quot; : 8 }, &quot;value&quot; : { &quot;count&quot; : 4 } }&lt;br&gt;{ &quot;_id&quot; : { &quot;digits&quot; : [&amp;nbsp; 0,&amp;nbsp; 1,&amp;nbsp; 2,&amp;nbsp; 4,&amp;nbsp; 5,&amp;nbsp; 8 ], &quot;country&quot; : 8 }, &quot;value&quot; : { &quot;count&quot; : 4 } }&lt;br&gt;{ &quot;_id&quot; : { &quot;digits&quot; : [&amp;nbsp; 0,&amp;nbsp; 1,&amp;nbsp; 2,&amp;nbsp; 4,&amp;nbsp; 5,&amp;nbsp; 9 ], &quot;country&quot; : 8 }, &quot;value&quot; : { &quot;count&quot; : 7 } }&lt;br&gt;{ &quot;_id&quot; : { &quot;digits&quot; : [&amp;nbsp; 0,&amp;nbsp; 1,&amp;nbsp; 2,&amp;nbsp; 5 ], &quot;country&quot; : 8 }, &quot;value&quot; : { &quot;count&quot; : 14 } }&lt;br&gt;{ &quot;_id&quot; : { &quot;digits&quot; : [&amp;nbsp; 0,&amp;nbsp; 1,&amp;nbsp; 2,&amp;nbsp; 5,&amp;nbsp; 6 ], &quot;country&quot; : 8 }, &quot;value&quot; : { &quot;count&quot; : 162 } }&lt;br&gt;{ &quot;_id&quot; : { &quot;digits&quot; : [&amp;nbsp; 0,&amp;nbsp; 1,&amp;nbsp; 2,&amp;nbsp; 5,&amp;nbsp; 6,&amp;nbsp; 7 ], &quot;country&quot; : 8 }, &quot;value&quot; : { &quot;count&quot; : 95 } }&lt;br&gt;Type &quot;it&quot; for more&lt;/font&gt;&lt;/p&gt;&lt;/blockquote&gt; &lt;p&gt;The unique emitted keys are under the field &lt;em&gt;_id&lt;/em&gt;, and all of the data returned from the reducers are&lt;br&gt;under the field &lt;em&gt;value&lt;/em&gt;. If you prefer that the mapreducer just output the results, rather than outputting to a collection, you can set the out value to { inline : 1 }, but bear in mind there is a limit to the size of a result you can output (16 MB).&lt;/p&gt; &lt;p&gt;In some situations you may need to feed the reducer function’s output into another reducer function. In these situations we need to carefully handle both cases: either map’s output or another reduce’s output.&lt;/p&gt; &lt;p&gt;MongoDB have so many features that we didn’t even mentioned here. In later posts will continue working on them.&lt;/p&gt; &lt;h3&gt;&lt;font color=&quot;#0000ff&quot;&gt;&lt;/font&gt;&lt;/h3&gt;  </description><link>http://ebeid-soliman.blogspot.com/2013/07/getting-started-with-mongodb-part-2.html</link><author>noreply@blogger.com (Ebeid Soliman ElSayed)</author></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-59384554657271185.post-2830278696665579012</guid><pubDate>Fri, 12 Jul 2013 18:46:00 +0000</pubDate><atom:updated>2013-07-12T15:54:21.770-05:00</atom:updated><category domain="http://www.blogger.com/atom/ns#">JSON</category><category domain="http://www.blogger.com/atom/ns#">MongoDB</category><category domain="http://www.blogger.com/atom/ns#">NoSQL</category><title>Getting Started with MongoDB – Part 1</title><description>&lt;br&gt;&lt;b&gt;MongoDB&lt;/b&gt; (from &quot;hu&lt;b&gt;mongo&lt;/b&gt;us&quot;) is an open source &lt;a href=&quot;http://en.wikipedia.org/wiki/Document-oriented_database&quot;&gt;document-oriented database&lt;/a&gt; system developed and supported by &lt;a href=&quot;http://www.blogger.com/www.10gen.com&quot;&gt;10gen&lt;/a&gt; (founded by &lt;a href=&quot;https://twitter.com/dmerr&quot;&gt;Dwight Merriman&lt;/a&gt;). First publicly released in 2009, and since then it have been a rising star in the NoSQL world. MongoDB stores structured data as &lt;a href=&quot;http://en.wikipedia.org/wiki/JSON&quot;&gt;JSON&lt;/a&gt;-like documents with dynamic schemas (technically data is stored in a binary form of JSON known as &lt;a href=&quot;http://en.wikipedia.org/wiki/BSON&quot;&gt;BSON&lt;/a&gt;), making the integration of data in certain types of applications easier and faster.&lt;br&gt; &lt;h4&gt;Installation&lt;/h4&gt; &lt;ol&gt; &lt;li&gt;Download the latest mongoDB version from &lt;a title=&quot;downloads page&quot; href=&quot;http://www.mongodb.org/downloads&quot; target=&quot;_blank&quot;&gt;here&lt;/a&gt;.  &lt;li&gt;Extract the archive to your preferred location (in my case C:\mongodb). MongoDB is self-contained and does not have any other system dependencies. You can run MongoDB from any folder you choose. You may install MongoDB in any directory.  &lt;li&gt;MongoDB requires a data folder to store its files (default is C:\data\db ). You may specify a different path with the dbpath setting when lunching mongod.exe.&lt;/li&gt;&lt;/ol&gt; &lt;h4&gt;Starting the Server&lt;/h4&gt;To start MongoDB, open the command prompt window, and run mongod.exe from the bin directory (specify the data path if needed)&lt;br&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhLYFSj0QJkVFK1yydUedpIvsd5YeopM1lneMymjWznveiO1n_DqfUCP4zUsBLVKwdx4HXed2dQD72RIItYTUjOmvCuvBQaYLS2v03h076etNiBBbKtEUcqaT-qLoQK-Z479QcHlpJ9Nw/s1600-h/CWindowssystem32cmd.exe%252520-%252520mongod.exe%252520%252520--dbpath%252520Cmongodbdata_2013-07-09_16-10-49.png&quot;&gt;&lt;img style=&quot;background-image: none; border-bottom: 0px; border-left: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top: 0px; border-right: 0px; padding-top: 0px&quot; title=&quot;CWindowssystem32cmd.exe - mongod.exe  --dbpath Cmongodbdata_2013-07-09_16-10-49&quot; border=&quot;0&quot; alt=&quot;CWindowssystem32cmd.exe - mongod.exe  --dbpath Cmongodbdata_2013-07-09_16-10-49&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjPTHC1HLhFaXGuBtIV2LSZtW_OSVNQM46E5nKA0OrqlRa3_pDuScmfpzBAeVYSJ6CCSMa_FnHRYaxC0vzVS6No-5eWc78QNIbhV6-E7VhpttbknSrxdD3Db5uCCG0DeR08kKxpr64e0Q/?imgmax=800&quot; width=&quot;565&quot; height=&quot;109&quot;&gt;&lt;/a&gt;The &lt;tt&gt;waiting for connections&lt;/tt&gt; message in the console output indicates that the mongod.exe process is running successfully and waiting for connections on port 27017&lt;br&gt; &lt;h4&gt;Connecting to the Server&lt;/h4&gt;To connect to the server, open another command prompt window and run mongo.exe from the bin directory.&lt;br&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgs47KNf4kKqdeUR-NCIjrLBDlPVXsLfmFiNV80Tz5aJrUyQudthu0uZHiQNgDJJGtSd1pVtFIzEaRrlFrrvn6FIsJMWlB2IgVSRXnnAK4y1fohK5NcS9np3Y59vDAUwcfVLSz3sScs7w/s1600-h/CWindowssystem32cmd.exe%252520-%252520mongo_2013-07-09_16-27-37%25255B3%25255D.png&quot;&gt;&lt;img style=&quot;background-image: none; border-right-width: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px&quot; title=&quot;CWindowssystem32cmd.exe - mongo_2013-07-09_16-27-37&quot; border=&quot;0&quot; alt=&quot;CWindowssystem32cmd.exe - mongo_2013-07-09_16-27-37&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjUUkpiVUNQJ5DMlD0cYnovlY-7HCjir7CBenHIKXxYPDhu24r0e_4MTBfMsUbTqaC6-htoD2sUOOvSnaIRV5hPCz7lQIfLsVxRLs8zRp7KtKqg-OoA7S0r7CtnihknbXJ2SYIZ6W_smQ/?imgmax=800&quot; width=&quot;493&quot; height=&quot;165&quot;&gt;&lt;/a&gt;&lt;br&gt; &lt;h4&gt;Run MongoDB as a Windows Service&lt;/h4&gt; &lt;ol&gt; &lt;li&gt;Create a log file for MongoDB (in my case c:\mongodb\log\mongo.log ).  &lt;li&gt;Create a data directory for MongoDB (in my case c:\mongodb\data ).  &lt;li&gt;Open the command prompt window as an administrator.  &lt;li&gt;Run the following command &lt;span style=&quot;color: blue&quot;&gt;&lt;i&gt;C:\mongodb\bin&amp;gt;mongod.exe –install –rest –master --logpath &quot;c:\mongodb\log\mongo.log&quot;&lt;/i&gt;&lt;/span&gt;  &lt;li&gt;Run &lt;span style=&quot;color: blue&quot;&gt;regedit&lt;/span&gt; from start menu.  &lt;li&gt;Go to &lt;i&gt;HKEY_LOCAL_MACHINE &amp;gt;&amp;gt; SYSTEM &amp;gt;&amp;gt; CurrentControlSet &amp;gt;&amp;gt; services&lt;/i&gt;  &lt;li&gt;Find the MongoDB directory &amp;amp; edit the &lt;span style=&quot;color: blue&quot;&gt;&lt;i&gt;ImagePath&lt;/i&gt;&lt;/span&gt; key.  &lt;li&gt;Set value as &lt;i&gt;&lt;span style=&quot;color: blue&quot;&gt;c:\mongodb\bin\mongod --service&amp;nbsp; --rest&amp;nbsp; --master&amp;nbsp; --logpath=C:\mongodb\log\mongo.log&amp;nbsp; --dbpath=C:\mongodb\data&lt;/span&gt;&lt;/i&gt;  &lt;li&gt;Save and exit registry editor  &lt;li&gt;Open ComponentServices from Start menu &amp;gt;&amp;gt; Run  &lt;li&gt;Locate the Mongo DB service, and reigh click &amp;gt;&amp;gt; Properties.  &lt;li&gt;Set the Startup Type to Automatic. Then start the service.  &lt;ol&gt; &lt;li&gt;To run the MongoDB service from command window, use &lt;i&gt;&lt;span style=&quot;color: blue&quot;&gt;net start MongoDB&lt;/span&gt;&lt;/i&gt;&lt;/li&gt;&lt;/ol&gt; &lt;li&gt;Check at &lt;a href=&quot;http://localhost:28017/&quot;&gt;http://localhost:28017/&lt;/a&gt; to see , MongoDB should return stats.&lt;/li&gt;&lt;/ol&gt;&lt;span style=&quot;color: black&quot;&gt;In case you want to remove MongoDB service &lt;/span&gt;&lt;i&gt;&lt;span style=&quot;color: blue&quot;&gt;C:\mongodb\bin\mongod.exe –remove&lt;/span&gt;&lt;/i&gt;&lt;br&gt; &lt;h4&gt;Data Model&lt;/h4&gt;Data in MongoDB has a &lt;i&gt;flexible&lt;/i&gt; schema. &lt;br&gt; &lt;ul&gt; &lt;li&gt;Database consists on a set of collections.  &lt;li&gt;Collections consists of a set of documents.  &lt;ul&gt; &lt;li&gt;Documents in the same collection do not need to have the same set of fields or structure.  &lt;li&gt;Common fields in a collection’s documents can hold different types of data.&lt;/li&gt;&lt;/ul&gt;&lt;/li&gt;&lt;/ul&gt;Based on what we mentioned, you could say that MongoDB is schema-less. But you may refer to this &lt;a title=&quot;Data Modeling Considerations for MongoDB Applications&quot; href=&quot;http://docs.mongodb.org/manual/core/data-modeling/&quot; target=&quot;_blank&quot;&gt;data modeling article&lt;/a&gt; before doing real work on MongoDB.&lt;br&gt; &lt;h4&gt;CRUD operations&lt;/h4&gt; &lt;ul&gt; &lt;li&gt;When you start the mongo shell, it connect to test database by default. To create a new database or switch to another database, use &lt;b&gt;&lt;i&gt;&lt;span style=&quot;color: blue&quot;&gt;use newdb&lt;/span&gt;&lt;/i&gt;&lt;/b&gt;  &lt;li&gt;&lt;span style=&quot;color: black&quot;&gt;To show a list of databases, use &lt;b&gt;&lt;i&gt;show dbs &lt;/i&gt;&lt;/b&gt;(databases are created when you insert the first values in it. This means that any database have been created but no values inserted in it, it really doesn’t exist).&lt;/span&gt;  &lt;li&gt;&lt;span style=&quot;color: black&quot;&gt;To confirm the current session database, use &lt;b&gt;&lt;i&gt;db&lt;/i&gt;&lt;/b&gt;&lt;/span&gt;  &lt;li&gt;&lt;span style=&quot;color: black&quot;&gt;To create a collection, just insert an initial record to it. Since Mongo is schema-less, there is no need to define anything up front. The following code creates/inserts a towns collection:&lt;/span&gt;&lt;/li&gt;&lt;/ul&gt;&lt;span style=&quot;color: blue&quot;&gt;db.towns.insert({&lt;br&gt;name: &quot;New York&quot;,&lt;br&gt;population: 22200000,&lt;br&gt;last_census: ISODate(&quot;2009-07-31&quot;),&lt;br&gt;famous_for: [ &quot;statue of liberty&quot;, &quot;food&quot; ],&lt;br&gt;mayor : {&lt;br&gt;name : &quot;Michael Bloomberg&quot;,&lt;br&gt;party : &quot;I&quot;&lt;br&gt;}&lt;br&gt;})&lt;/span&gt;&lt;br&gt; &lt;ul&gt; &lt;ul&gt; &lt;li&gt;brackets like {...} denote an object with key-value pairs.  &lt;li&gt;brackets like [...] denote an array.  &lt;li&gt;You can nest these values to any depth.&lt;/li&gt;&lt;/ul&gt; &lt;li&gt;To show a list of collections, use &lt;b&gt;&lt;i&gt;show collections&lt;/i&gt;&lt;/b&gt;.  &lt;li&gt;To list the contents of a collection, use &lt;b&gt;&lt;i&gt;db.towns.find()&lt;/i&gt;&lt;/b&gt;  &lt;ul&gt; &lt;li&gt;You will see a system generated field &lt;b&gt;_id &lt;/b&gt;( composed of a timestamp, client machine ID, client process ID, and a 3-byte incremented counter) (you can override this system generated&lt;/li&gt;&lt;/ul&gt; &lt;li&gt;MongoDB commands are JavaScript functions.  &lt;ul&gt; &lt;li&gt;&lt;b&gt;db&lt;/b&gt; is a JavaScript object that contains information about the current database. Try &lt;span style=&quot;color: blue&quot;&gt;&lt;b&gt;typeof db&lt;/b&gt;&lt;/span&gt;  &lt;li&gt;&lt;b&gt;db.&lt;i&gt;x &lt;/i&gt;&lt;/b&gt;is a JavaScript object that represent a collection named &lt;i&gt;x&lt;/i&gt; within the current database. Try &lt;span style=&quot;color: blue&quot;&gt;&lt;b&gt;typeof db.towns&lt;/b&gt;&lt;/span&gt;  &lt;li&gt;&lt;b&gt;db.&lt;i&gt;x&lt;/i&gt;.help()&lt;/b&gt; will list available functions related to the given object. Try &lt;span style=&quot;color: blue&quot;&gt;&lt;b&gt;typeof db.towns.insert&lt;/b&gt;&lt;/span&gt;  &lt;li&gt;&lt;span style=&quot;color: black&quot;&gt;If you want to inspect the source code of a function, call it without parameter or parentheses.&lt;/span&gt;&lt;/li&gt;&lt;/ul&gt; &lt;li&gt;&lt;span style=&quot;color: black&quot;&gt;&lt;b&gt;Functions&lt;/b&gt; You can create JavaScript functions and call them on the mongo shell like:&lt;/span&gt;&lt;/li&gt;&lt;/ul&gt; &lt;blockquote&gt;&lt;span style=&quot;color: blue&quot;&gt;function insertCity( name, population, last_census, famous_for, mayor_info) {&lt;br&gt;db.towns.insert({&lt;br&gt;name:name,&lt;br&gt;population:population,&lt;br&gt;last_census: ISODate(last_census),&lt;br&gt;famous_for:famous_for,&lt;br&gt;mayor : mayor_info&lt;br&gt;});&lt;br&gt;}&lt;/span&gt;&lt;br&gt;&lt;span style=&quot;color: blue&quot;&gt;insertCity(&quot;Punxsutawney&quot;, 6200, &#39;2008-31-01&#39;, [&quot;phil the groundhog&quot;], { name : &quot;Jim Wehrle&quot; } )&lt;br&gt;insertCity(&quot;Portland&quot;, 582000, &#39;2007-20-09&#39;, [&quot;beer&quot;, &quot;food&quot;], { name : &quot;Sam Adams&quot;, party : &quot;D&quot; } )&lt;/span&gt;&lt;br&gt;&lt;span style=&quot;color: black&quot;&gt;Now have three towns in our collection&lt;/span&gt;&lt;br&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEghMmyr4XBeRMWdOiM8DzOEbLl743GfO1fQGf6eLiqUAeOSdhpEUNKioBGmw3ttzzMNMc_4qA1VTqoiGOpSdhhc6pOHfg0SUTONv5XT7Vr5RgNZ-5nQ1xnIynmvm8H0gDDRmYufVerHvQ/s1600-h/Command%252520Prompt%252520-%252520mongo_2013-07-11_14-35-39%25255B1%25255D.png&quot;&gt;&lt;img style=&quot;background-image: none; border-bottom: 0px; border-left: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top: 0px; border-right: 0px; padding-top: 0px&quot; title=&quot;Command Prompt - mongo_2013-07-11_14-35-39&quot; border=&quot;0&quot; alt=&quot;Command Prompt - mongo_2013-07-11_14-35-39&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEi4sUrdtaHbJwSEB6IZhCL7_D38oDwu3Vj2MmCfuj1uiI_q3meWLYfad2kHs6bTgWPDBccryT2LbjJipPj9fbtYfu5HPzAr1GiZOmCKjyoujb8SVWRr3Lw0EBCsVHNZHIQetYRikQiQIQ/?imgmax=800&quot; width=&quot;543&quot; height=&quot;208&quot;&gt;&lt;/a&gt;&lt;/blockquote&gt; &lt;ul&gt; &lt;li&gt;To get a specific document, we only need _id passed to &lt;b&gt;find()&lt;/b&gt; function in type ObjectId(&lt;b&gt;findOne()&lt;/b&gt; retrieves only one matching document). String can be converted to ObjectId using &lt;b&gt;ObjectId(str)&lt;/b&gt; function.&lt;/li&gt;&lt;/ul&gt;&amp;nbsp;&lt;span style=&quot;color: blue&quot;&gt;db.towns.find({ &quot;_id&quot; : ObjectId(&quot;51def56c1cf66f4c40bb7f4a&quot;) })&lt;/span&gt;&lt;br&gt; &lt;ul&gt; &lt;ul&gt; &lt;li&gt;The find() function also accepts an optional second parameter: a fields object we can use to filter which fields are retrieved. If we want only the town name (along with _id), pass in name with a value resolving to 1 (or true).&lt;/li&gt;&lt;/ul&gt;&lt;/ul&gt;&lt;span style=&quot;color: blue&quot;&gt;db.towns.find({ &quot;_id&quot; : ObjectId(&quot;51def56c1cf66f4c40bb7f4a&quot;) }, { name : 1})&lt;/span&gt;&lt;br&gt; &lt;ul&gt; &lt;ul&gt; &lt;li&gt;To retrieve all fields except name, set name to 0 (or false or null).&lt;/li&gt;&lt;/ul&gt;&lt;/ul&gt;&lt;span style=&quot;color: blue&quot;&gt;db.towns.find({ &quot;_id&quot; : ObjectId(&quot;51def56c1cf66f4c40bb7f4a&quot;) }, { name : 0})&lt;/span&gt;&lt;br&gt; &lt;ul&gt; &lt;ul&gt; &lt;li&gt;&lt;span style=&quot;color: black&quot;&gt;You can retrieve documents based on criteria other than _id. You can use regular expressions or any &lt;a title=&quot;Query, Update and Projection Operators&quot; href=&quot;http://docs.mongodb.org/manual/reference/operator/&quot; target=&quot;_blank&quot;&gt;operator&lt;/a&gt;.&lt;/span&gt;&lt;/li&gt;&lt;/ul&gt;&lt;/ul&gt;db.towns.find( { name : /^P/, population : { $lt : 10000 } }, { name : 1, population : 1 } )&lt;br&gt;We said before that the query language is JavaScript, which means we can construct operations as we would construct objects. In the following query, we build a criteria where the population must be between 10.000 and 1 million. Ranges work also on dates.&lt;br&gt;&lt;span style=&quot;color: blue&quot;&gt;&amp;gt; var population_range = {}&lt;br&gt;&amp;gt; population_range[&#39;$lt&#39;] = 100000&lt;br&gt;100000&lt;br&gt;&amp;gt; population_range[&#39;$gt&#39;] = 10000&lt;br&gt;10000&lt;br&gt;&amp;gt; population_range[&#39;$lt&#39;] = 1000000&lt;br&gt;1000000&lt;br&gt;&amp;gt; population_range[&#39;$gt&#39;] = 10000&lt;br&gt;10000&lt;br&gt;&amp;gt; db.towns.find( {name : /^P/, population : population_range }, {name: 1})&lt;br&gt;{ &quot;_id&quot; : ObjectId(&quot;51df08e72476b99608460870&quot;), &quot;name&quot; : &quot;Portland&quot; }&lt;/span&gt;&lt;br&gt; &lt;ul&gt; &lt;ul&gt; &lt;li&gt;&lt;span style=&quot;color: black&quot;&gt;You can also query based on values in nested arrays, either matching exact values or matching partial values or all matching values or the lack of matching values.&lt;/span&gt;&lt;/li&gt;&lt;/ul&gt;&lt;/ul&gt;&lt;span style=&quot;color: blue&quot;&gt;&amp;gt; db.towns.find( { famous_for : &#39;food&#39; }, { _id : 0, name : 1, famous_for : 1 } )&lt;br&gt;{ &quot;name&quot; : &quot;New York&quot;, &quot;famous_for&quot; : [&amp;nbsp; &quot;statue of liberty&quot;,&amp;nbsp; &quot;food&quot; ] }&lt;br&gt;{ &quot;name&quot; : &quot;Portland&quot;, &quot;famous_for&quot; : [&amp;nbsp; &quot;beer&quot;,&amp;nbsp; &quot;food&quot; ] }&lt;br&gt;&amp;gt; db.towns.find( { famous_for : /statue/ }, { _id : 0, name : 1, famous_for : 1 } )&lt;br&gt;{ &quot;name&quot; : &quot;New York&quot;, &quot;famous_for&quot; : [&amp;nbsp; &quot;statue of liberty&quot;,&amp;nbsp; &quot;food&quot; ] }&lt;br&gt;&amp;gt; db.towns.find( { famous_for : { $all : [&#39;food&#39;, &#39;beer&#39;] } }, { _id : 0, name:1, famous_for:1 } )&lt;br&gt;{ &quot;name&quot; : &quot;Portland&quot;, &quot;famous_for&quot; : [&amp;nbsp; &quot;beer&quot;,&amp;nbsp; &quot;food&quot; ] }&lt;br&gt;&amp;gt; db.towns.find( { famous_for : { $nin : [&#39;food&#39;, &#39;beer&#39;] } }, { _id : 0, name : 1, famous_for : 1 } )&lt;br&gt;{ &quot;name&quot; : &quot;Punxsutawney&quot;, &quot;famous_for&quot; : [&amp;nbsp; &quot;phil the groundhog&quot; ] }&lt;/span&gt;&lt;br&gt; &lt;ul&gt; &lt;ul&gt; &lt;li&gt;&lt;span style=&quot;color: black&quot;&gt;You can query a sub-document by giving the field name as a string separating nested layers with a dot.&lt;/span&gt;&lt;/li&gt;&lt;/ul&gt;&lt;/ul&gt;&lt;span style=&quot;color: blue&quot;&gt;&amp;gt; db.towns.find( { &#39;mayor.party&#39; : &#39;I&#39; }, { _id : 0, name : 1, mayor : 1 } )&lt;br&gt;{ &quot;name&quot; : &quot;New York&quot;, &quot;mayor&quot; : { &quot;name&quot; : &quot;Michael Bloomberg&quot;, &quot;party&quot; : &quot;I&quot; } }&lt;/span&gt;&lt;br&gt; &lt;ul&gt; &lt;ul&gt; &lt;li&gt;To query the nonexistence of a field value&lt;/li&gt;&lt;/ul&gt;&lt;/ul&gt;&lt;span style=&quot;color: blue&quot;&gt;&amp;gt; db.towns.find( { &#39;mayor.party&#39; : { $exists : false } }, { _id : 0, name : 1, mayor : 1 } )&lt;br&gt;{ &quot;name&quot; : &quot;Punxsutawney&quot;, &quot;mayor&quot; : { &quot;name&quot; : &quot;jim Wehrle&quot; } }&lt;/span&gt;&lt;br&gt; &lt;ul&gt; &lt;li&gt; &lt;h3&gt;elemMatch &lt;/h3&gt;&lt;/li&gt;&lt;/ul&gt;$elemMatch helps us specify if a document or a nested document matches all of our criteria, the document counts as a match and returned. We can use any advanced operators within this criteria. To show it in action, let’s insert some data into a new collection &lt;i&gt;countries&lt;/i&gt;&lt;br&gt;&lt;span style=&quot;color: blue&quot;&gt;&amp;gt; db.countries.insert({ _id : &quot;us&quot;,&lt;br&gt;... name : &quot;United States&quot;,&lt;br&gt;... exports : {&lt;br&gt;...&amp;nbsp; foods : [&lt;br&gt;...&amp;nbsp;&amp;nbsp; { name : &quot;bacon&quot;, tasty : true },&lt;br&gt;...&amp;nbsp;&amp;nbsp; { name : &quot;burgers&quot; }&lt;br&gt;...&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; ]&lt;br&gt;...&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; }&lt;br&gt;... })&lt;br&gt;&amp;gt; db.countries.insert({ _id : &quot;ca&quot;,&lt;br&gt;... name : &quot;Canada&quot;,&lt;br&gt;... exports : {&lt;br&gt;...&amp;nbsp; foods : [&lt;br&gt;...&amp;nbsp;&amp;nbsp; { name : &quot;bacon&quot;, tasty : false },&lt;br&gt;...&amp;nbsp;&amp;nbsp; { name : &quot;syrup&quot;, tasty : true }&lt;br&gt;...&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; ]&lt;br&gt;...&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; }&lt;br&gt;... })&lt;br&gt;&amp;gt; db.countries.insert({ _id : &quot;mx&quot;,&lt;br&gt;... name : &quot;Mexico&quot;,&lt;br&gt;... exports : {&lt;br&gt;...&amp;nbsp; foods : [&lt;br&gt;...&amp;nbsp;&amp;nbsp; { name : &quot;salsa&quot;, tasty : true, condiment : true }&lt;br&gt;...&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; ]&lt;br&gt;...&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; }&lt;br&gt;... })&lt;br&gt;&amp;gt; print( db.countries.count() )&lt;br&gt;3&lt;/span&gt;&lt;br&gt;Now if we need to select countries that export tasty bacon, we should $elemMatch in a query like:&lt;br&gt;&lt;span style=&quot;color: blue&quot;&gt;&amp;gt; db.countries.find(&lt;br&gt;... {&lt;br&gt;...&amp;nbsp;&amp;nbsp; &#39;exports.foods&#39; : {&lt;br&gt;...&amp;nbsp;&amp;nbsp;&amp;nbsp; $elemMatch : {&lt;br&gt;...&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; name : &quot;bacon&quot;,&lt;br&gt;...&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; tasty : true&lt;br&gt;...&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; }&lt;br&gt;...&amp;nbsp;&amp;nbsp; }&lt;br&gt;... },&lt;br&gt;... { _id : 0, name : 1 }&lt;br&gt;... )&lt;br&gt;{ &quot;name&quot; : &quot;United States&quot; }&lt;/span&gt;&lt;br&gt;If we didn’t used $elemMatch and wrote a query like the following, it will return countries that export bacon or tasty food, not tasty bacon&lt;br&gt;&lt;span style=&quot;color: blue&quot;&gt;&amp;gt; db.countries.find(&lt;br&gt;... { &#39;exports.foods.name&#39; : &#39;bacon&#39; , &#39;exports.foods.tasty&#39; : true },&lt;br&gt;... { _id : 0, name : 1 }&lt;br&gt;... )&lt;br&gt;{ &quot;name&quot; : &quot;United States&quot; }&lt;br&gt;{ &quot;name&quot; : &quot;Canada&quot; }&lt;/span&gt;&lt;br&gt; &lt;ul&gt; &lt;li&gt; &lt;h3&gt;Boolean Operators&lt;/h3&gt;&lt;/li&gt;&lt;/ul&gt;&lt;b&gt;$or&lt;/b&gt; a prefix for criteria to return document that match either condition1 or condition2. There is a a lot of &lt;a title=&quot;Query, Update and Projection Operators&quot; href=&quot;http://docs.mongodb.org/manual/reference/operator/&quot; target=&quot;_blank&quot;&gt;operators&lt;/a&gt; you can use.&lt;br&gt;&lt;span style=&quot;color: blue&quot;&gt;&amp;gt; db.countries.find({&lt;br&gt;... $or : [ { _id : &quot;mx&quot; } , { name : &quot;United States&quot; } ] },&lt;br&gt;... {_id : 1} )&lt;br&gt;{ &quot;_id&quot; : &quot;us&quot; }&lt;br&gt;{ &quot;_id&quot; : &quot;mx&quot; }&lt;/span&gt;&lt;br&gt; &lt;h3&gt;Update&lt;/h3&gt;The find() function toke two parameters, criteria and list of fields to return. The update() function works the same way. The first parameter is a criteria (the same way you will use to retreive the document through find()). The second parameter is an object whose fields will replace the matched document(s) or a modifier operation (&lt;b&gt;$set&lt;/b&gt; to set a field value, $unset to delete a field, &lt;b&gt;$inc&lt;/b&gt; to increment a field value by a number).&lt;br&gt;The following query will set the field state with the string OR for the matching document.&lt;br&gt;db.towns.update( { _id : ObjectId(&quot;4d0ada87bb30773266f39fe5&quot;) }, { $set : { &quot;state&quot; : &quot;OR&quot; } } )&lt;br&gt;but the following query will replace the matching document with a new document { state : “OR”}&lt;br&gt;db.towns.update( { _id : ObjectId(&quot;4d0ada87bb30773266f39fe5&quot;) }, { state : &quot;OR&quot; } )&lt;br&gt; &lt;h3&gt;References&lt;/h3&gt;Although MongoDB is schema-less but you can make one document reference another document using a construct like { $ref : “&lt;i&gt;collection_name&lt;/i&gt;”, $id : “&lt;i&gt;reference_id&lt;/i&gt;” }. In the following query we linking New York town with the country US. Notice the display of the new country field in the New York town document.&lt;br&gt;&lt;span style=&quot;color: blue&quot;&gt;&amp;gt; db.towns.update(&lt;br&gt;... { _id : ObjectId(&quot;51def56c1cf66f4c40bb7f4a&quot;) },&lt;br&gt;... { $set : { country : { $ref : &quot;countries&quot;, $id : &quot;us&quot; } } }&lt;br&gt;... )&lt;br&gt;&amp;gt; db.towns.find( { _id : ObjectId(&quot;51def56c1cf66f4c40bb7f4a&quot;) } )&lt;br&gt;{ &quot;_id&quot; : ObjectId(&quot;51def56c1cf66f4c40bb7f4a&quot;), &lt;u&gt;&quot;country&quot; : DBRef(&quot;countries&quot;, &quot;us&quot;)&lt;/u&gt;, &quot;famous_for&quot; : [&amp;nbsp; &quot;statue of liberty&quot;,&amp;nbsp; &quot;food&quot; ], &quot;last_census&quot; : ISODate(&quot;2009-07-31T00:00:00Z&quot;), &quot;mayor&quot; : { &quot;na&lt;br&gt;me&quot; : &quot;Michael Bloomberg&quot;, &quot;party&quot; : &quot;I&quot; }, &quot;name&quot; : &quot;New York&quot;, &quot;population&quot; : 22200000 }&lt;/span&gt;&lt;span style=&quot;color: black&quot;&gt;Now we can retrieve New york from towns collection, then use it to retrieve its country &lt;/span&gt;&lt;br&gt;&lt;span style=&quot;color: blue&quot;&gt;&amp;gt; var NY = db.towns.findOne( { _id : ObjectId(&quot;51def56c1cf66f4c40bb7f4a&quot;) } )&lt;br&gt;&amp;gt; db.countries.findOne( { _id : NY.country.$id })&lt;br&gt;{&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &quot;_id&quot; : &quot;us&quot;,&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &quot;name&quot; : &quot;United States&quot;,&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &quot;exports&quot; : {&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &quot;foods&quot; : [&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; {&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &quot;name&quot; : &quot;bacon&quot;,&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &quot;tasty&quot; : true&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; },&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; {&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &quot;name&quot; : &quot;burgers&quot;&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; }&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; ]&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; }&lt;br&gt;}&lt;/span&gt;&lt;br&gt;or in a different way &lt;span style=&quot;color: blue&quot;&gt;&amp;gt; db[ NY.country.$ref ].findOne( { _id : NY.country.$id} )&lt;/span&gt;&lt;br&gt; &lt;h3&gt;Delete&lt;/h3&gt;&lt;span style=&quot;color: blue&quot;&gt;&lt;span style=&quot;color: black&quot;&gt;Removing documents from a collections is simple, use your criteria with a call to &lt;b&gt;remove()&lt;/b&gt; function and all matching documents will be removed. It’s a recommended practice to build your criteria in an object, use that criteria to ensure that matching documents are the expected ones, pass this criteria to remove() function.&lt;/span&gt;&lt;/span&gt;&lt;br&gt;&amp;gt; var bad_bacon = { &#39;exports.foods&#39; : {&lt;br&gt;... $elemMatch : { name : &#39;bacon&#39;, tasty : false }&lt;br&gt;... } }&lt;br&gt;&amp;gt; db.countries.find ( bad_bacon)&lt;br&gt;{ &quot;_id&quot; : &quot;ca&quot;, &quot;name&quot; : &quot;Canada&quot;, &quot;exports&quot; : { &quot;foods&quot; : [&amp;nbsp;&amp;nbsp;&amp;nbsp; {&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &quot;name&quot; : &quot;bacon&quot;,&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &quot;tasty&quot; : false },&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; {&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &quot;name&quot; : &quot;syrup&quot;,&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &quot;tasty&quot; : true } ] } }&lt;br&gt;&amp;gt; db.countries.remove( bad_bacon)&lt;br&gt;&amp;gt; db.countries.count()&lt;br&gt;2&lt;br&gt;&lt;br&gt; &lt;h3&gt;Reading with Code&lt;/h3&gt;You could ask MongoDb to run a decision function across documents.&lt;br&gt; &lt;blockquote&gt;&lt;span style=&quot;color: blue&quot;&gt;db.towns.find(&amp;nbsp; function() {&lt;br&gt;return this.population &amp;gt; 6000 &amp;amp;&amp;amp; this.population &amp;lt; 600000;&lt;br&gt;} )&lt;/span&gt;&lt;/blockquote&gt;or in a short-hand format &lt;span style=&quot;color: blue&quot;&gt;db.towns.find(&quot;this.population &amp;gt; 6000 &amp;amp;&amp;amp; this.population &amp;lt; 600000&quot;)&lt;/span&gt;&lt;br&gt;&lt;span style=&quot;color: black&quot;&gt;or combine custom code with other criteria using &lt;b&gt;$where&lt;/b&gt;&lt;/span&gt;&lt;br&gt; &lt;blockquote&gt;&lt;span style=&quot;color: blue&quot;&gt;db.towns.find( {&lt;br&gt;$where : &quot;this.population &amp;gt; 6000 &amp;amp;&amp;amp; this.population &amp;lt; 600000&quot;,&lt;br&gt;famous_for : /groundhog/&lt;br&gt;} )&lt;/span&gt;&lt;/blockquote&gt;Custom code should be your last resort due to the following:&lt;br&gt; &lt;ol&gt; &lt;li&gt;Custom code queries run slower than regular queries. &lt;li&gt;Custom code queries can’t be indexed. &lt;li&gt;MongoDb can’t optimize custom code queries. &lt;li&gt;If your custom code assume the existence of a particular field and this field is missing in a single, the entire query will fail.&lt;/li&gt;&lt;/ol&gt;In this post we explored the basics of MongoDB, a rising star in the NoSQL family and the most common document database. We saw how to install and configure it. We saw how we can store nested structured data as JSON objects and query that data at any depth. We How we can update and delete data. In the next post we going to dig deep into MongoDB.   </description><link>http://ebeid-soliman.blogspot.com/2013/07/getting-started-with-mongodb-part-1.html</link><author>noreply@blogger.com (Ebeid Soliman ElSayed)</author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjPTHC1HLhFaXGuBtIV2LSZtW_OSVNQM46E5nKA0OrqlRa3_pDuScmfpzBAeVYSJ6CCSMa_FnHRYaxC0vzVS6No-5eWc78QNIbhV6-E7VhpttbknSrxdD3Db5uCCG0DeR08kKxpr64e0Q/s72-c?imgmax=800" height="72" width="72"/></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-59384554657271185.post-1260260134339026870</guid><pubDate>Tue, 09 Jul 2013 22:27:00 +0000</pubDate><atom:updated>2013-07-09T17:27:00.396-05:00</atom:updated><category domain="http://www.blogger.com/atom/ns#">Apache Cassandra</category><category domain="http://www.blogger.com/atom/ns#">Cassandra</category><category domain="http://www.blogger.com/atom/ns#">NoSQL</category><title>Getting Started with Apache Cassandra</title><description>&lt;p&gt;Apache &lt;a href=&quot;http://cassandra.apache.org/&quot; target=&quot;_blank&quot;&gt;Cassandra&lt;/a&gt; is “an open source, distributed, decentralized, elastically scalable, highly available, fault-tolerant, tuneably consistent, column-oriented database that bases its distribution design on Amazon’s &lt;a title=&quot;Dynamo: Amazon&amp;rsquo;s Highly Available Key-value Store&quot; href=&quot;http://www.read.seas.harvard.edu/~kohler/class/cs239-w08/decandia07dynamo.pdf&quot; target=&quot;_blank&quot;&gt;Dynamo&lt;/a&gt; and its data model on Google’s &lt;a title=&quot;Bigtable: A Distributed Storage System for Structured Data&quot; href=&quot;http://static.googleusercontent.com/external_content/untrusted_dlcp/research.google.com/en/us/archive/bigtable-osdi06.pdf&quot; target=&quot;_blank&quot;&gt;Bigtable&lt;/a&gt;” (source: “Cassandra: The Definitive Guide,” O’Reilly Media, 2010, p. 14).&lt;/p&gt; &lt;p&gt;Cassandra is built to store lots of data across a variety of machines arranged in a ring, in other words scaling horizontally, rather than vertically. &lt;/p&gt; &lt;h4&gt;Data Model&lt;/h4&gt; &lt;p&gt;&lt;strong&gt;Cassandra is based on a key-value model &lt;/strong&gt;and it is organized according to the following concepts:&lt;/p&gt; &lt;ul&gt; &lt;li&gt;&lt;strong&gt;Column&lt;/strong&gt; is a key-value pair.&lt;/li&gt;&lt;/ul&gt; &lt;p&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEieuEmXEk_jQRd-uDAXqw4Zizz4z0Tuw65PluyAZlZYTSgLa9_FAoAbsZ1lQO2pJueJsDnOdpZMsy7Ri5uyTaBOGpNwJ_XZH1msUh9ber17GBo2wKXOrhkEEeHuvTsYV3YVYvtFi_OOLQ/s1600-h/Cassandra_DataModel_CheatSheet.pdf%252520-%252520Adobe%252520Reader_2013-07-03_15-59-51%25255B2%25255D.png&quot;&gt;&lt;img style=&quot;background-image: none; border-right-width: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px&quot; title=&quot;Cassandra_DataModel_CheatSheet.pdf - Adobe Reader_2013-07-03_15-59-51&quot; border=&quot;0&quot; alt=&quot;Cassandra_DataModel_CheatSheet.pdf - Adobe Reader_2013-07-03_15-59-51&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiRSp7Sc55ChGWklMt2D84EK5RPwAYDOQaWmpGdKfr88FboLoeNBx0pnC4Es3pVqQQumtObbk-mphtdOv51y6_VGqz1DO8n7Pn3W0kgIMLBPKGmluo2CafcnBy5MS8Ef_2E9HT4qG1LeQ/?imgmax=800&quot; width=&quot;104&quot; height=&quot;159&quot;&gt;&lt;/a&gt;&lt;/p&gt; &lt;ul&gt; &lt;li&gt;&lt;strong&gt;Column Family&lt;/strong&gt; is a set of key-value pairs (columns in Cassandra’s terminology). They are sorted by their keys. Families are referenced and sorted by row keys.&lt;/li&gt;&lt;/ul&gt; &lt;p&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgFjDd8UKOLhd1nYvohZ6dyw9oLy1w8jGcMps-3aPjLjl5thMkuHFxDUaFw3350ID5KafhyTkrL6lHqmzQhthwW2YFB7cIifw_LRrP4Dxpl_Egdrek_uzLQcJRxc5UqqDHVIamdt5qjog/s1600-h/Cassandra_DataModel_CheatSheet.pdf%252520-%252520Adobe%252520Reader_2013-07-03_16-03-39%25255B5%25255D.png&quot;&gt;&lt;img style=&quot;background-image: none; border-right-width: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px&quot; title=&quot;Cassandra_DataModel_CheatSheet.pdf - Adobe Reader_2013-07-03_16-03-39&quot; border=&quot;0&quot; alt=&quot;Cassandra_DataModel_CheatSheet.pdf - Adobe Reader_2013-07-03_16-03-39&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgG0vZ7gScgYK-7yKYb2ku8bvPvPrm4hL4MZKQ-QcUmP0ABrB-yuCZkWP9IrXrpuzGESGWHfI0kRSGzHiCpQFTje9zgDKTjhCAARr6SaCCuGe_AFTVEJqIs35rcTiH6lSyAVqXeXy_yxQ/?imgmax=800&quot; width=&quot;343&quot; height=&quot;192&quot;&gt;&lt;/a&gt;&lt;/p&gt; &lt;ul&gt; &lt;li&gt;&lt;strong&gt;Super Column&lt;/strong&gt; the value of a key-value pair can be a sequence of key-value pairs as well. In this case, the outer column would be called &lt;em&gt;super column&lt;/em&gt;.&lt;/li&gt;&lt;/ul&gt; &lt;p&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhOu37rIMIok0kaHfj00SP7HRJg0M4MCKy5tvD6Kdjrmwk2oBcFIiBr34_bsX5x5hI18mgsUmBpQbF_WEFbSx2JiptHos8geqIFp_IpI9RY2zMUz_LJ0A4JNox-1JBSeo0L1iyel7MkQw/s1600-h/Cassandra_DataModel_CheatSheet.pdf%252520-%252520Adobe%252520Reader_2013-07-03_16-39-29%25255B2%25255D.png&quot;&gt;&lt;img style=&quot;background-image: none; border-right-width: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px&quot; title=&quot;Cassandra_DataModel_CheatSheet.pdf - Adobe Reader_2013-07-03_16-39-29&quot; border=&quot;0&quot; alt=&quot;Cassandra_DataModel_CheatSheet.pdf - Adobe Reader_2013-07-03_16-39-29&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgZ0YmJmmeHGx184kC1NvLOBH9JUgfjSweyK1atdmTEG7RSI3rrkPauI6nqJ1macSKtVKwTDnaYhWLxkDp0gDISGsUpxvBrpBPLFLKp4wmC1TI3VKFuaGUb6QhsLw7yrHOoXJcheuXGiQ/?imgmax=800&quot; width=&quot;244&quot; height=&quot;191&quot;&gt;&lt;/a&gt;&lt;/p&gt; &lt;ul&gt; &lt;li&gt;Columns and Super Columns can equally be used within Column Families&lt;/li&gt;&lt;/ul&gt; &lt;p&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhkAhRk3bMy6j1fTbwWfivvj-di1YCMLBKwYrsgXg4Rd2a-FWttlerL5brBcd9rC7cy2YKwHE1qwfhrCK9nVxvikxeTv5rxbXIIJ_bfN4C1uLK0gYS8imMXtLDuMV4X63t5_AssDdpavw/s1600-h/Cassandra_DataModel_CheatSheet.pdf%252520-%252520Adobe%252520Reader_2013-07-03_16-44-41%25255B3%25255D.png&quot;&gt;&lt;img style=&quot;background-image: none; border-right-width: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px&quot; title=&quot;Cassandra_DataModel_CheatSheet.pdf - Adobe Reader_2013-07-03_16-44-41&quot; border=&quot;0&quot; alt=&quot;Cassandra_DataModel_CheatSheet.pdf - Adobe Reader_2013-07-03_16-44-41&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjgWgMCGeNv6jJoYOw-FWn0JN4yS49zQuvp2v5cRFYvSYX1A5Ug9KaGRwmHVJAacocUN-uDkDyJzjGFc4cbKW21c14wAd8AiEqbZpwEEyfWkJWemEMZTtl2YkqkIXoPWXaVLqPvF55apw/?imgmax=800&quot; width=&quot;563&quot; height=&quot;207&quot;&gt;&lt;/a&gt;&lt;/p&gt; &lt;ul&gt; &lt;li&gt;Columns or Super Columns are stored ordered by names within their Column Families&lt;/li&gt;&lt;/ul&gt; &lt;p&gt;For a better understanding of Cassandra’s data model, refer to this &lt;a title=&quot;A Quick Introduction to the Cassandra Data Model&quot; href=&quot;http://maxgrinev.com/2010/07/09/a-quick-introduction-to-the-cassandra-data-model/&quot; target=&quot;_blank&quot;&gt;article&lt;/a&gt; by &lt;a href=&quot;https://twitter.com/maxgrinev&quot; target=&quot;_blank&quot;&gt;Maxim Grinev&lt;/a&gt;.  &lt;h4&gt;&amp;nbsp;&lt;/h4&gt; &lt;h4&gt;Installation&lt;/h4&gt; &lt;ol&gt; &lt;li&gt;Download the latest Cassandra version from &lt;a title=&quot;Cassandra Downloads Page&quot; href=&quot;http://cassandra.apache.org/download/&quot; target=&quot;_blank&quot;&gt;here&lt;/a&gt; (I got version 1.2.6).  &lt;li&gt;Extract the archive (I extracted it to &lt;em&gt;C:\apache-cassandra-1.2.6&lt;/em&gt; )  &lt;li&gt;If you don’t have Java installed on your machine, go and get it installed.  &lt;li&gt;Add environment variables  &lt;ol&gt; &lt;li&gt;Reight-click the my Computer icon on your desktop or start menu.  &lt;li&gt;Click the Advanced tab (or the Advanced System Settings)  &lt;li&gt;Under System Variables, click New (adjust for your own directories)  &lt;ol&gt; &lt;li&gt;Variable Name :&amp;nbsp; CASSANDRA_HOME  &lt;li&gt;Variable Value : C:\apache-cassandra-1.2.6  &lt;li&gt;click OK&lt;/li&gt;&lt;/ol&gt; &lt;li&gt;Under System Variables, click New (adjust for your own directories)  &lt;ol&gt; &lt;li&gt;Variable Name : JAVA_HOME  &lt;li&gt;Variable Value : C:\Program Files\Java\jre7  &lt;li&gt;click OK&lt;/li&gt;&lt;/ol&gt;&lt;/li&gt;&lt;/ol&gt; &lt;li&gt;Now, open command window and navigate to your bin directory inside Cassandra directory (C:\apache-cassandra-1.2.6\bin in my case).  &lt;li&gt;Launch Cassandra by executing the comand &lt;strong&gt;&lt;em&gt;&lt;font color=&quot;#0000ff&quot;&gt;cassandra –f&lt;/font&gt;&lt;/em&gt;&lt;/strong&gt; (the “-f” causes it to run in the foreground). You will see lots of messages coming out. If everything goes fine, it will end up with something like this:&lt;/li&gt;&lt;/ol&gt; &lt;p&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjBIrfoe_Fl44YIKeXwyUCZ9EXV065NSDqckXcoTJpXCkHTw6XHBF9nzmGRWSnxdtJ2bBoydO0pQz0-BmxzH1kF87EbNamdvrU3WY7nLzTnpMGwgvVfgo2ae1u4wjAImVbmNJrHsQnrsg/s1600-h/CWindowssystem32cmd.exe%252520-%252520cassandra%252520%252520-f_2013-07-03_11-18-19%25255B4%25255D.png&quot;&gt;&lt;img style=&quot;background-image: none; border-right-width: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px&quot; title=&quot;CWindowssystem32cmd.exe - cassandra  -f_2013-07-03_11-18-19&quot; border=&quot;0&quot; alt=&quot;CWindowssystem32cmd.exe - cassandra  -f_2013-07-03_11-18-19&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjASUlDRUSqrSs1rgK6GU76BuYgJ00AOWDuwuLklhP90_zuziFvkczNIrF5vS3c7h11i9z0udnZSRRl27z0hyphenhyphenrQhLSbsTjIs6fN6udMcLXTD7IbT2bFQsYcy2wwqf0S-13mVfrYO3FkqA/?imgmax=800&quot; width=&quot;568&quot; height=&quot;101&quot;&gt;&lt;/a&gt;&lt;/p&gt; &lt;p&gt;Now we have a running Cassandra server is expecting incoming connections on port 9160.&lt;/p&gt; &lt;p&gt;Once Cassandra is up and running on your machine, we can connect to the running instance using the Cassandra command-line interface, launched by running “cassandra-cli.bat”, from the Cassandra “bin” directory.&lt;/p&gt; &lt;p&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgr4IDPCGnsimyJod4ayyEcIanOZneJtTLnpA9EPafUKj188eNE0kR-znSoWApVNdTlI4W5_GcJpkjpQcQ_HVHmX-gXibN3ADhY-KajBt_3dt45rQEiU_Vrxac3eZQKuuvHzuqKEHN1gg/s1600-h/CWindowssystem32cmd.exe%252520-%252520cassandra-cli.bat_2013-07-03_12-16-36%25255B3%25255D.png&quot;&gt;&lt;img style=&quot;background-image: none; border-right-width: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px&quot; title=&quot;CWindowssystem32cmd.exe - cassandra-cli.bat_2013-07-03_12-16-36&quot; border=&quot;0&quot; alt=&quot;CWindowssystem32cmd.exe - cassandra-cli.bat_2013-07-03_12-16-36&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEj19NwqP4z5eU3L9KjSk758pLxJ_cQSgj3mY9ycqJTJi917p96hnfW2G9ZRYDGuF0iFWDhci1JQSCF1u8sA8l4KMQVFwoN1deOEpIlS3-Sf5M8FHBoc9L7_8oUn-qTtS_Aw2C2TJytQbQ/?imgmax=800&quot; width=&quot;307&quot; height=&quot;97&quot;&gt;&lt;/a&gt;&lt;/p&gt; &lt;h4&gt;Commads&lt;/h4&gt; &lt;ul&gt; &lt;li&gt;&lt;font color=&quot;#0000ff&quot;&gt;&lt;strong&gt;show api version;&lt;/strong&gt;&lt;/font&gt; to show the current api version.  &lt;li&gt;&lt;strong&gt;&lt;font color=&quot;#0000ff&quot;&gt;describe cluster;&lt;/font&gt;&lt;/strong&gt; to show a description of the current cluster.&lt;/li&gt;&lt;/ul&gt; &lt;p&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEj2qcID2u-J3QQmMoV0W8gOfoQ1-ZqZLNNTjhPbRz_3guiEJdkG1t0edzGljzGORgi3PjYsWbmV6AsTWWOaJtlgzjf7Y_7tU7RLSqI0UrJitEwGk4dwfs5siqzSmzZi_3SuccFqE6RaEg/s1600-h/CWindowssystem32cmd.exe%252520-%252520cassandra-cli.bat_2013-07-05_12-59-46%25255B3%25255D.png&quot;&gt;&lt;img style=&quot;background-image: none; border-right-width: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px&quot; title=&quot;CWindowssystem32cmd.exe - cassandra-cli.bat_2013-07-05_12-59-46&quot; border=&quot;0&quot; alt=&quot;CWindowssystem32cmd.exe - cassandra-cli.bat_2013-07-05_12-59-46&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjxlCzUZ9x9HPzgJyi3zS4A2dRF1Zg798OqcEZ1ZoxqkYbAxf7DtlCaf_LGFSiKDMT2DVOzZJR6NHfuulAc5MrCpvv84LWVH0naAMlLtRtj0xY3aVsRWOVnMGEPEVEJs-SfXaN8JQ3ABA/?imgmax=800&quot; width=&quot;573&quot; height=&quot;156&quot;&gt;&lt;/a&gt;&lt;/p&gt; &lt;ul&gt; &lt;li&gt;&lt;font color=&quot;#0000ff&quot;&gt;&lt;strong&gt;create keyspace&lt;/strong&gt; &lt;em&gt;TestKS;&lt;/em&gt;&lt;/font&gt; to create a keyspace and it have to be a unique name.  &lt;li&gt;&lt;font color=&quot;#0000ff&quot;&gt;&lt;strong&gt;use&lt;/strong&gt; &lt;em&gt;TestKS;&lt;/em&gt;&lt;/font&gt; to switch to keyspace TestKS.  &lt;li&gt;&lt;font color=&quot;#0000ff&quot;&gt;&lt;strong&gt;create column family&lt;/strong&gt; &lt;em&gt;TestCF;&lt;/em&gt;&lt;/font&gt; to create a column family TestCF within the current keyspace.  &lt;ul&gt; &lt;li&gt;No other schema definition is required, the column family is a collection of name/value pairs.&lt;/li&gt;&lt;/ul&gt; &lt;li&gt;&lt;code&gt;&lt;font face=&quot;Arial&quot;&gt;&lt;font color=&quot;#0000ff&quot;&gt;&lt;strong&gt;set&lt;/strong&gt; &lt;em&gt;TestCF[ascii(&#39;TestKey&#39;)][ascii(&#39;column1&#39;)]=ascii(&#39;TestValue&#39;);&lt;/em&gt;&lt;/font&gt;&amp;nbsp;&lt;/font&gt;&lt;/code&gt;to insert the TestKey/TestValue key/value pair into the column named column1 within the column family TestCF. You can use the &lt;font color=&quot;#0000ff&quot;&gt;&lt;strong&gt;with ttl =&lt;/strong&gt; &lt;em&gt;x&lt;/em&gt;&lt;/font&gt; setting at the end of the set command to make the column self-delete aft &lt;em&gt;x&lt;/em&gt; seconds of the insertion time.  &lt;ul&gt; &lt;li&gt;by default Cassandra treats data as byte arrays but you can convert to other types such as &lt;strong&gt;&lt;font color=&quot;#0000ff&quot;&gt;Long&lt;/font&gt;&lt;/strong&gt;, &lt;strong&gt;&lt;font color=&quot;#0000ff&quot;&gt;int&lt;/font&gt;&lt;/strong&gt;, &lt;strong&gt;&lt;font color=&quot;#0000ff&quot;&gt;integer&lt;/font&gt;&lt;/strong&gt;,…. Also &lt;font color=&quot;#0000ff&quot;&gt;&lt;strong&gt;timeuuid()&lt;/strong&gt;&lt;/font&gt; generates new UUID. For full information about set command: &lt;strong&gt;&lt;font color=&quot;#0000ff&quot;&gt;type help set;&lt;/font&gt;&lt;/strong&gt;&lt;/li&gt;&lt;/ul&gt; &lt;li&gt;&lt;code&gt;&lt;font face=&quot;Arial&quot;&gt;&lt;font color=&quot;#0000ff&quot;&gt;&lt;strong&gt;get&lt;/strong&gt; &lt;em&gt;TestCF[ascii(&quot;TestKey&quot;)];&lt;/em&gt;&lt;/font&gt; to retrieve the value stored in the key &lt;em&gt;TestKey&lt;/em&gt; within the column family &lt;em&gt;TestCF&lt;/em&gt;&lt;/font&gt;&lt;/code&gt;&lt;/li&gt;&lt;/ul&gt; &lt;p&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhShKlZ8zPZJJhv77bjhyNqCWO554MiLjPTbTtXyhxhHLtSA5Fck2oxnVRguDBcjHDJEWLYquV2WDUjIrJ5AAiMvx4LQ3Us6zVK-frJ0pJD8YVhTC5g375GMIJZuBzCIq7D8T_q_cfk4g/s1600-h/CWindowssystem32cmd.exe%252520-%252520cassandra-cli.bat_2013-07-05_11-15-32%25255B3%25255D.png&quot;&gt;&lt;img style=&quot;background-image: none; border-right-width: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px&quot; title=&quot;CWindowssystem32cmd.exe - cassandra-cli.bat_2013-07-05_11-15-32&quot; border=&quot;0&quot; alt=&quot;CWindowssystem32cmd.exe - cassandra-cli.bat_2013-07-05_11-15-32&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjJJAqUr1UEzB-2r4mQecz8NJC_h95pzszydWVghREBgwRmOyJYBMKr3SLhvqHE4L2DqZ3lEgKvYcffCFjWci5ww91iyVPyshLNqd6etlOPaXSNV_ujGd7QtqX7_h83Vbf4bEghINoZZg/?imgmax=800&quot; width=&quot;572&quot; height=&quot;170&quot;&gt;&lt;/a&gt;&lt;/p&gt; &lt;ul&gt; &lt;li&gt;&lt;font color=&quot;#0000ff&quot;&gt;&lt;strong&gt;del&lt;/strong&gt; &lt;em&gt;TestCF[ascii(‘TestKey’)][ascii(‘column2’)];&lt;/em&gt;&lt;/font&gt; rows and columns can be deleted by specifying the row key and/or the column name&lt;br&gt;with the del (delete) command.&lt;/li&gt;&lt;/ul&gt; &lt;p&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgIkl_wSGgTtqI1LfbBnfTOn1vYOdzazWnYKYfuVS9qJt_ZdW7GfTJSwx7cyKWe4APnisNGtNAh5ZPCp2o111ABc8S_SZCpmdoEaM4Ut9vxuNg8N-tGgMAA94xeXdyn0tCroigIyj5WMw/s1600-h/CWindowssystem32cmd.exe%252520-%252520cassandra-cli.bat_2013-07-05_15-29-44%25255B3%25255D.png&quot;&gt;&lt;img style=&quot;background-image: none; border-right-width: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px&quot; title=&quot;CWindowssystem32cmd.exe - cassandra-cli.bat_2013-07-05_15-29-44&quot; border=&quot;0&quot; alt=&quot;CWindowssystem32cmd.exe - cassandra-cli.bat_2013-07-05_15-29-44&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhbdXo6htnz8sT5Mfw60aRYmNihTgMXFBEXk7EnkNHmBJVkC1xe9h1Fa_bTFKlGwWlTOlZeE4IhA-wIARdofYqYSdVFO1uNmP_jzcB7eoHNOYpuA4BJaeXByQxymlDXvyf4pXgxSHUQ3g/?imgmax=800&quot; width=&quot;577&quot; height=&quot;126&quot;&gt;&lt;/a&gt;&lt;/p&gt; &lt;ul&gt; &lt;li&gt;&lt;font color=&quot;#0000ff&quot;&gt;&lt;strong&gt;list&lt;/strong&gt; &lt;em&gt;TestCF;&lt;/em&gt;&lt;/font&gt; list the data inside a column family&lt;/li&gt;&lt;/ul&gt; &lt;p&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhrwtfKfTXa_5IyryBUxHrARrVEPyOTDAsmusJRFJ4UMT2bVSaBdf0YL0f1Stc22f18kW0b5NndPZgjgoXCHwdMbnuieoASHhIifQMDE0dWY_oLgvvzQdNbvMNYXPTAA7PtGjC2Bc3-eg/s1600-h/CWindowssystem32cmd.exe%252520-%252520cassandra-cli.bat_2013-07-05_16-05-31%25255B3%25255D.png&quot;&gt;&lt;img style=&quot;background-image: none; border-right-width: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px&quot; title=&quot;CWindowssystem32cmd.exe - cassandra-cli.bat_2013-07-05_16-05-31&quot; border=&quot;0&quot; alt=&quot;CWindowssystem32cmd.exe - cassandra-cli.bat_2013-07-05_16-05-31&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjOdYodtR_tvEPOiUjUC7taADm_OLzUbCWa6RF0_afJmWqym4aIV-o5jUkt6Ri9fxazB3_YLEJzAA_93b9tdEWdrcXfdck9lQ2dCwhB9ub35iAQp5jtKb-5AKJwYDOJCkyEM3zcTASJxg/?imgmax=800&quot; width=&quot;585&quot; height=&quot;340&quot;&gt;&lt;/a&gt;&lt;/p&gt; &lt;ul&gt; &lt;li&gt;&lt;font color=&quot;#0000ff&quot;&gt;&lt;strong&gt;drop column family&lt;/strong&gt; &lt;em&gt;TestCF;&lt;/em&gt;&lt;/font&gt; removes a column family.  &lt;li&gt;&lt;font color=&quot;#0000ff&quot;&gt;&lt;strong&gt;drop&lt;/strong&gt; &lt;strong&gt;keyspace&lt;/strong&gt; &lt;em&gt;TestKS;&lt;/em&gt;&lt;/font&gt; removes a key space.&lt;/li&gt;&lt;/ul&gt; &lt;p&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEh-E74Mh8VuQX2QhObOHPrENUNKTIJmYEL44DJj1wuC4R3T4OUSsVCILb7mkjU80S_zAm_wugohytVPS1TMVP-N4O9JjGWijWY4EC7Jb0RMgbdLhl6hngCXNoUO3qki8hEq02GwJWL6cA/s1600-h/CWindowssystem32cmd.exe%252520-%252520cassandra-cli.bat_2013-07-05_16-25-05%25255B3%25255D.png&quot;&gt;&lt;img style=&quot;background-image: none; border-right-width: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px&quot; title=&quot;CWindowssystem32cmd.exe - cassandra-cli.bat_2013-07-05_16-25-05&quot; border=&quot;0&quot; alt=&quot;CWindowssystem32cmd.exe - cassandra-cli.bat_2013-07-05_16-25-05&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiMNHlIqTYT2MzHy2C-LSbSPi76wd6tiZHDYs3Rj0GYc4zcyoAU5SqZpstPgJDtJ-At_8G80xvYBBZ5mR-Z-c8TcQKDSHqVQtgIz_K-fNuA8yb_kYshd_WrXLlrNd87OLF9eviSQHWZYg/?imgmax=800&quot; width=&quot;433&quot; height=&quot;90&quot;&gt;&lt;/a&gt;&lt;/p&gt; &lt;p&gt;==&amp;gt; You can insert to super columns much like inserting to normal columns. They can be read with get, written with set, and deleted with del. The super column version of these commands uses an extra [&#39;xxx&#39;] to represent the extra sub-index level.&lt;/p&gt; &lt;p&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgYpHGepOlrvITYzPI-t98z9H954ciPLLRXHm48X1BgdSoYLcAEKk2_48Xx1uQ3j2aJr3Z_1txHcQWlRY2Yz7jX-aljbVrr76GKPg9y4S7OOSWaLOvR66v1aBsl9ngBVdOxMH6h1OKYNg/s1600-h/CWindowssystem32cmd.exe%252520-%252520cassandra-cli.bat_2013-07-05_17-07-44%25255B5%25255D.png&quot;&gt;&lt;img style=&quot;background-image: none; border-right-width: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px&quot; title=&quot;CWindowssystem32cmd.exe - cassandra-cli.bat_2013-07-05_17-07-44&quot; border=&quot;0&quot; alt=&quot;CWindowssystem32cmd.exe - cassandra-cli.bat_2013-07-05_17-07-44&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiclu6hDysZrNtrRjfERFw9UCqPeBw17rSaN2GbJ36bFwfTI2I3EWDzSRmOjtuFOHhzBoFwcaBYjyDB82Zeu4Mcag7u-EWWeYxd13AF2YyVmkOhuABpK7_dCEPHwh1p3ru0B13vUc_2GA/?imgmax=800&quot; width=&quot;783&quot; height=&quot;367&quot;&gt;&lt;/a&gt;&lt;/p&gt; &lt;ul&gt; &lt;li&gt;&lt;font color=&quot;#0000ff&quot;&gt;&lt;strong&gt;assume&lt;/strong&gt; &lt;em&gt;TestCF&lt;/em&gt; &lt;strong&gt;comparator as ascii;&lt;/strong&gt;&lt;/font&gt; it decodes and helps display results of get and list requests inside the command-line interface. It can be used in the same way to set the &lt;strong&gt;&lt;font color=&quot;#0000ff&quot;&gt;validator&lt;/font&gt;&lt;/strong&gt; and &lt;strong&gt;&lt;font color=&quot;#0000ff&quot;&gt;keys&lt;/font&gt;&lt;/strong&gt;. By default, columns with no metadata are displayed in a hex format. This is done because row keys, column names, and column values are byte arrays. After using assume the column and value will be displayed rather than the hex code.&lt;/li&gt;&lt;/ul&gt; &lt;p&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjxdp-3i938W01fLU6N_KOSb3a8Mk5r9wQyd2jhFvc1Vq8rtBfMuGwjzcKRNHL6esI0FYJGQRNfComM_5ywRA-ERjmaK-BrKUeKx8DG5phVb_lUVP4sQQDfjsYdheJHH9KTusMkLmMQYg/s1600-h/CWindowssystem32cmd.exe%252520-%252520cassandra-cli.bat_2013-07-05_17-29-07%25255B4%25255D.png&quot;&gt;&lt;img style=&quot;background-image: none; border-right-width: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px&quot; title=&quot;CWindowssystem32cmd.exe - cassandra-cli.bat_2013-07-05_17-29-07&quot; border=&quot;0&quot; alt=&quot;CWindowssystem32cmd.exe - cassandra-cli.bat_2013-07-05_17-29-07&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEggPN3MKKqXpNy44720XNZi1PMDz2x_PcIaKEGp5TXHH8jyYz9MDgifvmAqwNPRqLA6YRs0nV9_j7RmWQBv1mJluuWTuc_3HMatJFh4eBysYPhDog1uwAsZ2IeJn2WfKBKg0ZJpYbstpA/?imgmax=800&quot; width=&quot;657&quot; height=&quot;317&quot;&gt;&lt;/a&gt;&lt;/p&gt; &lt;ul&gt; &lt;li&gt;&lt;strong&gt;Type Enforcement&lt;/strong&gt; : Cassandra is designed to store and retrieve simple byte arrays but it also have support for &lt;a title=&quot;CQL Data Types&quot; href=&quot;http://www.datastax.com/docs/1.1/references/cql/cql_data_types&quot; target=&quot;_blank&quot;&gt;built-in types&lt;/a&gt;. When creating or updating a column family, the user can supply column metadata that instructs the CLI Cassandra client on how to display data and help the server enforce types during insertion operations.&lt;br&gt;&lt;strong&gt;&lt;font color=&quot;#0000ff&quot;&gt;create column family User with comparator = UTF8Type;&lt;br&gt;update column family User with&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; column_metadata =&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; [&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; {column_name: first, validation_class: AsciiType},&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; {column_name: last, validation_class: AsciiType},&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; {column_name: age, validation_class: IntegerType, index_type: KEYS}&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; ];&lt;/font&gt;&lt;/strong&gt; &lt;li&gt;&lt;strong&gt;Querying data&lt;/strong&gt; : &lt;/li&gt;&lt;/ul&gt; &lt;p&gt;&lt;strong&gt;&lt;font color=&quot;#0000ff&quot;&gt;set User[ascii(&#39;jsmith&#39;)][ascii(&#39;first&#39;)] = ascii(&#39;John&#39;);&lt;br&gt;set User[ascii(&#39;jsmith&#39;)][ascii(&#39;last&#39;)] = ascii(&#39;Smith&#39;);&lt;br&gt;set User[ascii(&#39;jsmith&#39;)][ascii(&#39;age&#39;)] = &#39;38&#39;;&lt;/font&gt;&lt;/strong&gt;&lt;/p&gt; &lt;p&gt;&lt;strong&gt;&lt;font color=&quot;#0000ff&quot;&gt;get User where age = &#39;38&#39;;&lt;/font&gt;&lt;/strong&gt;&lt;/p&gt; &lt;ul&gt; &lt;li&gt;&lt;font color=&quot;#000000&quot;&gt;&lt;strong&gt;Update&lt;/strong&gt; is the same as set.&lt;/font&gt;&lt;/li&gt;&lt;/ul&gt; &lt;p&gt;&lt;strong&gt;&lt;font color=&quot;#0000ff&quot;&gt;set User[ascii(&#39;jsmith&#39;)][ascii(&#39;first&#39;)] = ascii(&#39;Jack&#39;);&lt;/font&gt;&lt;/strong&gt;&lt;/p&gt; &lt;ul&gt; &lt;li&gt;&lt;font color=&quot;#000000&quot;&gt;&lt;strong&gt;Quite&lt;/strong&gt; the client;&lt;/font&gt;&lt;/li&gt;&lt;/ul&gt; &lt;p&gt;&lt;strong&gt;&lt;font color=&quot;#0000ff&quot;&gt;quit;&lt;/font&gt;&lt;/strong&gt;&lt;/p&gt; &lt;p&gt;&lt;strong&gt;&lt;font color=&quot;#0000ff&quot;&gt;&lt;/font&gt;&lt;/strong&gt;&amp;nbsp;&lt;/p&gt; &lt;p&gt;&lt;font color=&quot;#000000&quot;&gt;In this post we just touched the Cassandra’s iceberg. In later posts we will dig more in it and how to write .net programs against it.&lt;/font&gt;&lt;/p&gt;  </description><link>http://ebeid-soliman.blogspot.com/2013/07/getting-started-with-apache-cassandra.html</link><author>noreply@blogger.com (Ebeid Soliman ElSayed)</author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiRSp7Sc55ChGWklMt2D84EK5RPwAYDOQaWmpGdKfr88FboLoeNBx0pnC4Es3pVqQQumtObbk-mphtdOv51y6_VGqz1DO8n7Pn3W0kgIMLBPKGmluo2CafcnBy5MS8Ef_2E9HT4qG1LeQ/s72-c?imgmax=800" height="72" width="72"/></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-59384554657271185.post-8682505122423645519</guid><pubDate>Mon, 08 Jul 2013 16:53:00 +0000</pubDate><atom:updated>2013-07-08T11:53:33.494-05:00</atom:updated><title>جريدة الشروق : تقرير شهادات سكان عمارات العبور</title><description>&lt;h3&gt;سكان «عمارات العبور»: ضرب النار والغاز بدأ من الحرس الجمهوري بدون مقدمات&lt;/h3&gt; &lt;p&gt;&lt;strong&gt;تعليقات: 117&lt;/strong&gt;&lt;a href=&quot;http://shorouknews.com/news/view.aspx?cdate=08072013&amp;amp;id=28a98832-a914-4633-92d9-16fab99a42a1#Comments&quot;&gt;شارك بتعليقك&lt;/a&gt; &lt;h4&gt;&lt;br&gt;نشر فى : الإثنين 8 يوليو 2013 - 4:13 م&lt;br&gt;آخر تحديث : الإثنين 8 يوليو 2013 – 4:13 م&lt;/h4&gt; &lt;p&gt;&lt;img src=&quot;http://shorouknews.com/uploadedimages/Sections/Egypt/Eg-Politics/original/eshtbakat-1618.jpg&quot; width=&quot;290&quot; height=&quot;200&quot;&gt;&lt;br&gt;اشتباكات الحرس الجمهوري – أرشيفية &lt;p&gt;&lt;strong&gt;كتب- مصطفى هاشم:&lt;/strong&gt; &lt;p&gt;&lt;strong&gt;رصدت &quot;الشروق&quot; أحداث الحرس الجمهوري التي أودت بحياة أكثر من 50 من مؤيدي الرئيس المعزول محمد مرسي و2 من الشرطة، من خلال سكان العمارات المقابلة للحرس الجمهوري، والتي يطلق عليها عمارات&quot;العبور&quot;.&lt;/strong&gt; &lt;p&gt;&lt;strong&gt;&lt;br&gt;&lt;/strong&gt; &lt;p&gt;قال الدكتور محمود سليمان أحد السكان بالعمارة المقابلة للحرس الجمهوري &quot;استيقظت بعد الفجر مباشرة على صوت الرصاص والهليكوبتر واختناق بسبب قنابل الغاز المسيل للدموع رغم أن كل زجاج شقتنا كان مغلقا.. بدأت ارى ما يحدث من خلف الزجاج ووجدت دبابات الجيش والمدرعات ناحية المتظاهرين.. ووجدتهم يحرقون خيام المعتصمين، وكان معهم بعض الشباب الذين يرتدون زيا مدنيا&quot;. &lt;p&gt;وأضاف &quot;بعد 5 دقائق فقط من سماعي لصوت الرصاص دق باب شقتنا ووجدت 3 من الشباب يطلبون مني مساعدتهم لأن الجيش والشرطة تلاحقهم.. وبالفعل أدخلتهم في إحدى الغرف وأغلقتها عليهم.. بعدها بدقائق بسيطة كانت الشرطة العسكرية والشرطة قد ملأت عمارتنا وبدأت في ضرب النار داخل كل أدوار العمارة وبدأوا يهددون السكان، حتى أن الآثار موجودة.. ويدقون الأبواب بقوة وقاموا بكسر باب إحدى الشقق لأن صاحبها لم يفتح لهم لأنه لم يكن فيها أحد من الأساس&quot;. &lt;p&gt;وتابع: &quot;أعتقد أن الشرطة العسكرية ضربت النار على بعض المتظاهرين الذين كانوا يحتمون بعمارتنا.. ضرب النار من قبل الجيش والشرطة استمر لنحو ساعة كاملة وطائرة الهليكوبتر كانت تحلق في الجو لكشف ما يحدث&quot;. &lt;p&gt;وأكد سليمان أن سيارات الإسعاف لم تكن موجودة طوال الساعة، وجاءت بعدما انتهى ضرب النار لحمل الجثث من الشوارع ومن العمارات&quot;. &lt;p&gt;وحول المعتصمين الذين اختبأوا في شقته قال &quot;لم أخرجهم إلا الساعة العاشرة، واحدا بعد الآخر لأن معظم الشقق كان يختبئ فيها معتصمون وبدأنا في إخراجهم بالتتابع&quot;. &lt;p&gt;أما محمد ثابت عامل في جراج إحدى العمارات المقابلة للحرس الجمهوري فقال &quot;الشرطة والجيش فجأة وبدون مقدمات بدأت في ضرب النار والغاز اختنق أطفالي الصغار واستيقظوا مرعوبين.. رأيت بعض المعتصمين قد دخلوا في الجراج للاحتماء به وبعضهم اختبأ تحت بعض السيارات لكن الشرطة العسكرية والشرطة دخلوا وراءهم وبدؤوا في إخراجي أيضا معهم إلى أن خرجنا للشارع واعتبروني ضمن المعتصمين وبدؤوا في سبنا وإهانتنا وضربنا، إلى أن تعرف علي بعض الضباط والمجندين الذين يخدمون في الحرس الجمهوري لأنهم يعرفونني وأخرجوني من بينهم&quot;. &lt;p&gt;أما أحمد همام عامل أمن في إحدى مكاتب المحاسبة في إحدى العمارات المقابلة للحرس الجمهوري كنت أصلي الفجر مع المعتصمين أمام الحرس الجمهوري والإمام انتهى من الصلاة سريعا وبعدها بدأ بعض المشايخ ناشد الجيش بأن الاعتصام سلميا وأنهم إخوتهم بكن فجأة وبدون مقدمات وبدون أي استفزازات لأنني كنت معهم وهم أمام العمارة التي أعمل بها.. بدأ الجيش والشرطة في ضرب النار الحي والغاز المسيل للدموع. &lt;p&gt;وأضاف &quot;المعتصمون بدأوا في الجري ودخلوا بعض العمارات ومنهم العمارة التي أعمل بها، ولكن الشرطة العسكرية والشرطة ومباحث أمن الدولة لاحقوهم.. وأدخلت بعض النساء والأطفال والشباب داخل الشقة ووصل عددهم إلى 40 شخصا، وكانت منهم عضوة بمجلس الشعب المنحل عن حزب الحرية والعدالة..الشرطة العسكرية هددونا وهددوا السكان بضرب النار الحي إن لخرجوا من عندهم.. البعض استجاب وضربوا النار داخل العمارة التي أعمل بها&quot;. &lt;p&gt;وأضاف همام &quot;استمر المعتصمون في الاختباء عندي إلى الساعة 12 ظهرا وبدأت بعدذلك في إخراجهم واحدا تلو الآخر لأن الشرطة العسكرية ومباحث أمن الدولة يملئون الشوارع المحيطة بالحرس. &lt;p&gt;أما أحد المعتصمين الذين اختبأوا لدى إحدى الشقق السكنية أحمد الديب فقال &quot;لم نهاجم الحرس الجمهوري كما يقول بعض وسائل الإعلام ولو كنا نريد ذلك كنا هاجمناهم ونحن عددنا كبير بعد صلاة العشاء ولكن نحن لا نريد أن نفعل ذلك من الأساس&quot; &lt;p&gt;وحول بداية الأحداث قال &quot;أيقظني احدهم من النوم لصلاه الفجر استيقظت و ذهبت للوضوء ثم ذهبت للصلاة أمام الحرس الجمهوري بدا الإمام يدعي في الركعة الثانية وبدون سابق إنذار تلعثم وأنهى الدعاء و في نهايه الصلاة بدأ الضرب من 3 محاور هي صلاح سالم، ويوسف عباس، ونادي الحرس الجمهوري نفسه&quot;. &lt;p&gt;وأضاف الديب &quot;بدأت قنابل الغاز.. ولم نكن ندري أين نذهب فنحن محاصرون بضرب الخرطوش والآلي والرصاص الحي من كل اتجاه بدون حرمه للنساء ولا الأطفال، وسقط عدد كبير من القتلى من الأطفال والنساء وكبار السن، وسقط عدد ضخم من الإصابات والإغماءات.. اختبأت في أحد العمارات وهرع عدد من المتظاهرين معي و اختبأنا وعدد كبير من النساء دخلوا احد الشقق و أغلقنا عليهم و لم اعلم مصيرهم بعد وهجم الأمن والجيش على العمارة و اعتقلوا كل من صعد اليها و لكن حماني الله عندما فتح احد السكان شقته لي وانقطعت علاقتي بالشارع حتي الظهر&quot;. &lt;p&gt;------------------------------------------------------------&lt;/p&gt; &lt;p&gt;The above article is retrieved from the Google cashed version because the original have been deleted.&lt;/p&gt; &lt;p&gt;&lt;a href=&quot;http://webcache.googleusercontent.com/search?q=cache%3Ahttp%3A%2F%2Fshorouknews.com%2Fnews%2Fview.aspx%3Fcdate%3D08072013%26id%3D28a98832-a914-4633-92d9-16fab99a42a1&amp;amp;rlz=1C1CHKZ_enEG430EG430&amp;amp;oq=cache%3Ahttp%3A%2F%2Fshorouknews.com%2Fnews%2Fview.aspx%3Fcdate%3D08072013%26id%3D28a98832-a914-4633-92d9-16fab99a42a1&amp;amp;aqs=chrome.0.57j58.1469j0&amp;amp;sourceid=chrome&amp;amp;ie=UTF-8&quot;&gt;http://webcache.googleusercontent.com/search?q=cache%3Ahttp%3A%2F%2Fshorouknews.com%2Fnews%2Fview.aspx%3Fcdate%3D08072013%26id%3D28a98832-a914-4633-92d9-16fab99a42a1&amp;amp;rlz=1C1CHKZ_enEG430EG430&amp;amp;oq=cache%3Ahttp%3A%2F%2Fshorouknews.com%2Fnews%2Fview.aspx%3Fcdate%3D08072013%26id%3D28a98832-a914-4633-92d9-16fab99a42a1&amp;amp;aqs=chrome.0.57j58.1469j0&amp;amp;sourceid=chrome&amp;amp;ie=UTF-8&lt;/a&gt;&lt;/p&gt; &lt;p&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgx0XfhSuvnCbXsQjVQfQfgtNyZu7KAbY4WhRki0EQwsKqIwwWb1CEBAM98Kkj2GZaEOeidBbWQ4WjEJDoNq_l18HKMiSj9Gh3Zf1jraaAbwMeuXbJrA8JCUOW5lcju3Us0EX-WO1q0EQ/s1600-h/E%252527*%252520-%252520%252528H%252527%252528%252529_2013-07-08_11-47-35%25255B4%25255D.png&quot;&gt;&lt;img style=&quot;background-image: none; border-bottom: 0px; border-left: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top: 0px; border-right: 0px; padding-top: 0px&quot; title=&quot;سكان &amp;laquo;عمارات العبور&amp;raquo; ضرب النار والغاز بدأ من الحرس الجمهوري بدون مقدمات - بوابة_2013-07-08_11-47-35&quot; border=&quot;0&quot; alt=&quot;سكان &amp;laquo;عمارات العبور&amp;raquo; ضرب النار والغاز بدأ من الحرس الجمهوري بدون مقدمات - بوابة_2013-07-08_11-47-35&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiiN1qU0CyUT5F_cdElO0kNMnxgNh3B9HUic9NirUvWs7_pcRspt6phOwxvMunVkfkj_7OKZ083QBW9HQhib0OVHpWkTjZ8Nez2fEWkS6KElcbsYEv57RMdehkA07nv86-NkMz2aqu_Rg/*%252520-%252520%252528H%252527%252528%252529_2013-07-08_11-47-35_thumb%25255B2%25255D.png?imgmax=800&quot; width=&quot;599&quot; height=&quot;585&quot;&gt;&lt;/a&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEi_rI4VxE3kFalUQnh1SszuTzD01PNMtu3dJuHRGjRjz_QrJG44oiYyQxlR9KMtGtuIXDmKshIzxiNZUzIOxKpWALQo2I9QbPQCzOUm_Ql7aUKq4pBQ0ZvlEJej3YU0Yz-ZTnTI6v5d5A/s1600-h/E%252527*%252520-%252520%252528H%252527%252528%252529_2013-07-08_11-47-56%25255B4%25255D.png&quot;&gt;&lt;img style=&quot;background-image: none; border-bottom: 0px; border-left: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top: 0px; border-right: 0px; padding-top: 0px&quot; title=&quot;سكان &amp;laquo;عمارات العبور&amp;raquo; ضرب النار والغاز بدأ من الحرس الجمهوري بدون مقدمات - بوابة_2013-07-08_11-47-56&quot; border=&quot;0&quot; alt=&quot;سكان &amp;laquo;عمارات العبور&amp;raquo; ضرب النار والغاز بدأ من الحرس الجمهوري بدون مقدمات - بوابة_2013-07-08_11-47-56&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiToXLAhp8xlIDtGD-u03HjXfoL0XFJL1CueAQlyd7kJhVmus-dUIyiyTOHEk6LMoh9oPIo67Ju_4QI-WkyescHpyUHMKz2XiNeN3gR31lpoele7AYs1UOVCwuMOvGTd7aZpnQmXhQ6Dw/*%252520-%252520%252528H%252527%252528%252529_2013-07-08_11-47-56_thumb%25255B2%25255D.png?imgmax=800&quot; width=&quot;603&quot; height=&quot;579&quot;&gt;&lt;/a&gt;&lt;/p&gt;  &lt;p&gt;Now the article have been removed&lt;/p&gt; &lt;p&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjF_VgRwh7E17EJ30W3As3omsLbVBIHymmhxeuIvC7f9g0dmSIkOb_ONkbyVWIdv2BN5oCJlUZ5ivHrx0DePL2dROJCMSBBcrrcPJjlaEHhSVDbHkDWd_w8TyGSNQ9hkCd3moq7YPyZRg/s1600-h/.7%252523%252520-%252520%252528H%252527%252528%252529%252520%252527D41HB%252520-%252520Google%252520Chrome_2013-07-08_11-48-16%25255B2%25255D.png&quot;&gt;&lt;img style=&quot;background-image: none; border-bottom: 0px; border-left: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top: 0px; border-right: 0px; padding-top: 0px&quot; title=&quot;خطأ - بوابة الشروق - Google Chrome_2013-07-08_11-48-16&quot; border=&quot;0&quot; alt=&quot;خطأ - بوابة الشروق - Google Chrome_2013-07-08_11-48-16&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiwJoqquEBvbaT8XQBw2m3O6hRNrF7a1IbWDk9aWzrLJeS0ymcL79v_p1i0l5_DV38aMbWM7ypvJcD6tuGHI09najkP7JECKp8cgnZ87ZL5IvAUlBDqorFOiw1Pyl-ozO5LhPAsJfNjXg/?imgmax=800&quot; width=&quot;244&quot; height=&quot;200&quot;&gt;&lt;/a&gt;&lt;/p&gt;  </description><link>http://ebeid-soliman.blogspot.com/2013/07/blog-post.html</link><author>noreply@blogger.com (Ebeid Soliman ElSayed)</author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiwJoqquEBvbaT8XQBw2m3O6hRNrF7a1IbWDk9aWzrLJeS0ymcL79v_p1i0l5_DV38aMbWM7ypvJcD6tuGHI09najkP7JECKp8cgnZ87ZL5IvAUlBDqorFOiw1Pyl-ozO5LhPAsJfNjXg/s72-c?imgmax=800" height="72" width="72"/></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-59384554657271185.post-3420317279598115747</guid><pubDate>Wed, 03 Jul 2013 17:47:00 +0000</pubDate><atom:updated>2013-07-03T12:47:00.801-05:00</atom:updated><category domain="http://www.blogger.com/atom/ns#">NoSQL</category><category domain="http://www.blogger.com/atom/ns#">Redis</category><title>Redis 101– Part 2</title><description>&lt;p&gt;We introduced many of the &lt;a title=&quot;Redis&quot; href=&quot;http://redis.io/&quot; target=&quot;_blank&quot;&gt;Redis&lt;/a&gt;’s fundamental concepts and commands in the last post. In this post we going to introduce some advanced features.&lt;/p&gt; &lt;h4&gt;Publish-Subscribe&lt;/h4&gt; &lt;p&gt;Previously we queued data that could be read by a blocking pop command. Using that queue, we made a very basic publish-subscribe model. Any number of messages could be pushed to this queue, and a single queue reader would pop messages as they were available. This is powerful but limited. Redis provides some specialized publish-subscribe (or pub-sub) commands.&lt;/p&gt; &lt;ul&gt; &lt;li&gt;&lt;strong&gt;SUBSCRIBE&lt;/strong&gt; subscribe a client to a key, known as a channel in pub-sub terminology; client will block until messages are available.&lt;/li&gt;&lt;/ul&gt; &lt;p&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjMlSGXKPf5_H8yGrRwLoNuh_J2o-6IR2gB6gJG7x0-Furq9mcz2n_lhCK2Iupjm8_vbfQId0_PXVL8jhXkLC7q64xRs_LFHmInjBh7FFKsktHGYkp81t4by16QuWSACb97ZLY6PtwwkA/s1600-h/Redis%252520Client_2013-07-01_16-25-11%25255B3%25255D.png&quot;&gt;&lt;img style=&quot;background-image: none; border-bottom: 0px; border-left: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top: 0px; border-right: 0px; padding-top: 0px&quot; title=&quot;Redis Client_2013-07-01_16-25-11&quot; border=&quot;0&quot; alt=&quot;Redis Client_2013-07-01_16-25-11&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEip_rPKeJ1NpXyTnpHm1gG5oOWM8wcAjMEEjN0xF0XwEv1EFiFVw3XD-An1D2AN47qijPmkHNDNJa94sYWUzrJ5wdVpj6RQTU4icX03FqbQtgV3rfJ4Pswg14TQj5LEZqBFLo7kJykDcQ/?imgmax=800&quot; width=&quot;393&quot; height=&quot;87&quot;&gt;&lt;/a&gt;&lt;/p&gt; &lt;ul&gt; &lt;li&gt;&lt;strong&gt;PUBLISH&lt;/strong&gt; will push message into the channel returning how many subscribers have received it&lt;/li&gt; &lt;ul&gt; &lt;li&gt;Publisher window &lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhMZxalDWkAJxguo9mNAfkwG2iZWGon8uIs_C5pCw0uGsayHJ2l3WDXxZ-NTMoSgQ9apZ2_wl1BiCGVL-XtoexvBnYQbCqDSfQs3WqLbGQB3h7HxSuXV0nPYIq50IUgCY8oqV0dzsDWKA/s1600-h/Redis%252520Client_2013-07-01_16-27-41%25255B5%25255D.png&quot;&gt;&lt;img style=&quot;background-image: none; border-bottom: 0px; border-left: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top: 0px; border-right: 0px; padding-top: 0px&quot; title=&quot;Redis Client_2013-07-01_16-27-41&quot; border=&quot;0&quot; alt=&quot;Redis Client_2013-07-01_16-27-41&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEii84qjPghCJzV8zEh4eXDZ8rMBoeemK-lrD-UBKuWaenMcRcz2XwbZ477HmAlXX1ya0WLhJgSrPlywbc1Jr6hr7ZWM4BoYItT-8TCB_gPtAP8S4LDO8SCPqUJoGze56UyDQ-BoUPWS2A/?imgmax=800&quot; width=&quot;374&quot; height=&quot;68&quot;&gt;&lt;/a&gt;&lt;/li&gt; &lt;li&gt;Subscriber window receives : the string “message”, the channel name, the published message value &lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEimmQdXTnAoa_jvKHUsXgFiWTUacJUWoxf3nxbj8RniQonTLjxOxQ2bnJGIK1SunN_LU1USlV1j0y6CqwdldXQP42htNpeB1r1tdHHxc5AyaK40vkcraW72eCIHdtQ-VactRucgK5eJnw/s1600-h/Redis%252520Client_2013-07-01_16-28-53%25255B5%25255D.png&quot;&gt;&lt;img style=&quot;background-image: none; border-bottom: 0px; border-left: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top: 0px; border-right: 0px; padding-top: 0px&quot; title=&quot;Redis Client_2013-07-01_16-28-53&quot; border=&quot;0&quot; alt=&quot;Redis Client_2013-07-01_16-28-53&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhvWShFExdKF3ffzu9ra2uoVC-F1V7xzusCTzgBZ1qZIXBTgUpgeKrMo8FIkTLuGO_YNaMHWXWAAlQvSV000oRFUEkAkIzd9aoVcqFxIy9n8V-htO5Vm0lIPCKiH78_hW06JTAUpBolkw/?imgmax=800&quot; width=&quot;324&quot; height=&quot;136&quot;&gt;&lt;/a&gt;&lt;/li&gt;&lt;/ul&gt; &lt;li&gt;UNSUBSCRIBE unsubscribe or disconnect from the specified channel. If no channel name provided, it will disconnect from all channels.&lt;/li&gt;&lt;/ul&gt; &lt;h4&gt;Server Information&lt;/h4&gt; &lt;ul&gt; &lt;li&gt;&lt;strong&gt;INFO&lt;/strong&gt; returns a list of server data, including version, process ID, memory used, and uptime.&lt;/li&gt;&lt;/ul&gt;   &lt;p&gt;In order to change any of the Redis’s default configurations, you need to edit redis.config file at C:\Program Files\Redis\conf . It is fairly self-explanatory.&lt;/p&gt; &lt;h4&gt;Durability&lt;/h4&gt; &lt;p&gt;Redis has a few persistence options:&lt;/p&gt; &lt;ul&gt; &lt;li&gt;No persistence at all, which simply keeps all values in main memory.&lt;/li&gt; &lt;li&gt;Forced save&lt;/li&gt; &lt;ul&gt; &lt;li&gt;Use command &lt;strong&gt;SAVE&lt;/strong&gt; to force server to save database to disk.&lt;/li&gt; &lt;li&gt;Use command &lt;strong&gt;BGSAVE&lt;/strong&gt; to force server to save database to disk asynchronously in the background.&lt;/li&gt; &lt;li&gt;Use command &lt;strong&gt;LASTSAVE&lt;/strong&gt; to get a timestamp of the last time a Redis disk write succeeded (also provided through the &lt;em&gt;last_save_time&lt;/em&gt; field in the server &lt;strong&gt;INFO&lt;/strong&gt; output).&lt;/li&gt;&lt;/ul&gt;&lt;/ul&gt; &lt;h4&gt;Snapshotting&lt;/h4&gt; &lt;p&gt;By default Redis saves snapshots of the dataset on disk, in a binary file called dump.rdb. You can configure Redis to have it save the dataset every N seconds if there are at least M changes in the dataset, or you can manually force it by calling the SAVE or BGSAVE commands as we said before. For example, the following configuration will make Redis automatically dump the dataset to disk every 60 seconds if at least 1000 keys changed (This strategy is known as &lt;i&gt;snapshotting&lt;/i&gt;.): &lt;p&gt;&lt;font color=&quot;#0000ff&quot;&gt;save 60 1000&lt;/font&gt;&amp;nbsp; &lt;h4&gt;&amp;nbsp;&lt;/h4&gt; &lt;h4&gt;Append-only file&lt;/h4&gt; &lt;p&gt;Snapshotting is not very durable. If your computer running Redis stops, the latest data written on Redis will get lost. While this may not be a big deal for some applications, there are use cases for full durability, and in these cases Redis was not a viable option. &lt;p&gt;The &lt;i&gt;append-only file&lt;/i&gt; is an alternative, fully-durable strategy for Redis. It became available in version 1.1. You can turn on the AOF in your configuration file: &lt;p&gt;&lt;font color=&quot;#0000ff&quot;&gt;appendonly yes&lt;/font&gt; &lt;p&gt;Then we must decide how often a command is appended to the file. Setting &lt;em&gt;always&lt;/em&gt; is the more durable, since every command is saved. By default &lt;em&gt;everysec&lt;/em&gt; is enabled, which saves up and writes commands only once a second. This is a decent trade-off, since it’s fast enough, and worst case you’ll lose only the last one second of data. Finally, &lt;em&gt;no&lt;/em&gt; is an option, which just lets the OS handle flushing. It can be fairly infrequent, and not recommended. &lt;p&gt;&lt;font color=&quot;#0000ff&quot;&gt;appendfsync always&lt;/font&gt; &lt;p&gt;&lt;font color=&quot;#0000ff&quot;&gt;# appendfsync everysec&lt;/font&gt; &lt;p&gt;&lt;font color=&quot;#0000ff&quot;&gt;# appendfsync no&lt;/font&gt; &lt;p&gt;From now on, every time Redis receives a command that changes the dataset (e.g. SET) it will append it to the AOF. When you restart Redis it will re-play the AOF to rebuild the state. Append-only has more detailed parameters, you could refer to the online documentation for more details. &lt;h4&gt;&amp;nbsp;&lt;/h4&gt; &lt;h4&gt;Security&lt;/h4&gt; &lt;p&gt;Redis provides command-level security through obscurity, by allowing you to hide or suppress commands. This will rename the FLUSHALL command (remove all keys from the system) into some hard-to-guess value like c283d93ac9528f986023793b411e4ba2:&lt;/p&gt; &lt;p&gt;rename-command FLUSHALL c283d93ac9528f986023793b411e4ba2&lt;/p&gt; &lt;p&gt;If we attempt to execute FLUSHALL against this server, we’ll be hit with an error. We can also disable the command entirely by setting it to a blank string.&lt;/p&gt; &lt;p&gt;rename-command FLUSHALL &quot;&quot;&lt;/p&gt; &lt;p&gt;You can set any number of commands to a blank string to allow only a customized subset of the Redis’s commands.&lt;/p&gt; &lt;h4&gt;Benchmarking&lt;/h4&gt; &lt;p&gt;Redis provides an excellent benchmarking tool. It connects locally to port 6379 by default and issues 10,000 requests using 50 parallel clients. Tool test many commands and have a long output report. Tool is in C:\Program Files\Redis\&lt;/p&gt; &lt;p&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEj2lY-BkxedOV8tfSews2zK9gkRWMgr72erS3fKUJyP0Unsi9sdmR1LMMY7ez5kTaysxjM51JTCAej6l7wGHP3cHBCDUlxdh4hEMZ6WSBtkL6MbJfXaI71atpwJbsQkTIbQBM3A5xxIgg/s1600-h/CWindowssystem32cmd.exe_2013-07-02_09-15-52%25255B3%25255D.png&quot;&gt;&lt;img style=&quot;background-image: none; border-bottom: 0px; border-left: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top: 0px; border-right: 0px; padding-top: 0px&quot; title=&quot;CWindowssystem32cmd.exe_2013-07-02_09-15-52&quot; border=&quot;0&quot; alt=&quot;CWindowssystem32cmd.exe_2013-07-02_09-15-52&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjFkKkyntKxJwAmF7ZxyZHVe7B5WGrS7o6_puBxOD1-FftJzdJBQG-YPUdkLCYSzFvtQLaBEplFRBk1B0ZUZWd4YOINvPKtTvBzZCimPSurBJzvznTUcUWNBAy1BWJilb3KQY7YKJ9-6A/?imgmax=800&quot; width=&quot;342&quot; height=&quot;366&quot;&gt;&lt;/a&gt;&lt;/p&gt; &lt;h4&gt;Replication&lt;/h4&gt; &lt;p&gt;Redis supports master-slave replication. One server is the master by default if you don’t set it as a slave of anything. Data will be replicated to any number of slave servers. Configuring master-slave setting is the same as running another instance with the slaveof option in the salve’s conf file set to the master IP and port. Refer to our previous &lt;a title=&quot;Running multiple Redis instances on the same server&quot; href=&quot;http://ebeid-soliman.blogspot.com/2013/07/running-multiple-redis-instances-on.html&quot; target=&quot;_blank&quot;&gt;post&lt;/a&gt; for more details.&lt;/p&gt; &lt;p&gt;This concludes out Redis 101 tutorial, we tried to touch all basic and moderate features in it. Later we going to show how to write C# programs against Redis. &lt;/p&gt;  </description><link>http://ebeid-soliman.blogspot.com/2013/07/redis-101-part-2.html</link><author>noreply@blogger.com (Ebeid Soliman ElSayed)</author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEip_rPKeJ1NpXyTnpHm1gG5oOWM8wcAjMEEjN0xF0XwEv1EFiFVw3XD-An1D2AN47qijPmkHNDNJa94sYWUzrJ5wdVpj6RQTU4icX03FqbQtgV3rfJ4Pswg14TQj5LEZqBFLo7kJykDcQ/s72-c?imgmax=800" height="72" width="72"/></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-59384554657271185.post-4558320522262868780</guid><pubDate>Tue, 02 Jul 2013 16:42:00 +0000</pubDate><atom:updated>2013-07-02T11:42:51.399-05:00</atom:updated><category domain="http://www.blogger.com/atom/ns#">NoSQL</category><category domain="http://www.blogger.com/atom/ns#">Redis</category><title>Running multiple Redis instances on the same server</title><description>&lt;p&gt;Redis runs as a background process that listens to a specific port (6379 by default) for incoming requests from clients. Running multiple instances requires a separate conf file and a new init script. The conf file specifies details for the new instance, and the init script handles starting/stopping of the instance background process.&lt;/p&gt; &lt;ol&gt; &lt;li&gt;Make a copy of the &lt;a title=&quot;Redis&quot; href=&quot;http://redis.io/&quot; target=&quot;_blank&quot;&gt;redis&lt;/a&gt;.conf file at C:\Program Files\Redis\Conf and give it a new name redis-s1.conf. Leave both files in the same directory C:\Program Files\Redis\Conf&lt;/li&gt; &lt;li&gt;Open the redis-s1.conf with your favorite text editor (e.g. notepad ) and change the following:&lt;/li&gt; &lt;ol&gt; &lt;li&gt;PID File&lt;/li&gt; &lt;ul&gt; &lt;li&gt;pidfile /var/run/redis-s1.pid&lt;/li&gt;&lt;/ul&gt; &lt;li&gt;Port&lt;/li&gt; &lt;ul&gt; &lt;li&gt;port 6380&lt;/li&gt;&lt;/ul&gt; &lt;li&gt;Log File&lt;/li&gt; &lt;ul&gt; &lt;li&gt;logfile &quot;C:/Program Files/Redis/logs/redis-s1.log&lt;/li&gt;&lt;/ul&gt; &lt;li&gt;Data Directory (don’t forget to create that directory)&lt;/li&gt; &lt;ul&gt; &lt;li&gt;dir &quot;C:/Program Files/Redis/data2&quot;&lt;/li&gt;&lt;/ul&gt; &lt;li&gt;For replication only : If you planning to use this instance as a slave in master-slave replication setting (where 127.0.0.1 is the master instance IP, 6379 in the master instance port)&lt;/li&gt; &lt;ul&gt; &lt;li&gt;slaveof 127.0.0.1 6379&lt;/li&gt;&lt;/ul&gt;&lt;/ol&gt; &lt;li&gt;To start the new instance&lt;/li&gt; &lt;ol&gt; &lt;li&gt;Open a new command window&lt;/li&gt; &lt;li&gt;Navigate to C:\Program Files\Redis&lt;/li&gt; &lt;li&gt;Run redis-server conf\redis-s1.conf&lt;/li&gt;&lt;/ol&gt; &lt;li&gt;To connect to the new instance&lt;/li&gt; &lt;ol&gt; &lt;li&gt;Open a new command window&lt;/li&gt; &lt;li&gt;Navigate to C:\Program Files\Redis&lt;/li&gt; &lt;li&gt;Run redis-cli –h 127.0.0.1 –p 6380&lt;/li&gt;&lt;/ol&gt;&lt;/ol&gt; &lt;p&gt;Now you can have multiple Redis instances on the same server like any other DBMS.&lt;/p&gt;  </description><link>http://ebeid-soliman.blogspot.com/2013/07/running-multiple-redis-instances-on.html</link><author>noreply@blogger.com (Ebeid Soliman ElSayed)</author></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-59384554657271185.post-3698580356570439947</guid><pubDate>Wed, 26 Jun 2013 20:29:00 +0000</pubDate><atom:updated>2013-07-01T09:53:30.911-05:00</atom:updated><category domain="http://www.blogger.com/atom/ns#">NoSQL</category><category domain="http://www.blogger.com/atom/ns#">Redis</category><title>Redis 101</title><description>&lt;p&gt;&lt;a title=&quot;Redis&quot; href=&quot;http://redis.io/&quot; target=&quot;_blank&quot;&gt;Redis&lt;/a&gt; (REmote DIctionary Service) is an open-source networked in-memory key-value data store. First released in 2009, currently sponsored by &lt;a href=&quot;http://www.vmware.com/&quot; target=&quot;_blank&quot;&gt;VMware&lt;/a&gt;, and since then it have been ranked &lt;a title=&quot;DB-Engines Ranking of Key-value Stores&quot; href=&quot;http://db-engines.com/en/ranking/key-value+store&quot; target=&quot;_blank&quot;&gt;the most popular key-value store by DB-Engine&lt;/a&gt;. Redis creator &lt;a title=&quot;Salvatore Sanfilippo aka antirez&quot; href=&quot;http://invece.org/&quot; target=&quot;_blank&quot;&gt;Salvatore Sanfilippo&lt;/a&gt; refers to his project as a “data structure server” to capture its unique handling of complex data types and other features. Interested ? Enough talking, let’s get down to business. &lt;/p&gt; &lt;p&gt;&lt;strong&gt;Download&lt;/strong&gt; Redis installer from &lt;a href=&quot;https://github.com/rgl/redis/downloads&quot; target=&quot;_blank&quot;&gt;here&lt;/a&gt;.&lt;/p&gt; &lt;p&gt;&lt;strong&gt;Installation&lt;/strong&gt; is straight forward:&lt;/p&gt; &lt;p&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEh_Fprqb6SmBqLWdt0b3jH9GAvKaaYJoikaSKOhAJBYzGZ8WxL3GGaIaPRpanuVOd0hmUGiaQVLCQlK0BK8RqnHT2Rafs4N3NE-JIwDDyzH5yVUif2Ao9TXAhgTVaEpZa0YmVOxpbb3kQ/s1600-h/Setup%252520-%252520Redis_2013-06-27_11-42-13%25255B4%25255D.png&quot;&gt;&lt;img style=&quot;background-image: none; border-bottom: 0px; border-left: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top: 0px; border-right: 0px; padding-top: 0px&quot; title=&quot;Setup - Redis_2013-06-27_11-42-13&quot; border=&quot;0&quot; alt=&quot;Setup - Redis_2013-06-27_11-42-13&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjoEXLL_igfXyQnZo3wstBJ7pWfE3S2lFRkWo4JgubuL1hiB5OaqOVz4N46SbPJQ6evoySooryIKnoaYbpWvYWf1wcSdb60vmiEU4gpYo39Z8SaSA4w_TyWzsEV8aK-fsaqBLqCiBFJJA/?imgmax=800&quot; width=&quot;401&quot; height=&quot;322&quot;&gt;&lt;/a&gt;&lt;/p&gt; &lt;p&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhQ9bK6OJC3nOeAkzzfNJZEhUIBIjfuhCbxRRxemqr19iCyC3s6F8uOZAk-m8QysPCnjanyAGpZqlcdLiY8LiPVj0-6RYsFHeOoo769GnM845uhyphenhyphenmGY281JnsRnfH0KXNznhAcEMzyAXw/s1600-h/Setup%252520-%252520Redis_2013-06-27_11-42-21%25255B3%25255D.png&quot;&gt;&lt;img style=&quot;background-image: none; border-bottom: 0px; border-left: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top: 0px; border-right: 0px; padding-top: 0px&quot; title=&quot;Setup - Redis_2013-06-27_11-42-21&quot; border=&quot;0&quot; alt=&quot;Setup - Redis_2013-06-27_11-42-21&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiWSj_fGxvvv2S95VH83Or1fVi_CpJeD7VZ9hFX5eINoa-KY6KRT02pnj_qtenQhmKucx6JwAziB-BmJaY1rcLmikO-iS3k6PS-dwEsLDePh0UpbNRHv2Wuo1gC5rIGsOyGCvbYtLmrRg/?imgmax=800&quot; width=&quot;406&quot; height=&quot;321&quot;&gt;&lt;/a&gt;&lt;/p&gt; &lt;p&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgVCihTR61nbRyMkLhSViBLLbVoj3y5ZmXjFI6R6caYNcuNnqKdRXVLYWDiH03zBJExcbaot3KFPvAAFlem76NGM2a8znpINTvJZZl4DEaVOPQbuA4DsLcs1pRG-m2juwDj4RXG0ABusQ/s1600-h/Setup%252520-%252520Redis_2013-06-27_11-42-25%25255B3%25255D.png&quot;&gt;&lt;img style=&quot;background-image: none; border-bottom: 0px; border-left: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top: 0px; border-right: 0px; padding-top: 0px&quot; title=&quot;Setup - Redis_2013-06-27_11-42-25&quot; border=&quot;0&quot; alt=&quot;Setup - Redis_2013-06-27_11-42-25&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhO3w25pbPFBl083gH9GgWXDyS9N_BXHw_9fCWgOLRw26NqnUCQvAceEKjJGkMUy096sZ92BDzRnFni2_kxo56NNjm_9ShUIL9DAZcXtTSH9EXme6xv5hppczQGeLofTbF5usTWx4FLhg/?imgmax=800&quot; width=&quot;412&quot; height=&quot;325&quot;&gt;&lt;/a&gt;&lt;/p&gt; &lt;p&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgeVbsDendgOfQkIjc3-rfsNLMcWoMjltyap0IY8i8EsNrYrWSX4MbDlt2U7lI2MylrQT6u1pepNb3zMBI7z_767Rd2aMoP-jr582zVsUF4Hwvv50202U5QMDsNu6M97zJNwT1-fyRz8g/s1600-h/Setup%252520-%252520Redis_2013-06-27_11-42-29%25255B3%25255D.png&quot;&gt;&lt;img style=&quot;background-image: none; border-bottom: 0px; border-left: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top: 0px; border-right: 0px; padding-top: 0px&quot; title=&quot;Setup - Redis_2013-06-27_11-42-29&quot; border=&quot;0&quot; alt=&quot;Setup - Redis_2013-06-27_11-42-29&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhUUZCVu0kZmXDcYkzyjJQ5LX_4-Qa9Dc0yXmn7Pfia1PYdfhGm8eWAV4Spcx_KMpQtpN3SJPjlg8R0tmi1k5t-7_uAvOXS0SvppyFaFEQ_3uV_Y0Gqcy5US-wIkyCZRzIcwvriPPOf5Q/?imgmax=800&quot; width=&quot;420&quot; height=&quot;332&quot;&gt;&lt;/a&gt;&lt;/p&gt; &lt;p&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEipK9TTeCffkzC1OMMDZ_rq4N28UHIkOCjrh_OfU-wp2oeCZ1AjB7Ezj_p5cFToO2u4F7wteSbav-XiMLuXsW2J5_Z7x0K98g8kEXcRhQjaom_F7eaJIE06-COK8Ly3ncwbE3QFIJ2W4w/s1600-h/Setup%252520-%252520Redis_2013-06-27_11-42-32%25255B3%25255D.png&quot;&gt;&lt;img style=&quot;background-image: none; border-bottom: 0px; border-left: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top: 0px; border-right: 0px; padding-top: 0px&quot; title=&quot;Setup - Redis_2013-06-27_11-42-32&quot; border=&quot;0&quot; alt=&quot;Setup - Redis_2013-06-27_11-42-32&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEg4UynYlqcz84mG7_2qd1LiIwUDJlvUJ3_16ntvaPnwe04dTQYuic8w6DLxNNXJnlJgKtXDH-Us6uT9CaJcrJayzbGc-eKefp5vfeh03G-3Nl48YM2bX-V1fApdjAmRNOP_OuF1AlJilA/?imgmax=800&quot; width=&quot;430&quot; height=&quot;339&quot;&gt;&lt;/a&gt;&lt;/p&gt; &lt;p&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEifrrX265e2fxWyPpgCxVM5gUpHY69jhVscuP3ODw4xYpzw8sOsd-PLHkLoVXyF_Gp1sYhMq41qtZr510bjYXGpl0-4fGDFy2di9Y2hSv8HPk0yJR7M6Wko2uETZ_rYFUESifUHlo3SSQ/s1600-h/Setup%252520-%252520Redis_2013-06-27_11-42-36%25255B3%25255D.png&quot;&gt;&lt;img style=&quot;background-image: none; border-bottom: 0px; border-left: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top: 0px; border-right: 0px; padding-top: 0px&quot; title=&quot;Setup - Redis_2013-06-27_11-42-36&quot; border=&quot;0&quot; alt=&quot;Setup - Redis_2013-06-27_11-42-36&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhRbOv_vPSjOznE6FRiR4d4Ap-y51y1DWYNnh1fEWeLVDtD8ZEj2FSYOabZ6DdEEbOVMPyPvmToi-FVZUBtgVjvkUy5Atp0NYToejS1N29073qgDzTeHaEy_ajOD4dkm96fgInVRahy0Q/?imgmax=800&quot; width=&quot;437&quot; height=&quot;345&quot;&gt;&lt;/a&gt;&lt;/p&gt; &lt;p&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiM9OSCEQQxBWVYGW3PXeiT_URXI-zS5tsF-ZjnGrsP2lRVWzdbBCIprJsUXZC-Qw7G_6drkMP73CjmTqrTe_18uCla9_YpPe7A7hykPpt1btcPyo_OxLqMEcXh6plLVAte1aU7RisXYw/s1600-h/Setup%252520-%252520Redis_2013-06-27_11-45-05%25255B3%25255D.png&quot;&gt;&lt;img style=&quot;background-image: none; border-bottom: 0px; border-left: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top: 0px; border-right: 0px; padding-top: 0px&quot; title=&quot;Setup - Redis_2013-06-27_11-45-05&quot; border=&quot;0&quot; alt=&quot;Setup - Redis_2013-06-27_11-45-05&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgM56dX0Dqpyp17J11frtgSESFukDA6w0z0ASzIrJ_UnEML_dTfTJ8wTZBWund66ZkEQ5o_-QLQb-ecvqlHaDIcPAsFypKxcz1vrIQxJa3aQmFtRf2BYaOkP0YMviI7YOtK3DqYcy7ZyA/?imgmax=800&quot; width=&quot;446&quot; height=&quot;352&quot;&gt;&lt;/a&gt;&lt;/p&gt; &lt;p&gt;&lt;strong&gt;Start the Server&lt;/strong&gt; go to Control Panel &amp;gt;&amp;gt; Administrative Tools &amp;gt;&amp;gt; Services , right click &lt;em&gt;Redis Server&lt;/em&gt; and select Start.&lt;/p&gt; &lt;p&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjawyLeLulDQL4MkI2pMfkqHwWolh_APjCAN682ZlncwAZ2uqPdxx1sWnR8xiqrYbmKTDb8ULJ4rzAXcLi9LuvWOQArSW4doh7C_WDMB7xvdnV0vIvSDp40LtrczHTB4Z5j1f0IVm_d_Q/s1600-h/Services_2013-06-27_11-49-50%25255B3%25255D.png&quot;&gt;&lt;img style=&quot;background-image: none; border-bottom: 0px; border-left: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top: 0px; border-right: 0px; padding-top: 0px&quot; title=&quot;Services_2013-06-27_11-49-50&quot; border=&quot;0&quot; alt=&quot;Services_2013-06-27_11-49-50&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgSCJb84ueJglYofAG2pcZDBP4wxU67p8lYL21gVEdQ2JDX9Du92CC6th1TOwRVO6Pcct7fh68qK5S3WduPOG9MVPlklv6aQZ6kMtqoYuP36h6BWCnHPHjd6vSxf4KmgvBi-KKdnY_hqg/?imgmax=800&quot; width=&quot;544&quot; height=&quot;150&quot;&gt;&lt;/a&gt;&lt;/p&gt; &lt;p&gt;&lt;strong&gt;Start the Client&lt;/strong&gt; look for Redis Client (with red cube icon) in your start menu and open it. As you see it listens to port 6379 by default. You could ping your server by writing PING, if everything is good you will get PONG in return.&lt;/p&gt; &lt;p&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEh4Y09UQXzxuDmMHuwQObvMjtAFHT2MPxDXowj3DsuZw7ssTCgo9CI8i5N-vmEgvzqXKB4_8J-e5dM-w4wlysXJl2LsfoCwz5ADHTUuMEypXkfPhh6nJEJrE7DuvsWWZeJw5vKCEUOcJw/s1600-h/Redis%252520Client_2013-06-27_11-56-46%25255B4%25255D.png&quot;&gt;&lt;img style=&quot;background-image: none; border-bottom: 0px; border-left: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top: 0px; border-right: 0px; padding-top: 0px&quot; title=&quot;Redis Client_2013-06-27_11-56-46&quot; border=&quot;0&quot; alt=&quot;Redis Client_2013-06-27_11-56-46&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjjYtA55TfaTCv07vE3LjyvsLXXNP9jdpACM-85BGpVe-SC0tRrNpTJTk9ow9fv6YHJepHIX0gu0dMN4-m6yTTUo7dHojDYpD-HwJVAyJg0BnnZMXik9d5szxLAKKHFPr3ec4mCJScfbQ/?imgmax=800&quot; width=&quot;494&quot; height=&quot;114&quot;&gt;&lt;/a&gt;&lt;/p&gt;         &lt;h3&gt;GET &lt;font style=&quot;font-weight: normal&quot;&gt;&amp;amp; &lt;font style=&quot;font-weight: bold&quot;&gt;SET&lt;/font&gt;&lt;/font&gt;&lt;/h3&gt; &lt;p&gt;As we said before, Redis is a key-value store. We store value inside a key and retrieve it later using that key. We can use the command SET to store the value &quot;fido&quot; at key &quot;server:name&quot; (server replies with Ok if everything is good) (Note that we used colons [:] within our key. This is a valid character that often logically separates a key into segments. It’s merely a matter of convention, with no deeper meaning in Redis.)&lt;/p&gt;&lt;pre&gt;&lt;code&gt; &lt;font color=&quot;#0000ff&quot;&gt;SET server:name &quot;fido&quot;&lt;/font&gt;&lt;/code&gt;&lt;/pre&gt;&lt;pre&gt;&lt;code&gt;&lt;font face=&quot;Arial&quot;&gt;To retrieve our value, we use GET command (server replies with “fido”)&lt;/font&gt;&lt;/code&gt;&lt;/pre&gt;&lt;pre&gt;&lt;code&gt; &lt;font color=&quot;#0000ff&quot;&gt;GET server:name&lt;/font&gt; &lt;/code&gt;&lt;/pre&gt;&lt;pre&gt;&lt;font face=&quot;Arial&quot;&gt;You could also delete a given key and its associated value using DEL command and you can check for key existence using EXISTS (1 exists, 0 otherwise). &lt;/font&gt;&lt;code&gt;&lt;font face=&quot;Arial&quot;&gt;We get and set multiple values in one command using MSET &amp;amp; MGET&lt;/font&gt;&lt;/code&gt;&lt;/pre&gt;&lt;pre&gt;&lt;code&gt;&lt;font color=&quot;#0000ff&quot;&gt; MSET 1 valueA 2 valueB&lt;/font&gt;&lt;/code&gt;&lt;/pre&gt;&lt;pre&gt;&lt;code&gt;&lt;font color=&quot;#0000ff&quot;&gt; MGET 1 2&lt;/font&gt;&lt;/code&gt;&lt;/pre&gt;&lt;br /&gt;&lt;p&gt;Although Redis stores strings, it recognizes integers and provides some simple operations for them. If we want to keep a running total of something, we can create a count and then increment it with the INCR command (gives error for noninteger values).&lt;/p&gt;&lt;pre&gt;&lt;code&gt;&lt;font face=&quot;Arial&quot;&gt; &lt;/font&gt;&lt;font color=&quot;#0000ff&quot; face=&quot;Courier New&quot;&gt;SET count 2&lt;/font&gt;&lt;/code&gt;&lt;/pre&gt;&lt;pre&gt;&lt;code&gt;&lt;font color=&quot;#0000ff&quot;&gt; INCR count&lt;/font&gt;&lt;/code&gt;&lt;/pre&gt;&lt;pre&gt;&lt;code&gt;&lt;font color=&quot;#0000ff&quot;&gt; GET count&lt;/font&gt;&lt;/code&gt;&lt;/pre&gt;&lt;pre&gt;&lt;code&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhbnzmOSf7ugpqxmL3MMYUYEsyXWB1tTl29Gn5oeQ83p1rB7z4W6DM9Cp3uC6JprElOyihqRJmiYdwW9a9w_0bTZ_V9edZRggSolYYYAZflRubMwyT1BnX6KR_3MYNgxq8GkMLzyv1j9Q/s1600-h/Redis%252520Client_2013-06-27_13-01-40%25255B4%25255D.png&quot;&gt;&lt;img style=&quot;background-image: none; border-bottom: 0px; border-left: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top: 0px; border-right: 0px; padding-top: 0px&quot; title=&quot;Redis Client_2013-06-27_13-01-40&quot; border=&quot;0&quot; alt=&quot;Redis Client_2013-06-27_13-01-40&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgxmGAbcs-MJWv_ylJ18V-ZqOLD8DOtKg51gSXg84cvLUtdhVEUtFh3716USFQRdnJ40ZeXOOTpZsDqzVYyYo6uWJj1_8dx-eVmqQ16JvYA_1WlmHCC-GG4FfX3BtrN6MNOuZFfGDQ67A/?imgmax=800&quot; width=&quot;351&quot; height=&quot;134&quot;&gt;&lt;/a&gt;&lt;/code&gt;&lt;/pre&gt;&lt;br /&gt;&lt;p&gt;You can also increment by any integer (INCRBY) or decrement (DECR, DECRBY).&lt;/p&gt;&lt;br /&gt;&lt;p&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEj0oXZ10bHufgNWbupSXlMjpJROggV5nJhycKuIMcA60bPS6uvNe-6oheY2UpF5pTSCM6GadEqI6sf53d0MYMKyM-B5TS_O17cquCNhPvHEdaR9qAzod8G_sm9vdU2POhXp7N9H1-elyA/s1600-h/Redis%252520Client_2013-06-27_13-04-08%25255B3%25255D.png&quot;&gt;&lt;img style=&quot;background-image: none; border-bottom: 0px; border-left: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top: 0px; border-right: 0px; padding-top: 0px&quot; title=&quot;Redis Client_2013-06-27_13-04-08&quot; border=&quot;0&quot; alt=&quot;Redis Client_2013-06-27_13-04-08&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgERA8E2TG65GSvEJtOhcGSb5fQmlLRHWXASSGgVytlyaWa7KvQAMdTzwSJ8AqZfEKcX_ZaoP5GHO6VdsVvcG__1woB8LropaNfwZ7Fp64NOof1xSXpH8FZQscHM4YgxpzY7fRhJ7jlgw/?imgmax=800&quot; width=&quot;355&quot; height=&quot;146&quot;&gt;&lt;/a&gt;&lt;/p&gt;&lt;br /&gt;&lt;p&gt;It is good to know that these simple operations are atomic in Radis.&lt;/p&gt;&lt;br /&gt;&lt;h3&gt;Expire&lt;/h3&gt;&lt;br /&gt;&lt;p&gt;You can tell Radis to hold a key only for a certain period of time (in seconds) using EXPIRE command. You can test how long a key will exist for with the TTL command. It returns the number of seconds until it will be deleted (-1 means the key will never expire). All keys are permanent by default.&lt;/p&gt;&lt;br /&gt;&lt;p&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhm2hCbBtab_ozHQN1uRGQoJkyH6IBHHsB8bXCa2OgseYrWY-HesjpYtV0kRjjaj1cFtTe9EcTethDTLDWWXryi4_-sPSYMzpd6EPOoj1-sg2xSHO1X58cnpNIFjAoEISvZqhyphenhyphenYhEa5PA/s1600-h/Redis%252520Client_2013-06-27_13-40-01%25255B3%25255D.png&quot;&gt;&lt;img style=&quot;background-image: none; border-bottom: 0px; border-left: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top: 0px; border-right: 0px; padding-top: 0px&quot; title=&quot;Redis Client_2013-06-27_13-40-01&quot; border=&quot;0&quot; alt=&quot;Redis Client_2013-06-27_13-40-01&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEg1LRqZvcDmrE3aRoS0eAPn9zfxtVgvaB7lKkEQP702cSB8bjITCitFQdOpTXbLEcmpVXlwmw-oj4usP5yFBNpiihpcaVRoxssYUOYMNeMNvqv8CwliVull_2srsoXkIIZOjouvCy6eOQ/?imgmax=800&quot; width=&quot;356&quot; height=&quot;114&quot;&gt;&lt;/a&gt;&amp;nbsp;&lt;/p&gt;&lt;br /&gt;&lt;p&gt;Setting and expiring keys is so common that Redis provides a shortcut command called SETEX. Also at any moment before the key expires, you can remove the timeout by running PERSIST KeyName.&lt;/p&gt;&lt;br /&gt;&lt;p&gt;A common trick for keeping only recently used keys is to update the expire time whenever you retrieve a value. This will ensure that your most recently used keys will remain in Redis, while &lt;a href=&quot;http://en.wikipedia.org/wiki/Cache_algorithms#Least_Recently_Used&quot; target=&quot;_blank&quot;&gt;the least recently used&lt;/a&gt; keys will just expire as normal.&lt;/p&gt;&lt;br /&gt;&lt;h3&gt;Transactions&lt;/h3&gt;&lt;br /&gt;&lt;p&gt;Redis like most DBMSs supports transactions. We begin the transaction with the MULTI command and execute it with EXEC command. So, wrapping two operations like SET and INCR in a single block will complete either successfully or not at all.&lt;/p&gt;&lt;br /&gt;&lt;p&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgbKuz-whMIjUeGmws7qtixnTkJmSJhzLQawzQeIXbtJJg_gKrvNGJawak9IKK_OSEcAoU3-2efstSNfe7JAgVSeCfC_8RuOx8VcVjT01BC5SRHb2aHLyuT1WZF4lcObIcl0mVmDfdIaA/s1600-h/Redis%252520Client_2013-06-27_13-17-56%25255B3%25255D.png&quot;&gt;&lt;img style=&quot;background-image: none; border-bottom: 0px; border-left: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top: 0px; border-right: 0px; padding-top: 0px&quot; title=&quot;Redis Client_2013-06-27_13-17-56&quot; border=&quot;0&quot; alt=&quot;Redis Client_2013-06-27_13-17-56&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhh55u2lDfJIT3VHmPIVfuQlL8NcOwtAO2FDTogwuXB6xUPA4fhV8mOn0j78ZcqLdl-8anEP6FBHo1VRZSp82hSI5DdtfLDqOP0qjwKtqlP1x2gOPtZIchgy51ogdXebMRpSXiBpXEyeQ/?imgmax=800&quot; width=&quot;363&quot; height=&quot;197&quot;&gt;&lt;/a&gt;&lt;/p&gt;&lt;br /&gt;&lt;p&gt;As you may guess from the server response inside the transaction, commands are not executed instantly. Instead, they are queued and then executed in sequence.&lt;/p&gt;&lt;br /&gt;&lt;p&gt;Similar to ROLLBACK in SQL, you can stop a transaction with the DISCARD command, which will clear the transaction queue. Unlike ROLLBACK, it won’t revert the database; it will simply not run the transaction at all. The effect is identical, although the underlying concept is a different mechanism (transaction rollback vs. operation cancellation).&lt;/p&gt;&lt;br /&gt;&lt;h3&gt;Complex Data Types&lt;/h3&gt;&lt;br /&gt;&lt;p&gt;Radis can store lists, hashes, sets, and sorted sets natively. These collection data types can contain a huge number of values (up to 2^32 elements or more than 4 billion) per key. That’s more than enough for all &lt;a href=&quot;http://facebook.com&quot; target=&quot;_blank&quot;&gt;Facebook&lt;/a&gt; accounts to live as a list under a single key.&lt;/p&gt;&lt;br /&gt;&lt;h4&gt;List&lt;/h4&gt;&lt;br /&gt;&lt;p&gt;A list is a series of ordered values that can act both as queues (first value in, first value out) and as stacks (last value in, first value out). Some of the important commands for interacting with lists are RPUSH, LPUSH, LLEN, LRANGE, LPOP, and RPOP. You can immediately begin working with a key as a list, as long as it doesn&#39;t already exist as a different type.&lt;/p&gt;&lt;br /&gt;&lt;ul&gt;&lt;br /&gt;&lt;li&gt;&lt;strong&gt;RPUSH&lt;/strong&gt; puts the new value at the end (right) of the list.&lt;/li&gt;&lt;br /&gt;&lt;li&gt;&lt;strong&gt;LPUSH&lt;/strong&gt; puts the new value at the start (left) of the list.&lt;/li&gt;&lt;/ul&gt;&lt;br /&gt;&lt;p&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjFNkxSfYmDXZ8AEoETR6wbCxlS4EH2d6l80PtFHkB7HhxlfhoakbhdH_A5uThA0OOeUSXh4vsdDrrgeD-iPMhaw_TZoWm6wwN36xg6hlA5gxNanDNPCN0KCx7X79CdNm-rjivlD4LHYQ/s1600-h/Redis%252520101%252520-%252520Windows%252520Live%252520Writer_2013-06-27_14-42-33%25255B3%25255D.png&quot;&gt;&lt;img style=&quot;background-image: none; border-bottom: 0px; border-left: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top: 0px; border-right: 0px; padding-top: 0px&quot; title=&quot;Redis 101 - Windows Live Writer_2013-06-27_14-42-33&quot; border=&quot;0&quot; alt=&quot;Redis 101 - Windows Live Writer_2013-06-27_14-42-33&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhDxpRddWeQs86q5YNCidxaxdr6BTdHUgqzXXRiC7sFUghg_KCEnGzq9IvSC-bbVrwR0JDmJ7PXVI7u-nRJknzQ0C_GNa7yQ33cG8VeLiNn1vAf5eH_5vReGrpybTtfYKGaYOV98inyow/?imgmax=800&quot; width=&quot;441&quot; height=&quot;168&quot;&gt;&lt;/a&gt;&lt;/p&gt;&lt;br /&gt;&lt;ul&gt;&lt;br /&gt;&lt;li&gt;&lt;strong&gt;LRANGE&lt;/strong&gt; gives a subset of the list. It takes the index of the first element you want to retrieve as its first parameter and the index of the last element you want to retrieve as its second parameter. A value of -1 for the second parameter means to retrieve all elements in the list.&lt;/li&gt;&lt;/ul&gt;&lt;br /&gt;&lt;p&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEg103xF-3LKGnQ9QI9rYPvGIfylcy33MEKE7aXz8GgUe2SVh55tzVPdfMcLTT0n5npJjlTuocDbC14gxe2r3FV_wp5sptSiN6QY14PCZXT_KDgel0JuKKSbGxc8K_OToneeDqBJpyA67g/s1600-h/Redis%252520Client_2013-06-27_14-46-47%25255B3%25255D.png&quot;&gt;&lt;img style=&quot;background-image: none; border-bottom: 0px; border-left: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top: 0px; border-right: 0px; padding-top: 0px&quot; title=&quot;Redis Client_2013-06-27_14-46-47&quot; border=&quot;0&quot; alt=&quot;Redis Client_2013-06-27_14-46-47&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEg-qZI8nASUcm5tP1jaMXn3OgBRkk3zsuiECAzZxHxOxkfOjbUDgNu5_uCCfLqgADJrpkCV7G3u3GGilpJumyRjrGjM-e6kbe_yK6xDT2T7tcAQQHK13ZkeRea_miNt4Gpy5I8ey841bg/?imgmax=800&quot; width=&quot;444&quot; height=&quot;178&quot;&gt;&lt;/a&gt;&lt;/p&gt;&lt;br /&gt;&lt;ul&gt;&lt;br /&gt;&lt;li&gt;&lt;strong&gt;LLEN&lt;/strong&gt; returns the current length of the list.&lt;/li&gt;&lt;br /&gt;&lt;li&gt;&lt;strong&gt;LPOP&lt;/strong&gt; removes the first (left) element from the list and returns it.&lt;/li&gt;&lt;br /&gt;&lt;li&gt;&lt;strong&gt;RPOP&lt;/strong&gt; removes the last (right) element from the list and returns it.&lt;/li&gt;&lt;br /&gt;&lt;ul&gt;&lt;br /&gt;&lt;li&gt;Use LPUSH/RPOP to make List act like a queue.&lt;/li&gt;&lt;br /&gt;&lt;li&gt;Use LPUSH/LPOP to make List act like a stack.&lt;/li&gt;&lt;/ul&gt;&lt;br /&gt;&lt;li&gt;&lt;strong&gt;LREM&lt;/strong&gt; removes (some or all) matching elements from the list. It also requires a number to know how many matches to remove. Setting the count to 0 as we do here just removes them all. Setting the count greater than 0 will remove only that number of matches, and setting the count to a negative number will remove that number of&lt;br&gt;matches but scan the list from the end (right side).&lt;/li&gt;&lt;/ul&gt;&lt;br /&gt;&lt;p&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjAgK5zmlmPkm007ILLq7QTTa1s3QzIwmwYEyv1tNTl_lzRenUMeLk9sweqlMGsQwdNTYMRWeV5TvGEuMson9NTjlX7LSwTvr2Ry5K0bZmE7ArJTKouPHjXj9QXJD37y4xslhUS-DERCw/s1600-h/Redis%252520Client_2013-06-27_14-53-25%25255B3%25255D.png&quot;&gt;&lt;img style=&quot;background-image: none; border-bottom: 0px; border-left: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top: 0px; border-right: 0px; padding-top: 0px&quot; title=&quot;Redis Client_2013-06-27_14-53-25&quot; border=&quot;0&quot; alt=&quot;Redis Client_2013-06-27_14-53-25&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjVs-9PYTrrmzKxZC61_YDZdOQgDGfYp13_3G7OxzIUolNRoeqH8fQpJr5a9hXhdDCyEMDLh8yvREr5ZEACgKTSPvfduhOk0KiSRoIX1faGuaD2UtVMGnNqUQn8FdABB1LRwwuSUC1AIA/?imgmax=800&quot; width=&quot;446&quot; height=&quot;243&quot;&gt;&lt;/a&gt;&lt;/p&gt;&lt;br /&gt;&lt;ul&gt;&lt;br /&gt;&lt;li&gt;&lt;strong&gt;RPOPLPUSH&lt;/strong&gt; a single command for popping values from the tail of one&lt;br&gt;list (right pop) and pushing to the head of another (left push). Surprisingly, there is no commands for RPOPRPUSH, LPOPLPUSH, or LPOPRPUSH.&lt;/li&gt;&lt;/ul&gt;&lt;br /&gt;&lt;h4&gt;Blocking Lists&lt;/h4&gt;&lt;br /&gt;&lt;p&gt;It really interesting to know that Redis provides message queuing APIs natively. So, assume you want to write a simple messaging system where multiple clients can push data to one side of the queue and one or more listeners pop data from the other side of the queue. Listeners should just listen for new data and pop them as they arrive.&lt;/p&gt;&lt;br /&gt;&lt;ul&gt;&lt;br /&gt;&lt;li&gt;&lt;strong&gt;BRPOP&lt;/strong&gt; the blocking version of RPOP, it blocks the connection when there are no elements to pop from any of the given lists.&lt;/li&gt;&lt;/ul&gt;&lt;br /&gt;&lt;p&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEigSVdruqK_vG6INjvRQ1ClC9QNQiYfjfxkRsSHlUeTahutwKAm7KLpHIQxqkvrsDGhk914ZovFVDXqpOg-DHnan9KSuFYPp6IaR6IJOSxv32yaX6StRkELZmTofVuh0A-cy-d8m-AwLQ/s1600-h/Redis%252520Client_2013-06-28_11-04-25%25255B3%25255D.png&quot;&gt;&lt;img style=&quot;background-image: none; border-bottom: 0px; border-left: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top: 0px; border-right: 0px; padding-top: 0px&quot; title=&quot;Redis Client_2013-06-28_11-04-25&quot; border=&quot;0&quot; alt=&quot;Redis Client_2013-06-28_11-04-25&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgc3EU-rtGPXvkv5b4pVnqPukk8M1UeaIXh1F_0CUS9XeX1xg_zZOttbisHAjPRain-PGinDUF8OOHVjzNqK57gPdMx6PmMH9dVIjKoqKG-02-1J7dR4Fvm9MJ79GUdc82Q3vD8vpE0SQ/?imgmax=800&quot; width=&quot;376&quot; height=&quot;41&quot;&gt;&lt;/a&gt;&lt;/p&gt;&lt;br /&gt;&lt;p&gt;now open another Redis client window and push a message into messages list&lt;/p&gt;&lt;br /&gt;&lt;p&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEirHCSycy9IGFIbVEH3EXHxuhEHLGKkwtrtCf4aiC9LOzxWaFx_gjMbIPOQoEwybedBOBGWqLuIsC-nLuZqkkdSTyXjFLK_pSC7oZsX30D1XfQhVbJEcMt1ckOIJg5V7Hp-TerJ7ppE2g/s1600-h/Redis%252520Client_2013-06-28_11-04-53%25255B3%25255D.png&quot;&gt;&lt;img style=&quot;background-image: none; border-bottom: 0px; border-left: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top: 0px; border-right: 0px; padding-top: 0px&quot; title=&quot;Redis Client_2013-06-28_11-04-53&quot; border=&quot;0&quot; alt=&quot;Redis Client_2013-06-28_11-04-53&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEghxCPnHlXSUSIFZIfhsVnKV2SGvFbVcloaJgSi1rmBFxHlvAjLtC2fSgV3ot2eETvRju4_CnQsclSL5pl1Eusd7LHnzz0jKuZlDQdrIOO-tmc9ZkZH04N_7dA6_fqyTP2K69q_NkHHsA/?imgmax=800&quot; width=&quot;376&quot; height=&quot;60&quot;&gt;&lt;/a&gt;&lt;/p&gt;&lt;br /&gt;&lt;p&gt;if you switched back to the blocking BRPOP command window, you will find it return the key, the popped value, and the time spent blocking&lt;/p&gt;&lt;br /&gt;&lt;p&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhVFr2C9mGZM_HMbl3Jhfvp_OkdXI1MXYtEexFZF8Y-voRLMmPvlO6cMN51tjWYUQEk5XeepcBYEGlJ1VBoJK3gI5ustr1u9prx9ttzB1BaKIYUo5QtJlZRFWoe43fvoHk_AI3xEO3Cxg/s1600-h/Redis%252520Client_2013-06-28_11-05-11%25255B3%25255D.png&quot;&gt;&lt;img style=&quot;background-image: none; border-bottom: 0px; border-left: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top: 0px; border-right: 0px; padding-top: 0px&quot; title=&quot;Redis Client_2013-06-28_11-05-11&quot; border=&quot;0&quot; alt=&quot;Redis Client_2013-06-28_11-05-11&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhUW21MRsaKnBbdvHHxZoGBNeYWWqmD2ZGAY1eE86eO4W9wONGlCPIgiPYKLw08Z0D7uW-tNzshEyUeR7QnaTdbd5v1cHrZmNzAvpah56EbGkh1nw2euD5YG8Q8R40qm2szaOzjyMeF4Q/?imgmax=800&quot; width=&quot;381&quot; height=&quot;94&quot;&gt;&lt;/a&gt;&lt;/p&gt;&lt;br /&gt;&lt;ul&gt;&lt;br /&gt;&lt;li&gt;&lt;strong&gt;BLPOP&lt;/strong&gt; the blocking version of left pop LPOP&lt;/li&gt;&lt;br /&gt;&lt;li&gt;&lt;strong&gt;BRPOPLPUSH&lt;/strong&gt; the blocking version of right pop left push BRPOPLPUSH&lt;/li&gt;&lt;/ul&gt;&lt;br /&gt;&lt;h4&gt;Set&lt;/h4&gt;&lt;br /&gt;&lt;p&gt;Sets are unordered collections with no duplicate values and are an excellent choice for performing complex operations between two or more key values, such as unions or intersections.&lt;/p&gt;&lt;br /&gt;&lt;ul&gt;&lt;br /&gt;&lt;li&gt;&lt;strong&gt;SADD&lt;/strong&gt; adds the given value to the set (duplication is not allowed).&lt;/li&gt;&lt;br /&gt;&lt;li&gt;&lt;strong&gt;SREM&lt;/strong&gt; removes the given value from the set.&lt;/li&gt;&lt;/ul&gt;&lt;br /&gt;&lt;p&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgB7THAuUhbwkJ2MLzMcwVlY7P9o-5kQ8ziyVriUCM-j-eQ_4OTlzX5ZWLUivSbJsj9S3uNL4W6hCakBiM7RP4zxUNQh-yQASNuD5qmXNs3dPiQPY9uEyxQPurp8BaCYWkS070lsdHlMA/s1600-h/Redis%252520Client_2013-06-27_16-41-05%25255B4%25255D.png&quot;&gt;&lt;img style=&quot;background-image: none; border-bottom: 0px; border-left: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top: 0px; border-right: 0px; padding-top: 0px&quot; title=&quot;Redis Client_2013-06-27_16-41-05&quot; border=&quot;0&quot; alt=&quot;Redis Client_2013-06-27_16-41-05&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEh-gN-IA2DrzSkh3jSo-woUch-nZTgtOwdQG24hnCpH9VL8vvm4tCpFC_5JoQ91QrFomB_xroGdXMnsHEfYmk4PsjLuTTAP8sVDnqwges9FS-JZIEPp8cfiPc5rFsgqseitnTzxTgQaHw/?imgmax=800&quot; width=&quot;462&quot; height=&quot;162&quot;&gt;&lt;/a&gt;&lt;/p&gt;&lt;br /&gt;&lt;ul&gt;&lt;br /&gt;&lt;li&gt;&lt;strong&gt;SISMEMBER&lt;/strong&gt; tests if the given value is in the set.&lt;/li&gt;&lt;br /&gt;&lt;li&gt;&lt;strong&gt;SMEMBERS&lt;/strong&gt; returns a list of all the members of this set.&lt;/li&gt;&lt;br /&gt;&lt;li&gt;&lt;strong&gt;SUNION&lt;/strong&gt; combines two or more sets and returns the list of all elements.&lt;/li&gt;&lt;br /&gt;&lt;li&gt;&lt;strong&gt;SINTER&lt;/strong&gt; returns the intersection of two or more lists.&lt;/li&gt;&lt;br /&gt;&lt;li&gt;&lt;strong&gt;SDIFF&lt;/strong&gt; returns the elements that exist in the first list only but not in the second list.&lt;/li&gt;&lt;/ul&gt;&lt;br /&gt;&lt;p&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhLYcZS9hj2twm8ZTy06GdA6oj78dHDlQ8Fy0IMr-TV-6fYpcjxlaMAjTpLSnUgRMdafhANUrBvlx6kwyHEnXdDVvBCe52EDEqQNilNxT-EVseCHsKhWYvnQFqbK6Mtq93cEUeyackzdA/s1600-h/Redis%252520101%252520-%252520Windows%252520Live%252520Writer_2013-06-27_17-00-54%25255B3%25255D.png&quot;&gt;&lt;img style=&quot;background-image: none; border-bottom: 0px; border-left: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top: 0px; border-right: 0px; padding-top: 0px&quot; title=&quot;Redis 101 - Windows Live Writer_2013-06-27_17-00-54&quot; border=&quot;0&quot; alt=&quot;Redis 101 - Windows Live Writer_2013-06-27_17-00-54&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEg6RTQTnQBrv0RE28rJ3li2ukzn2dUkWDx7_HMr8Fh3Bbv4lPNpAzLJqqniGnrPWi4XWMBsBSE0ejUh2XZqa5ztRE-RmbNTz6fpOTf1wObUiLReE3XhXQDcI1DpIeaGpmonIsAYZ_j5SA/?imgmax=800&quot; width=&quot;473&quot; height=&quot;344&quot;&gt;&lt;/a&gt;&lt;/p&gt;&lt;br /&gt;&lt;ul&gt;&lt;br /&gt;&lt;li&gt;&lt;strong&gt;SUNIONSTORE&lt;/strong&gt; / &lt;strong&gt;SIMTERUNION&lt;/strong&gt; / &lt;strong&gt;SDIFF&lt;/strong&gt; stores the result of operation done on the second and third parameters into the first parameter.&lt;/li&gt;&lt;/ul&gt;&lt;br /&gt;&lt;p&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjSN-DqKZ4THBfW0qgu6hCCSrbiBH83-KEASaXkKBhrC6kWEN7GkjTlANOqNMqJpttt85-UAfzTanz53gV7EIg7m7AymW6FH8KQZCcsO2ygpqGbaZoLtrYJjDQaAt4WbWk6cZLAUL1aOw/s1600-h/Redis%252520Client_2013-06-27_17-09-00%25255B3%25255D.png&quot;&gt;&lt;img style=&quot;background-image: none; border-bottom: 0px; border-left: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top: 0px; border-right: 0px; padding-top: 0px&quot; title=&quot;Redis Client_2013-06-27_17-09-00&quot; border=&quot;0&quot; alt=&quot;Redis Client_2013-06-27_17-09-00&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEglXKl1iPFtWZAzqGbMDk1fjK87K-EwnCrq1z7oNLPvw_GhfLuxKQE4bUP9Y9L6KhnxKcBh0KsYsf37qmzuAePLovH8zC8tQiSCJVXNm5VfctbC_LvY0i2hYuBir-CQ-7_Hh25_3oX_Mw/?imgmax=800&quot; width=&quot;478&quot; height=&quot;158&quot;&gt;&lt;/a&gt;&lt;/p&gt;&lt;br /&gt;&lt;ul&gt;&lt;br /&gt;&lt;li&gt;&lt;strong&gt;SMOVE&lt;/strong&gt; moves one element from one set to another.&lt;/li&gt;&lt;br /&gt;&lt;li&gt;&lt;strong&gt;SCARD&lt;/strong&gt; counts the set elements (set cardinality).&lt;/li&gt;&lt;/ul&gt;&lt;br /&gt;&lt;p&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgnSOIbs3Raiv12kHEoHjaVRBCkqg3uX_xXr8evt9PHOmdIc8jcG75Lau3iEJ2EpAuNhFlkluUdMZITXRlwCl1v3Tphe5m0xKxjbuo60fAoyjkU7ZeFcR7cAIEIvwQluQjszLmR2qAeqw/s1600-h/Redis%252520Client_2013-06-27_17-21-00%25255B3%25255D.png&quot;&gt;&lt;img style=&quot;background-image: none; border-bottom: 0px; border-left: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top: 0px; border-right: 0px; padding-top: 0px&quot; title=&quot;Redis Client_2013-06-27_17-21-00&quot; border=&quot;0&quot; alt=&quot;Redis Client_2013-06-27_17-21-00&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgHgvZd0lbOm3SgkKlvNS1xhoi9VHpJd52LCzx1B68lfiNurA23u3BtJQJW2LotTdYXq0D728bK6qxbXVNGI-2WceqjhfHRXd0McTckrdeM3VTyoFtVQIIAXfgTNdc8IgtlKN6p56D0cw/?imgmax=800&quot; width=&quot;482&quot; height=&quot;255&quot;&gt;&lt;/a&gt;&lt;/p&gt;&lt;br /&gt;&lt;ul&gt;&lt;br /&gt;&lt;li&gt;&lt;strong&gt;SPOP&lt;/strong&gt; returns a random element from a set and removes it.&lt;/li&gt;&lt;br /&gt;&lt;li&gt;&lt;strong&gt;SRANDMEMBER&lt;/strong&gt; returns a random element from a set but does not remove it&lt;/li&gt;&lt;/ul&gt;&lt;br /&gt;&lt;h4&gt;Sorted Sets&lt;/h4&gt;&lt;br /&gt;&lt;p&gt;Sorted set is similar to a regular set, but now each value has an associated score. This score is used to sort the elements in the set. Sorted sets take something from each of the other collections data types. They are ordered like lists and are unique like sets. They have field-value pairs like hashes, but rather than string fields, they are instead numeric scores that denote the order of the values. Internally, sorted sets keep values in order, so inserts can take log(N) time to insert (where N is the size of the set), rather than the constant time complexity of hashes or lists.&lt;/p&gt;&lt;br /&gt;&lt;ul&gt;&lt;br /&gt;&lt;li&gt;&lt;strong&gt;ZADD&lt;/strong&gt; add a value with a specified score.&lt;/li&gt;&lt;br /&gt;&lt;li&gt;&lt;strong&gt;ZRANGE&lt;/strong&gt; returns the elements between start index (zero-based) and end index (-1 means to the end of the sorted set. Put &lt;strong&gt;WITHSCORES&lt;/strong&gt; at the end of command to get elements and scores, not only the elements. To get them in reverse, insert the word REV, as in &lt;strong&gt;ZREVRANGE&lt;/strong&gt;.&lt;/li&gt;&lt;/ul&gt;&lt;br /&gt;&lt;p&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjWZWFoyf3D30eVD0CgVo5hPW6k17B_eP5dEhFdAJgJHG1xJzsZ59o3y-MAqSIqJF4z8_qFc7k6WUzmMOik3KA5MsVgviX2-e4RQh9z1Dbidze6eNH01fFyoUNaILjJzDYN0OAHwWm7cg/s1600-h/Redis%252520Client_2013-06-28_08-51-02%25255B3%25255D.png&quot;&gt;&lt;img style=&quot;background-image: none; border-bottom: 0px; border-left: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top: 0px; border-right: 0px; padding-top: 0px&quot; title=&quot;Redis Client_2013-06-28_08-51-02&quot; border=&quot;0&quot; alt=&quot;Redis Client_2013-06-28_08-51-02&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiNxclUowRHPVpbCKqq7myg08H7vQdXDDwnxQzkEaNJmRhl1UL9EYJHipGgnXV6OCC02uPHNJ7OBVxBBXMHDVx6DpLEJ9Otc7poaC0mvhEg5PTYqZR_4DSVdtd0gXXJx8l0l0vCZArEzA/?imgmax=800&quot; width=&quot;484&quot; height=&quot;328&quot;&gt;&lt;/a&gt;&lt;/p&gt;&lt;br /&gt;&lt;ul&gt;&lt;br /&gt;&lt;li&gt;&lt;strong&gt;ZRANGEBYSCORE&lt;/strong&gt; since we are using a sorted set, it’s more likely to get elements by score ranges instead of index ranges (x &amp;lt;= score &amp;lt;= y). We can make a score number exclusive by prefixing it with an opening parenthesis ( x &amp;lt; score &amp;lt;= y). &lt;/li&gt;&lt;/ul&gt;&lt;br /&gt;&lt;p&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEga_HMevZVt1n4JREj3tJlWEDyGnI5e32MY1bUQ3htlRqwVDxlfzSgj_SVhv-LFRQ1ycpWKwcICtdrMLclYsA_vR6loHHFnttFk_PvQS5IVXWiovLDf-Fuxf0e__6_zWTykpU_kU9M0hg/s1600-h/Redis%252520Client_2013-06-28_11-49-34%25255B3%25255D.png&quot;&gt;&lt;img style=&quot;background-image: none; border-bottom: 0px; border-left: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top: 0px; border-right: 0px; padding-top: 0px&quot; title=&quot;Redis Client_2013-06-28_11-49-34&quot; border=&quot;0&quot; alt=&quot;Redis Client_2013-06-28_11-49-34&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjpcySMvTYgEjVe5G0TYd-7TYccRS-duBiLDVt845vsOWvKMEoPxwHwbW9vjICWq5HjFDttX1mxK5OLmc8K3rWt-nbH6-mSPnas3k4l3YbRohg376MDNA3fl8AJYKt1sp5-QrCIWZ1uLw/?imgmax=800&quot; width=&quot;494&quot; height=&quot;245&quot;&gt;&lt;/a&gt;&lt;/p&gt;&lt;br /&gt;&lt;ul&gt;&lt;br /&gt;&lt;li&gt;&lt;strong&gt;-inf / inf&lt;/strong&gt; negative / positive infinities. can be used in retrieval (by index or by score). We can also range by both positive and negative values.&lt;/li&gt;&lt;br /&gt;&lt;li&gt;&lt;strong&gt;ZREMRANGEBYRANK&lt;/strong&gt; / &lt;strong&gt;ZREMRANGEBYSCORE&lt;/strong&gt; remove values by rank or score.&lt;/li&gt;&lt;br /&gt;&lt;li&gt;&lt;strong&gt;ZINCRBY&lt;/strong&gt; Increments the score of member in the sorted set stored at key by increment. If member does not exist in the sorted set, it is added with increment as its score (as if its previous score was 0.0). If key does not exist, a new sorted set with the specified member as its sole member is created. It is possible to provide a negative value to decrement the score.&lt;/li&gt;&lt;/ul&gt;&lt;br /&gt;&lt;p&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhkjljOKk9pPEoCYmDt4MjDDVl_Z10KsRllW24zpGoDwO_bKBaPTAZZlM9j3hb3MkSuD4UVvdIdz1j7699bx8XFiau4_5hQ97WrIvlJoR2_c3-XAtIeqlznRpHszBXQThCaaPV4BzS2vg/s1600-h/Redis%252520Client_2013-06-28_08-58-48%25255B4%25255D.png&quot;&gt;&lt;img style=&quot;background-image: none; border-bottom: 0px; border-left: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top: 0px; border-right: 0px; padding-top: 0px&quot; title=&quot;Redis Client_2013-06-28_08-58-48&quot; border=&quot;0&quot; alt=&quot;Redis Client_2013-06-28_08-58-48&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgBRp8Lg8MVJEJ7iR5At31wN7nwMPvva0pIKosng-xOSxUYR9kJXcWRTQ4zvqArHi9REn0kFqDKChGgRa3FOs1feBd5o4VH52aT9yo66U3wWfPcpTQHnNFEYX0R9fVx4msGucz9BruF1A/?imgmax=800&quot; width=&quot;488&quot; height=&quot;162&quot;&gt;&lt;/a&gt;&lt;/p&gt;&lt;br /&gt;&lt;ul&gt;&lt;br /&gt;&lt;li&gt;&lt;strong&gt;ZUNIONSTORE&lt;/strong&gt; Computes the union of numkeys sorted sets given by the specified keys, and stores the result in destination set. It is mandatory to provide the number of input keys (numkeys) before passing the input keys and the other (optional) arguments. Parameters needed:&lt;/li&gt;&lt;br /&gt;&lt;ul&gt;&lt;br /&gt;&lt;li&gt;destination ==&amp;gt; a set to hold the union operation result&lt;/li&gt;&lt;br /&gt;&lt;li&gt;numkeys ==&amp;gt; number of keys you are going to join.&lt;/li&gt;&lt;br /&gt;&lt;li&gt;weight ==&amp;gt; optional number(s) to multiply each score of the relative key by (if you have two keys, you can have two weights and son on)&lt;/li&gt;&lt;br /&gt;&lt;li&gt;aggregate ==&amp;gt; optional rule to specify how the results of the union are aggregated. This option defaults to SUM, where the score of an element is summed across the inputs where it exists. When this option is set to either MIN or MAX, the resulting set will contain the minimum or maximum score of an element across the inputs where it exists.&lt;/li&gt;&lt;/ul&gt;&lt;/ul&gt;&lt;br /&gt;&lt;p&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEizYXG_2ys9itVluYfL8iV4PZ7rewF-f3V9UaTE56fBrpSjuigSyUyZDSx_cuJEyhYS0-OLziW3WMhtnZnVPudd0KhO2Dyb0N0mt4xgVGNjzi0v8-q5h-87y3ZKXSvMv4gzEh4T3BVUyw/s1600-h/Redis%252520101%252520-%252520Windows%252520Live%252520Writer_2013-06-28_12-29-14%25255B3%25255D.png&quot;&gt;&lt;img style=&quot;background-image: none; border-bottom: 0px; border-left: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top: 0px; border-right: 0px; padding-top: 0px&quot; title=&quot;Redis 101 - Windows Live Writer_2013-06-28_12-29-14&quot; border=&quot;0&quot; alt=&quot;Redis 101 - Windows Live Writer_2013-06-28_12-29-14&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEju7SafK9ClMcPsCFysBEG7tVEGhgZGIz7hR2LiGEe4UoZ1f6oHpaXzxoqf2e85efzd41X90lORlFFgaHMiPt-jWh9-6wwHRmITsACRdfw1u_PYYkatlLy_2FJFZs_9OegoYsMZYCCJcA/?imgmax=800&quot; width=&quot;497&quot; height=&quot;331&quot;&gt;&lt;/a&gt;&lt;/p&gt;&lt;br /&gt;&lt;p&gt;In the above example we prepared two sorted sets, sset1 with elements (1 “one” 2 “two”) , sset2 with elements (1 “one” 2 “two” 3 “three”). Then tell Redis to merge these two sets with the following parameters:&lt;/p&gt;&lt;br /&gt;&lt;ul&gt;&lt;br /&gt;&lt;ul&gt;&lt;br /&gt;&lt;li&gt;store the operation result in sorted set named &lt;em&gt;out&lt;/em&gt;&lt;/li&gt;&lt;br /&gt;&lt;li&gt;we going to merge &lt;em&gt;2&lt;/em&gt; sorted sets, then provide them &lt;em&gt;sset1 sset2&lt;/em&gt;.&lt;/li&gt;&lt;br /&gt;&lt;li&gt;we going to use &lt;em&gt;WEIGHTS&lt;/em&gt;, then provide these weights &lt;em&gt;2 3&lt;/em&gt;.&lt;/li&gt;&lt;/ul&gt;&lt;/ul&gt;&lt;br /&gt;&lt;h4&gt;Hash&lt;/h4&gt;&lt;br /&gt;&lt;p&gt;Hash is a collections object that can hold any number of key-value pairs.&lt;/p&gt;&lt;br /&gt;&lt;ul&gt;&lt;br /&gt;&lt;li&gt;&lt;strong&gt;HMSET&lt;/strong&gt; store the key-value pairs into the hash (first parameter.&lt;/li&gt;&lt;br /&gt;&lt;li&gt;&lt;strong&gt;HVALS&lt;/strong&gt; returns the values of a hash.&lt;/li&gt;&lt;br /&gt;&lt;li&gt;&lt;strong&gt;HKEYS&lt;/strong&gt; returns the keys of a hash.&lt;/li&gt;&lt;br /&gt;&lt;li&gt;&lt;strong&gt;HGET&lt;/strong&gt; returns the value of of a single key in a hash.&lt;/li&gt;&lt;/ul&gt;&lt;br /&gt;&lt;p&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjV9RvKa2Z4Tc9a8EW6r-k00aNu_gjPLTbx3w7ZUOoLVMxq79UD-Tjrso_0rezVttEYvaaqQQzUTipSJC0jpiYHd90ViQZF_TuPUo7liKllCPfTpyx9F5Y1eFCt2LbCl79OjFcrpyY6Kg/s1600-h/Redis%252520Client_2013-06-28_10-09-24%25255B4%25255D.png&quot;&gt;&lt;img style=&quot;background-image: none; border-bottom: 0px; border-left: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top: 0px; border-right: 0px; padding-top: 0px&quot; title=&quot;Redis Client_2013-06-28_10-09-24&quot; border=&quot;0&quot; alt=&quot;Redis Client_2013-06-28_10-09-24&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhwPslMAwg6Z2yqbKNlU8_sFhcyrXRf6T1LGmhv7RMtkC7IBfRridYmUzseXZ_sW26o5xnr_DmZPKMM-Fn9CSewWhdWnzzTVSZQIVj9TJmO4YQxJYODU-GyyGyqTXU-opR0VLHYoPBQiQ/?imgmax=800&quot; width=&quot;744&quot; height=&quot;312&quot;&gt;&lt;/a&gt;&lt;/p&gt;&lt;br /&gt;&lt;ul&gt;&lt;br /&gt;&lt;li&gt;&lt;strong&gt;HDEL&lt;/strong&gt; deletes a key-value pair from a hash.&lt;/li&gt;&lt;br /&gt;&lt;li&gt;&lt;strong&gt;HSET&lt;/strong&gt; updates or adds a value at a specified key in a hash.&lt;/li&gt;&lt;br /&gt;&lt;li&gt;&lt;strong&gt;HINCRBY&lt;/strong&gt; increments an integer field value by some count in a hash. It is possible to provide a negative value to decrement.&lt;/li&gt;&lt;br /&gt;&lt;li&gt;&lt;strong&gt;HLEN&lt;/strong&gt; returns the number of fields in a hash.&lt;/li&gt;&lt;/ul&gt;&lt;br /&gt;&lt;p&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEi9ZmTlgYC57wzOZ5puSjK-2cG7dIpG0SoUHBuDiFMi6VnD1YwjXYbcFZ6Mcil9JVtrMTldEmog8k6v7HKcWwGU5N5EPI70PyadEH1aoW-MudWBe8SArfmafzwhyOhgNLTtL-eiQ_43rQ/s1600-h/Redis%252520Client_2013-06-28_10-17-28%25255B6%25255D.png&quot;&gt;&lt;img style=&quot;background-image: none; border-bottom: 0px; border-left: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top: 0px; border-right: 0px; padding-top: 0px&quot; title=&quot;Redis Client_2013-06-28_10-17-28&quot; border=&quot;0&quot; alt=&quot;Redis Client_2013-06-28_10-17-28&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEh6Tkr8RYopnfJ7Eo6Ygnixhdfv-Y5bE2mUwRbDs9xTgFhrGFZD_BS17wTtB_hyk1g4nP6HD-vIktbCo0oVX5WVhEMEcZj2Zi1arvXbqlmMFHgnbQrDbLMTZoxAQsHn0xpfL82bUltxIA/?imgmax=800&quot; width=&quot;489&quot; height=&quot;293&quot;&gt;&lt;/a&gt;&lt;/p&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;h4&gt;Database Namespaces&lt;/h4&gt;&lt;br /&gt;&lt;p&gt;You may have been wondering, which database we working on. So far, we have interacted only with a single namespace. In Redis’s terminology, a namespace is called a &lt;i&gt;database &lt;/i&gt;and is keyed by a number. So far, we’ve always interacted with the default namespace 0 (also known as database 0).&lt;br /&gt;&lt;ul&gt;&lt;br /&gt;&lt;li&gt;Use &lt;strong&gt;SELECT&lt;/strong&gt; command to switch to different database and provide it a DB number. Setting a value to a key in one database will not affect any other key in other databases.&lt;/li&gt;&lt;/ul&gt;&lt;br /&gt;&lt;p&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgqLw3Ih0Ir6AP7YFmwDhp0zQ3YhgnCNX0XUPhKM7HsU2gsN0tjcjcA0u5OYqAJnCd2rjhZ84eY4-0Vu1iLqmEgPP0naSl-qo3sOyTj-pjAg0PfB-fjpGMsBxd6g11S9iNxn8tEH1sGRw/s1600-h/clip_image001%25255B6%25255D.png&quot;&gt;&lt;img style=&quot;background-image: none; border-bottom: 0px; border-left: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top: 0px; border-right: 0px; padding-top: 0px&quot; title=&quot;clip_image001&quot; border=&quot;0&quot; alt=&quot;clip_image001&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhKi-VGqnhDVuhyphenhyphenAmjQOs0Dx2_bP6AgikzJDC9uKfyu-VtWR6s2aAKE50iplNqiGlVp6RwVyaPDSzqQ4Oq7LAnphvV39jk9bmqSVIGUv3Anc7TFidKrTOhZi648GqnNrHOG-Mc_u9tQ1g/?imgmax=800&quot; width=&quot;432&quot; height=&quot;361&quot;&gt;&lt;/a&gt;&lt;/p&gt;&lt;br /&gt;&lt;ul&gt;&lt;br /&gt;&lt;li&gt;Since all databases are running in the same server instance, Redis lets us move keys from one database to another with the &lt;strong&gt;MOVE&lt;/strong&gt; command.&lt;/li&gt;&lt;/ul&gt;&lt;br /&gt;&lt;p&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhZvbYe9PGa5bmEl7U4tkjedIJJpVRLyndZYhrauQnSkRclaXBxXYRCcylF1IfxAs5OWIJNUBRT3jy7T6yYeovZ3jDWUEou-uoOmajrM6dPBX-xVOQW17sJ6P2oCDJXvDMCRn2pQtflUw/s1600-h/clip_image002%25255B5%25255D.png&quot;&gt;&lt;img style=&quot;background-image: none; border-bottom: 0px; border-left: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top: 0px; border-right: 0px; padding-top: 0px&quot; title=&quot;clip_image002&quot; border=&quot;0&quot; alt=&quot;clip_image002&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhsf36p8rbF2S2VI-doYpKuT8SAfGxkMASzHYFNz8MiGRCh8Lcvnwm72sI3BVPGXA1_d_h-FG5H2-3D0NOrJ7NH177E1xqBTcz3b7NmqvKpaLLdUT6imuimMh1Qnslcl6cxasl1pnaGuA/?imgmax=800&quot; width=&quot;338&quot; height=&quot;159&quot;&gt;&lt;/a&gt;&lt;/p&gt;&lt;br /&gt;&lt;p&gt;This can be useful for running different applications against a single Redis server but still allow these multiple applications to trade data between each other.&lt;br /&gt;&lt;h4&gt;More commands&lt;/h4&gt;&lt;br /&gt;&lt;ul&gt;&lt;br /&gt;&lt;li&gt;&lt;strong&gt;RENAME&lt;/strong&gt; rename a key&lt;/li&gt;&lt;br /&gt;&lt;li&gt;&lt;strong&gt;TYPE&lt;/strong&gt; return the type of a key’s value&lt;/li&gt;&lt;br /&gt;&lt;li&gt;&lt;strong&gt;DEL&lt;/strong&gt; deletes a key-value pair&lt;/li&gt;&lt;br /&gt;&lt;li&gt;&lt;strong&gt;FLUSHDB&lt;/strong&gt; removes all keys in database&lt;/li&gt;&lt;br /&gt;&lt;li&gt;&lt;strong&gt;FLUSHALL&lt;/strong&gt; removes all keys from all databases on this server instance.&lt;/li&gt;&lt;/ul&gt;&lt;br /&gt;&lt;p&gt;Redis’s data types and the complex queries it can perform make it much more than a standard key-value store. It can act as a stack, queue, or priority queue; can be an object store (via hashes); and even can perform complex set operations such as unions, intersections, and subtractions (diff). It provides many atomic commands, and for those multistep commands, it provides a transaction mechanism. It has a built-in ability to expire keys, which is useful as a cache.&lt;/p&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;p&gt;In this post we just introduced Redis as a data structure server. In later post we going to cover the advanced features of Redis.&lt;/p&gt;  </description><link>http://ebeid-soliman.blogspot.com/2013/06/redis-101.html</link><author>noreply@blogger.com (Ebeid Soliman ElSayed)</author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjoEXLL_igfXyQnZo3wstBJ7pWfE3S2lFRkWo4JgubuL1hiB5OaqOVz4N46SbPJQ6evoySooryIKnoaYbpWvYWf1wcSdb60vmiEU4gpYo39Z8SaSA4w_TyWzsEV8aK-fsaqBLqCiBFJJA/s72-c?imgmax=800" height="72" width="72"/></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-59384554657271185.post-1002609715498201480</guid><pubDate>Mon, 24 Jun 2013 21:59:00 +0000</pubDate><atom:updated>2013-06-27T17:42:29.513-05:00</atom:updated><category domain="http://www.blogger.com/atom/ns#">PostgreSQL</category><title>PostgreSQL 101</title><description>&lt;p&gt;PostgreSQL is the finest open source example of the relational database management system (RDBMS) tradition. This means that PostGreSQL is a design-first data store. First you design the schema, and then you enter data that conforms to the definition of that schema.&lt;/p&gt; &lt;h3&gt;History of PostgreSQL&lt;/h3&gt; &lt;blockquote&gt; &lt;p&gt;PostgreSQL has existed in the current project incarnation since 1995, but its roots&lt;br&gt;are considerably older. The original project was written at Berkeley in the early 1970s&lt;br&gt;and called the Interactive Graphics and Retrieval System, or “Ingres” for short. In the&lt;br&gt;1980s, an improved version was launched post-Ingres—shortened to Postgres. The&lt;br&gt;project ended at Berkeley proper in 1993 but was picked up again by the open source&lt;br&gt;community as Postgres95. It was later renamed to PostgreSQL in 1996 to denote its&lt;br&gt;rather new SQL support and has remained so ever since.&lt;/p&gt;&lt;/blockquote&gt; &lt;h3&gt;Installation&lt;/h3&gt; &lt;p&gt;You can download the latest PostgreSQL installer from &lt;a href=&quot;http://www.postgresql.org/download&quot;&gt;http://www.postgresql.org/download&lt;/a&gt; (In this tutorial I’m using the Windows 64bit installer). Setup is straight-forward. Below are screen-shots of installation steps:&lt;/p&gt; &lt;p&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhYGc_Ytx2AuNfVjs0eTLBXJkTSvxxILuv5Gv7t8oJc4vvDFJNko1I7uM27QhN9_l7BVdk20AAT9rPoE2Bsvv0FoZ4v0oF4oKilgdQMrx6uUpGe7nZln5Yc7T45vnQZGExUlgBYPxNfFg/s1600-h/Setup_2013-06-24_14-23-08%25255B3%25255D.png&quot;&gt;&lt;img style=&quot;background-image: none; border-right-width: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px&quot; title=&quot;Setup_2013-06-24_14-23-08&quot; border=&quot;0&quot; alt=&quot;Setup_2013-06-24_14-23-08&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEimUOWML4h23t3RD_6qHXFB4qE1GzkMQ4uF6fQokNks8oHitkdPp_RZFOpZ1BUErwy8lztZJ6lahFRzBOndecsR0-G4djTC1YsOYocUu7R5PFQ8-T3ZxdQOIVrjNmKWCSszKPkrHq00gw/?imgmax=800&quot; width=&quot;306&quot; height=&quot;242&quot;&gt;&lt;/a&gt;&lt;/p&gt; &lt;p&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjMRSjAUtxGZiaraKgcmKHADmHolpwLH7oh2_W0S39SK8J6beecj0oZR2biaGK9kEN4pthksO7XN0aEgI3q9770yTK39bDMBWQ_nvHU_spyzn4QviQk9TPxcaSjYh11Bbh_ItqFcZoyKg/s1600-h/Setup_2013-06-24_14-23-13%25255B3%25255D.png&quot;&gt;&lt;img style=&quot;background-image: none; border-right-width: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px&quot; title=&quot;Setup_2013-06-24_14-23-13&quot; border=&quot;0&quot; alt=&quot;Setup_2013-06-24_14-23-13&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEg5goeC2ZbO7pL3eXKyoj1K2LmcdqVzlqQLBBu130Hg4N8ZUPzIh_gwwTQ66NLe5_Qn654AdcxY1u5Ijn1r9qo4uUg8OSz0DfaN_khqqraa8tVIcPULt1R7cIi1DlgBjrcqveGZLmqrcg/?imgmax=800&quot; width=&quot;309&quot; height=&quot;244&quot;&gt;&lt;/a&gt;&lt;/p&gt; &lt;p&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEg0EY6qPK2xdl60C55T27xHBh8WrfWI4Zdo-0HppsAmD2NcFUkBht13MHj4CpMhD_KRCs8uEeYppXkw_97zLAYU3605EqgLVSA3Jkq7zqBsUHXDZcpcSmVgYhllmSVMQkJZ8I0Qk-IZWg/s1600-h/Setup_2013-06-24_14-23-16%25255B3%25255D.png&quot;&gt;&lt;img style=&quot;background-image: none; border-right-width: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px&quot; title=&quot;Setup_2013-06-24_14-23-16&quot; border=&quot;0&quot; alt=&quot;Setup_2013-06-24_14-23-16&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhw1oMB7kVc9Gc3UD-TFA9oDDAMB6X6TMTggrk1HYt9oMiQxjhKfblM9flsVbaidRcEcoEZPDByw1jQmd8szyWuqFHFs3psZcMRfQmEWhDNuuu0sOdW3M8pPyw68xA2WlF4zc74EAN1YA/?imgmax=800&quot; width=&quot;312&quot; height=&quot;247&quot;&gt;&lt;/a&gt;&lt;/p&gt; &lt;p&gt;remember the superuser password, you will need it later&lt;/p&gt; &lt;p&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhjDEFhtVTkJ2ijwiJNnF0UFe64A4WkcAGFNf5d88zLqmBdTf57wslP0zwrh90R7YwDQhfxeNH_u2_4SPypbRge4zGBGGGK9Ptsjp3SROtX91thUAOb6GZx5XnqlxtLLQVVSfwH1YHRJQ/s1600-h/Setup_2013-06-24_14-23-37%25255B3%25255D.png&quot;&gt;&lt;img style=&quot;background-image: none; border-right-width: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px&quot; title=&quot;Setup_2013-06-24_14-23-37&quot; border=&quot;0&quot; alt=&quot;Setup_2013-06-24_14-23-37&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjvrh44RUwEfXwZQQZ_JXUb9EChvz_IRbo-4quiNUYX-G9pySdsrxKT3sci_9JQM6OSPUHwHZ_mIAgvEXQWL_vnnRwwn0XAElB23FH83X50bH0gE2OdWWU0MIZ0hp3snWwg51GRLGUiYw/?imgmax=800&quot; width=&quot;315&quot; height=&quot;249&quot;&gt;&lt;/a&gt;&lt;/p&gt; &lt;p&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhwyy-sb4-BYAqEWs5ZE4SeaXbOajrpwqITSL76wCh8hNOVeLhfI7jJgh1tXvCfsHLs_BLyakmpZvPqzoELOTImF4c5UWWFlwqYmGnnLCV7mFOT4BXeTEmTzGM7dzAqBvi9owULbZdCCA/s1600-h/Setup_2013-06-24_14-23-41%25255B3%25255D.png&quot;&gt;&lt;img style=&quot;background-image: none; border-right-width: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px&quot; title=&quot;Setup_2013-06-24_14-23-41&quot; border=&quot;0&quot; alt=&quot;Setup_2013-06-24_14-23-41&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiqwlyCe8Vev6yQAyq2HD3ZeVwjWz8qNydUrD5X2KE9bubkZfua4eoKDGT8QmB3nMPs8oEnFVTuOJZd8NCAYySpoii80GSAH2vKro8oYZQE5ahn1eytnc2ree8vfGsG2JVBjozpo1jyQA/?imgmax=800&quot; width=&quot;316&quot; height=&quot;250&quot;&gt;&lt;/a&gt;&lt;/p&gt; &lt;p&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgfet7zF4SXJrWTJspj1FuBuQBdIfMYfcZ4iiq3Rx2ZCGxA-K-oQ72u1qJxFXix2suE6IjH4knA2uCcYmQLVSy1yKih5KFag-ouPI-zdvei2IqIcMQ5Fa_MD3vkldegpFQ7RflbVAXwog/s1600-h/Setup_2013-06-24_14-23-44%25255B3%25255D.png&quot;&gt;&lt;img style=&quot;background-image: none; border-right-width: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px&quot; title=&quot;Setup_2013-06-24_14-23-44&quot; border=&quot;0&quot; alt=&quot;Setup_2013-06-24_14-23-44&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEj4_QjajD_GbygE4W4fDnhfPHmOaZcla09N0eEiI-CPxQrPplh1Q-qcukCXMxzBEyv_HYSmYIZcf0QyW_mSaI-TRgdBnm4mAhB8ls_ckvwSq1kGf9H-aVa2xD2k8GbJIkaMgj59zPKa6w/?imgmax=800&quot; width=&quot;317&quot; height=&quot;250&quot;&gt;&lt;/a&gt;&lt;/p&gt; &lt;p&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhhWZ97NzbmSGRtyqXJ5HgTmAJvav835lutXyyDshilX3lB1XoNVN80Zsn0ZjnKeJwKSh1s2jA-5KgbY0Odd8K8aHh31nZEVYtCH1dOYinLDDGLePsCHnuVG8_Yui165F88SVlAFD2dJA/s1600-h/Setup_2013-06-24_14-23-47%25255B3%25255D.png&quot;&gt;&lt;img style=&quot;background-image: none; border-right-width: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px&quot; title=&quot;Setup_2013-06-24_14-23-47&quot; border=&quot;0&quot; alt=&quot;Setup_2013-06-24_14-23-47&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiDK2KuO8z4Wtpyo6cu6E2LcY3XbSZ-8nX5ZN9Kt-pdlL7-MhhyphenhyphengoGgCUlYM2gxfxVDVjVw6VgnoW5E8GToOwhoYYkhODY1rmqL1x0qk7M0biUPYKyWRuvRgN5Ea6931UrtywJBOTGdlg/?imgmax=800&quot; width=&quot;318&quot; height=&quot;251&quot;&gt;&lt;/a&gt;&lt;/p&gt; &lt;p&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEja0fktNnGUlBEATIcO-JCoKKD6_f4Angc1-lVBDF0JJnvw6bNfi8x1n59XGtiYsqKAsvYmU_pB0LrwW-PMAPjmCqbWek9a2vjd723YFh6ku87GkenIl_wTLYuQLIBjCgq7Gf8i8eR8Kw/s1600-h/Setup_2013-06-24_14-23-56%25255B3%25255D.png&quot;&gt;&lt;img style=&quot;background-image: none; border-right-width: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px&quot; title=&quot;Setup_2013-06-24_14-23-56&quot; border=&quot;0&quot; alt=&quot;Setup_2013-06-24_14-23-56&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEj3k62drruUZe6KKco8Beq-NLLt5hIsk7Q_0tw-KYhtvQ6DF7DEhKG5Akl3-XeyTDTGURhOgJBaMe2rEa8eOfOWA6oacpzzZZlTq8ebKVM8uQGx60lG7SZQAMhBfjVcNZvDF7G3VSMivg/?imgmax=800&quot; width=&quot;318&quot; height=&quot;251&quot;&gt;&lt;/a&gt;&lt;/p&gt; &lt;p&gt;when the PostgreSQL installation finish, you could choose to run Stack Builder to install additional tools. In my case I chose to run Stack builder&lt;/p&gt; &lt;p&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEh_slvtJck4zP_Rxvhei5Whnd_Mtb-AwIp3iRxA2Y4W5c8ATJArx7WcdI63Je5PbfFBMh3VAX-UvQKAkEcHpk9wdo76oYnN5GSsD6uH-QwohTRtMZ68h1Ykrm9Qoq7J4Ij_asKvHHGwpQ/s1600-h/Setup_2013-06-24_14-25-58%25255B3%25255D.png&quot;&gt;&lt;img style=&quot;background-image: none; border-right-width: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px&quot; title=&quot;Setup_2013-06-24_14-25-58&quot; border=&quot;0&quot; alt=&quot;Setup_2013-06-24_14-25-58&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhg1DDwWLIy29WukvgIEb5mB75b-lt746vv7MEjGJDWlEWxpOs0rt9snz9XJ3gJ4BZZCISakRsgXEByAMGMMf7twnP6ITkNitUnxukO2QQlwVEjNPlKwLxmG1Q4TK1sy-6JludV8K3KIw/?imgmax=800&quot; width=&quot;317&quot; height=&quot;250&quot;&gt;&lt;/a&gt;&lt;/p&gt; &lt;p&gt;choose your recently installed instance&lt;/p&gt; &lt;p&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEh3dHtebl-Z2keU8lBG4HPOpT2Lbw5ga_PnRq1fRyy-sQh34CShQ3Xbc1_a437Ua2ye2FUi74V0xhHrYC8JzCoP26G34-tDAj4JpYFssA-X7AssaOcaJGQKobw6t5La9g71R77sRu8aww/s1600-h/Stack%252520Builder%2525203.1.0_2013-06-24_14-26-15%25255B3%25255D.png&quot;&gt;&lt;img style=&quot;background-image: none; border-right-width: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px&quot; title=&quot;Stack Builder 3.1.0_2013-06-24_14-26-15&quot; border=&quot;0&quot; alt=&quot;Stack Builder 3.1.0_2013-06-24_14-26-15&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjbRydcMvYvX_F3DqZuMdSSL-LvL_MDuRybQvqZzY0uLHpWBIXGdqgMCuneeV8gc5QybFAfwLUtz9-8cZcKk-lTmncHi0DCkukfrMvbOA0P0C3LokwBRmY4e4-VLCfFctXlfI8RDAiJTQ/?imgmax=800&quot; width=&quot;322&quot; height=&quot;224&quot;&gt;&lt;/a&gt;&lt;/p&gt; &lt;p&gt;and I choose to install Npgsql database driver (for future .Net development) and phpPgAdmin for administration tasks.&lt;/p&gt; &lt;p&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgTv6hoABimGTxVL-imCGIevEo4zS1KVu0eF2P8ec3HNSkxKcMwEjDvQhZKXGoaWpZOK0hO0Epweq9Z51zL0tk_9MxAho4P2VjV8yE3aoVUVhhbAJB-JEAewwXQMmVRxProC9ThQHqTlQ/s1600-h/Stack%252520Builder%2525203.1.0_2013-06-24_14-26-54%25255B3%25255D.png&quot;&gt;&lt;img style=&quot;background-image: none; border-right-width: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px&quot; title=&quot;Stack Builder 3.1.0_2013-06-24_14-26-54&quot; border=&quot;0&quot; alt=&quot;Stack Builder 3.1.0_2013-06-24_14-26-54&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjHuY8YM9SC2ZB3cTZiXNndthbJQ6q8vhEeAirJy2QbwddqKOKcZHnS1QAbe3HmBPbsaPXvJwaGztAZ71Hu8XSl4-ysDYpL6-8pIG8Hmk37xyBQnbevSl68sp3E5FXAI_OsvYnh9NUytA/?imgmax=800&quot; width=&quot;326&quot; height=&quot;227&quot;&gt;&lt;/a&gt;&lt;/p&gt; &lt;p&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEj8Wf1DgKkHejoBPX0hgBafs8zBT77obSMlD3jAdXEu50xhS8Anv93IjP757IA-A9oh8HDPLGQXCsCZLtQ43lj3El3GZgRO0yA5XFrM62898SUp1sTgJ0Wnvzhev1lTWrynCgMHCiE2MA/s1600-h/Stack%252520Builder%2525203.1.0_2013-06-24_14-27-00%25255B3%25255D.png&quot;&gt;&lt;img style=&quot;background-image: none; border-right-width: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px&quot; title=&quot;Stack Builder 3.1.0_2013-06-24_14-27-00&quot; border=&quot;0&quot; alt=&quot;Stack Builder 3.1.0_2013-06-24_14-27-00&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiDMqL2I4FflVfZgZ3Fc9LzvidS9uD5at4yrOa1iK8PojEsMxii9t2rOJ4zNe8cqZSuIVMROnHYQ7afUgMMM03wIgmU8p_8iI3okYt96ygHIB1zAat5Gbxl0F7nL3emdh-5Z4uSBvVk8A/?imgmax=800&quot; width=&quot;328&quot; height=&quot;228&quot;&gt;&lt;/a&gt;&lt;/p&gt; &lt;p&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhd9rMWbtnqfgqxRiQw0UfPaxr2O-ixUfRRcQmVXmCAExXEYNxLdxdkEZRvq2drymEkBdaW1XfFuKNMmqmlLIFpQe3c2dSeLCcXX-3yCe5M8kSZDxX7lz9QsU8ANlRlNqQ5-uhvu0efoA/s1600-h/Stack%252520Builder%2525203.1.0_2013-06-24_14-27-13%25255B3%25255D.png&quot;&gt;&lt;img style=&quot;background-image: none; border-right-width: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px&quot; title=&quot;Stack Builder 3.1.0_2013-06-24_14-27-13&quot; border=&quot;0&quot; alt=&quot;Stack Builder 3.1.0_2013-06-24_14-27-13&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhxcU1kQ_ysDKj9tPZhtPDHzYPh98oW2r37FChdeEywh7ErbjCVQ7pZzf-Oj1qUQHS_tjh1iHdeZ4pqLtseWP1Lzd5WK2TGtcZ386yHzU2tatjsmcyKN3U2IR9gre1jyCnkqFWVGwxcew/?imgmax=800&quot; width=&quot;329&quot; height=&quot;229&quot;&gt;&lt;/a&gt;&lt;/p&gt; &lt;p&gt;Stack Builder will lunch installation wizards for your chosen tools in sequence&lt;/p&gt; &lt;p&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjyVmliVNsNHLx_1zPSPU0KZsAdqTqL8mb6Rd4bi6W4ZL9EPY-zj7zsA0hFSZJITa7XKedY78WYmqy1lgZ2SZVSRAyV_Y-pdD8rDcHO_uKL90q1sib4JhvRUloU3X5TlOT6zgMUlBPLRw/s1600-h/Setup_2013-06-24_14-27-30%25255B3%25255D.png&quot;&gt;&lt;img style=&quot;background-image: none; border-right-width: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px&quot; title=&quot;Setup_2013-06-24_14-27-30&quot; border=&quot;0&quot; alt=&quot;Setup_2013-06-24_14-27-30&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhvXYeXE8uGOWMB01i3Inl-3ELiBDejg0a3278_OVpUAWTlQgaOkyT1FnD4e8FXumUd6F0KbixAPakQfrWcID1xZTR5xEXsTmYVwkrOb3slgicy1V0OZWHfIg9TLzQtnhoqQhYuj2jyhA/?imgmax=800&quot; width=&quot;333&quot; height=&quot;263&quot;&gt;&lt;/a&gt;&amp;nbsp;&lt;/p&gt; &lt;p&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgzuUH_siLi5iH5E8gxz3V4REJBdUAaUTL1eoU0kl3r8cywCvZMfMz8nxpRu1aidXCKmbr_I9yfTxwp-AjSS6x7c7WCLx3Cml9-kiV3I21nXEm7yUiUs4ONeDFYil7xz5qYuC6TUmg2ZQ/s1600-h/Setup_2013-06-24_14-27-34%25255B3%25255D.png&quot;&gt;&lt;img style=&quot;background-image: none; border-right-width: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px&quot; title=&quot;Setup_2013-06-24_14-27-34&quot; border=&quot;0&quot; alt=&quot;Setup_2013-06-24_14-27-34&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEh2eU_wTscgEsDIgVGcCyd_TlC4rU4kDGWFhy-YjR8H8_sXpLX7bI0hdTldP9NHetg9ahFUjD3IHnLh5UBw1oJWcLI_RCGH2BZof7Q707BelMxWmnKwQWLPXJw7QyjSqY-Wnng9suQ8ZA/?imgmax=800&quot; width=&quot;336&quot; height=&quot;265&quot;&gt;&lt;/a&gt;&lt;/p&gt; &lt;p&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjfQ1C0uoUlKqWBTtu0XtwJSZg2BA0sbiVDYplzySPS6v7alj70ixWTfgjv38CE6Iin_IG3WIURUob1AGxhxfJJE6k5WQoakz0-i1FMFaHi0n1mMSUXB-oTEdQbQyXhNx96KhboWWs4aQ/s1600-h/Setup_2013-06-24_14-27-36%25255B3%25255D.png&quot;&gt;&lt;img style=&quot;background-image: none; border-right-width: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px&quot; title=&quot;Setup_2013-06-24_14-27-36&quot; border=&quot;0&quot; alt=&quot;Setup_2013-06-24_14-27-36&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjEEnkqrVIXj10-j1oBiMS_ltqHEHFwGs2Fm5aqd1d_nMDDdK1zDJwC_pzfokwPF4dOHY_m1JPimkm-I5wQcffdldyKLIiDw_uDFA-mkHt3XfG7ob2WIFG3o1R_Y3McFM2HPb1cd_8lIQ/?imgmax=800&quot; width=&quot;341&quot; height=&quot;269&quot;&gt;&lt;/a&gt;&lt;/p&gt; &lt;p&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjMaNQN5CypT2K0WtVU5thI1z2fzfL32sFV9GGQYd1UxRkFyj7-a8XH5ksV0NmbOFOb3GuggZITpFpLATSPpwb2SDXZyosW3DIqJoIqeDvPQ02GHEOCCfGjO5oWCiZua5u1p1K0bn3xkQ/s1600-h/Setup_2013-06-24_14-27-41%25255B3%25255D.png&quot;&gt;&lt;img style=&quot;background-image: none; border-right-width: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px&quot; title=&quot;Setup_2013-06-24_14-27-41&quot; border=&quot;0&quot; alt=&quot;Setup_2013-06-24_14-27-41&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiqS1NlZzh9hxD5d5ubcYD8G-bAPWDHeJZbAJmNBYChm8exgLXlaMA5bAFV7rghUtWQDncDJPoURDAD0ZEVbRfxec63aYdiq_cnNmcKo6RqJ3PfCKX0ktxrc041emlaD5yXcKBTcyDXDA/?imgmax=800&quot; width=&quot;341&quot; height=&quot;269&quot;&gt;&lt;/a&gt;&lt;/p&gt; &lt;p&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhVQKMa49jg-EUO0NPXG8PO3YiuOlwtbnMiQtl7aeuumY1YUT0_XEwCC62md1YG-N4Oc8Gh-YDyX3ebyqzSR_j0wtBT7Mj63qwr5TzHaskn_78r5wD5bFAWlCErtfiv7elHx2gpD2i5Rg/s1600-h/Setup_2013-06-24_14-30-25%25255B3%25255D.png&quot;&gt;&lt;img style=&quot;background-image: none; border-right-width: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px&quot; title=&quot;Setup_2013-06-24_14-30-25&quot; border=&quot;0&quot; alt=&quot;Setup_2013-06-24_14-30-25&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjA4Qh10hyS2TGXadpsulVm0S1QVWHOoI7Owj5ltyBU3vxMQXjnTgr9kP2SoAsBfLKkQE1QpCusau0XGm9OUtqZ7hc5zBRIADb0UV7KnbMHTsfmBE4ZSDX1-5IWYyM6n6cA21HUwR9wSg/?imgmax=800&quot; width=&quot;344&quot; height=&quot;272&quot;&gt;&lt;/a&gt;&lt;/p&gt; &lt;p&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjbXhOSDKcNHJn1EEV8Q4MG-LZRhaNwnG2TcDvqInCvpozAQHilyHmrftkWTI0Hn2-E2eNwdqOdKrWWC2hyK8K8JItbFiEogHvd8OFPY4tTSlvZrjZfOhVAVn73KqsHQtdFkakMwE_1FQ/s1600-h/Setup_2013-06-24_14-30-37%25255B3%25255D.png&quot;&gt;&lt;img style=&quot;background-image: none; border-right-width: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px&quot; title=&quot;Setup_2013-06-24_14-30-37&quot; border=&quot;0&quot; alt=&quot;Setup_2013-06-24_14-30-37&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjSEQFV2AvlQmjrcYOuvcRn9_J3moXHp00fpF8X92O0Doh0oVHDAJq0OV7oAhwhARmQT5XXF4nR-G65tT33gljn0bVKx4GCGML-tf8STUclW00A785hxpXxl9fpP0O1IgdfcJH6vYzKsg/?imgmax=800&quot; width=&quot;346&quot; height=&quot;273&quot;&gt;&lt;/a&gt;&lt;/p&gt; &lt;p&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjNI8Ws5DAoYmXmC5f3aLHQc8SNJnip65-C8PFSqxZ2ErdSiDriNufXUOnzq6W11ql4gDBhw4YSoL1woWT1cIAQXEo3RjDrElb9uDV3pNlpcaz2MBZY5B6ufU_dGxY40AV1y6-j5BamJw/s1600-h/Setup_2013-06-24_14-30-42%25255B3%25255D.png&quot;&gt;&lt;img style=&quot;background-image: none; border-right-width: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px&quot; title=&quot;Setup_2013-06-24_14-30-42&quot; border=&quot;0&quot; alt=&quot;Setup_2013-06-24_14-30-42&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjlgdOXg50YBydUpxLorZp0AgVhilbwolGDGXF6ckxzZH3_qgEiIqrqY13vNMSQtMpakVyqD-Dt_bLJd9mdWMEi1mZbmQUgv3tne8PAZsrh8vy2SKkftKrhRN1spWpSc2n9Fezx2n6NjQ/?imgmax=800&quot; width=&quot;350&quot; height=&quot;276&quot;&gt;&lt;/a&gt;&lt;/p&gt; &lt;p&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjDCjRfQTe3VpiIp6Z8ueBsjGghC-w1WSiOw4PomtEkweJovhMzEJEqD5_ZkIDUL9zFGaUNvU3o1nIGRL1RytOx2RLqNjtAKT3D8rT1d-Z-L92MXfWC_VZcWh9PIWBmbo_gUWgB8mwOJA/s1600-h/Setup_2013-06-24_14-30-47%25255B3%25255D.png&quot;&gt;&lt;img style=&quot;background-image: none; border-right-width: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px&quot; title=&quot;Setup_2013-06-24_14-30-47&quot; border=&quot;0&quot; alt=&quot;Setup_2013-06-24_14-30-47&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjG6jl6ayzGFdV-UfKfUasbcl9_HNef4z6ypnwkFmI-kUGiH4CKtKhg4iQN1XdBHZp-dXZXH6BZFx-KlbQd9E5cLgxnKYIFMSAqMn8jraBwUd39R_5YvTYcQDOlrkje5fV2BSEj76XW5w/?imgmax=800&quot; width=&quot;349&quot; height=&quot;276&quot;&gt;&lt;/a&gt;&lt;/p&gt; &lt;p&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhO89vD4ZBLFFU4ml_zmiUAxuQDAyov1mcSRwfE8odVICkzyT5k0pcRbDRT2w0SKZgzPW0EB-W5A-ZgdHY2fi6NeC8gXBHLqwY1_oeIGuf9aNmz1QtYjBF0LDEuAZt5dDaWu2DgHkNf1Q/s1600-h/Setup_2013-06-24_14-30-53%25255B3%25255D.png&quot;&gt;&lt;img style=&quot;background-image: none; border-right-width: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px&quot; title=&quot;Setup_2013-06-24_14-30-53&quot; border=&quot;0&quot; alt=&quot;Setup_2013-06-24_14-30-53&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjEZ66KYTjKV1sW7s2ZWJMYUlQjv1T6wzx453Y6c9iwxy_GfrE-ghFi_gYCB5_C-kXF1iXTDefA6y1mT5pnyX02HDEy-31mDBnGR_9ItQrfv27srzqqLHB5IZMwW0WcWQ9N4eV6eM6qEQ/?imgmax=800&quot; width=&quot;354&quot; height=&quot;280&quot;&gt;&lt;/a&gt;&lt;/p&gt; &lt;p&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhVdyVhvv2AIjnY9jJQR0c6hFVdeckv0nWet9Yof6VuQiofnRRlh8GQsp_EjeJ1DtTNYQ_qresuOp4vqJw8Ax61gGhsxDSb_nJMo0heYHH9M1VBZgfJwD2gQwjfVH65lAQsBgVNHlT-cQ/s1600-h/Setup_2013-06-24_14-31-12%25255B3%25255D.png&quot;&gt;&lt;img style=&quot;background-image: none; border-right-width: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px&quot; title=&quot;Setup_2013-06-24_14-31-12&quot; border=&quot;0&quot; alt=&quot;Setup_2013-06-24_14-31-12&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhOlqd-tpbE-Xo1jj2eEW0V4sawrlb1TP3t6eX4VeYsI4BQamMEk-XP0Wp3SLV9stgHTIEuLAmns1HDo3EqJHq0KjZA90t9S82MStLsONXwqWcS7Ct13bJexLJUIrePCBoV1TFF4-hzLQ/?imgmax=800&quot; width=&quot;354&quot; height=&quot;280&quot;&gt;&lt;/a&gt;&lt;/p&gt; &lt;p&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgw7XeSFd7HHb4vET1ID2xpkWbC4MTyXfn-IwASTrMa2VtUWHtT-nHuVLgkYz2pO35rkBFOrCLCdoNu-fBSryCVyPxKSuktAzk1JU45tBYuJIQiZTNHRZAP2uCvYudnD9w8CQQy9a5Eqg/s1600-h/Stack%252520Builder%2525203.1.0_2013-06-24_14-31-19%25255B3%25255D.png&quot;&gt;&lt;img style=&quot;background-image: none; border-right-width: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px&quot; title=&quot;Stack Builder 3.1.0_2013-06-24_14-31-19&quot; border=&quot;0&quot; alt=&quot;Stack Builder 3.1.0_2013-06-24_14-31-19&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiUd7OLYcdW5FmTPZAj3AV8y0u_hSywiqLTLkNNm_WvBKzChrbrJNwxzqInWp7gvXG2MJkzlag2lUAOYKMWbiO6SzoBbsbw3XqBVb5bhSBD1Q-DY1_-bFQVTulKLjtHqHD-3wbG1RER8Q/?imgmax=800&quot; width=&quot;360&quot; height=&quot;250&quot;&gt;&lt;/a&gt;&lt;/p&gt; &lt;h3&gt;Starting with PostgreSQL&lt;/h3&gt; &lt;p&gt;To get started, open &lt;em&gt;&lt;strong&gt;pgAdmin III&lt;/strong&gt;&lt;/em&gt; from your start menu. On the left hand side right-click on your server instance and click &lt;em&gt;Connect&lt;/em&gt;&lt;/p&gt; &lt;p&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEi1ln6042HuoZJjqS0uwseZmK0Pwz1ksV5vUHFZtyFJqhaFf4y-WDG1qQVvE4HtnvfRQKqEOWzDgLMeq0ezdEptByvBYf5bvlhS1pxVlg5tmcwFXY_qMSfraB8t47Y6igU-hep92wLb_w/s1600-h/pgAdmin%252520III_2013-06-24_15-08-22%25255B3%25255D.png&quot;&gt;&lt;img style=&quot;background-image: none; border-right-width: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px&quot; title=&quot;pgAdmin III_2013-06-24_15-08-22&quot; border=&quot;0&quot; alt=&quot;pgAdmin III_2013-06-24_15-08-22&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjIUR76YAGD7hX92cdznvz4VpDzuiLsmR4A5SPk5qwlXyQ0QeaSJm7Twf6f3b8doqTTL1CoS7kmVUKDwvNCFyOHJPxZVmEweN2bYzzbfH0REY8aQsgO-0rYcAZuPQDNDBHs2-eDHbvkow/?imgmax=800&quot; width=&quot;325&quot; height=&quot;306&quot;&gt;&lt;/a&gt;&amp;nbsp;&lt;/p&gt; &lt;p&gt;enter the password you used in the setup &lt;/p&gt; &lt;p&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjHgcWY_l8bt70Q2bhC23IPjjgUxSWw136kjquZ1fisWNQOVQxhRjEQAQcF3X_7Q_aGbPKmaYKef1rrqNJkgNx8QAawGfM83VOJHVTb28VgZFGWH_8aZO19yaLSanCtyUFcE12mkawrzQ/s1600-h/Connect%252520to%252520Server_2013-06-24_15-08-43%25255B6%25255D.png&quot;&gt;&lt;img style=&quot;background-image: none; border-right-width: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px&quot; title=&quot;Connect to Server_2013-06-24_15-08-43&quot; border=&quot;0&quot; alt=&quot;Connect to Server_2013-06-24_15-08-43&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEj0REUTUCfpI3dORXaSth8ayn0l7vogfP5AbUHBhpQra29QKt2pEXx46cFjezYowxfpGgRHeIaeQNGBHGnOjZQmpxFNQNlJyPhoTWXV9kk9LQrpnmYCi4b4mlDI6oviNqGu1RsZG960uQ/?imgmax=800&quot; width=&quot;285&quot; height=&quot;163&quot;&gt;&lt;/a&gt;&lt;/p&gt; &lt;p&gt;Once you connected to your server, you can right click on the databases node and click &lt;em&gt;New Database&lt;/em&gt;&lt;/p&gt; &lt;p&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEggGs1hpEYrhN7oA79l2MBfmjBKILZCUofD-mWCycAoj2sT8unAC4OLhjbDhbpMYLtXYHXzzHHze7W9Nc666W9fOFNKh-HNZq9nPNB4UZiMpgXFPeunkjPZvQVFzxXlXKnsr_9rxhksfQ/s1600-h/pgAdmin%252520III_2013-06-24_15-09-33%25255B3%25255D.png&quot;&gt;&lt;img style=&quot;background-image: none; border-right-width: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px&quot; title=&quot;pgAdmin III_2013-06-24_15-09-33&quot; border=&quot;0&quot; alt=&quot;pgAdmin III_2013-06-24_15-09-33&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjv61Q0bZ8k9wyvyDdACfdzZgpKzCUbHOnIyn-K0mNcLTaFIXqLc9Qimz6LFIGjiSuYkDZwLBCde9rzHXas3QME68IR1peuunhQlF-lem2gX4X77kbhVknjfAzD3IByzQbgJWvrkIW6JQ/?imgmax=800&quot; width=&quot;335&quot; height=&quot;335&quot;&gt;&lt;/a&gt;&lt;/p&gt; &lt;p&gt;we going to create a simple database called &lt;em&gt;book&lt;/em&gt; with the default settings&lt;/p&gt; &lt;p&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjbloJ5bxdbZN_zTiVW95B37hx1XBuTFTt0gjzOeZzE3IuZKk3gjixRiCRc0Dr8bIiFTQ5V4IVMxsSv8cIWV0ZQG3dKk3-YUrxAPDGMsSW8RyDj9uL9EpMN73whjbZttLY1QOFzw_vXZQ/s1600-h/New%252520Database..._2013-06-24_16-45-31%25255B3%25255D.png&quot;&gt;&lt;img style=&quot;background-image: none; border-right-width: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px&quot; title=&quot;New Database..._2013-06-24_16-45-31&quot; border=&quot;0&quot; alt=&quot;New Database..._2013-06-24_16-45-31&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiWfyICaUIps6rzOLeOz1cZVbHerxJKK6CfA80MUkFFCgOE82qQnd8yageBeYU9MceVjCggY8C8j8lIhVDAzEtrux8DDxKgYKx2PJKk41BXmydgcRTux8Zauo02O_7C4YNnzI5F5z_wZg/?imgmax=800&quot; width=&quot;338&quot; height=&quot;355&quot;&gt;&lt;/a&gt;&lt;/p&gt; &lt;p&gt;to start writing queries, you could open &lt;em&gt;Tools&lt;/em&gt; menu, then click &lt;em&gt;Query Tool &lt;/em&gt;(or press CTRL + E).&lt;/p&gt; &lt;h3&gt;Working with Tables&lt;/h3&gt; &lt;p&gt;Creating a table consists of giving it a name and a list of columns with types&lt;br&gt;and (optional) constraint information. Each table should also nominate a&lt;br&gt;unique identifier column to pinpoint specific rows. That identifier is called a&lt;br&gt;PRIMARY KEY. The SQL to create a countries table looks like this:&lt;/p&gt;&lt;pre class=&quot;prettyprint lang-sql&quot;&gt;CREATE TABLE countries (country_code char(2) PRIMARY KEY,country_name text UNIQUE);&lt;br /&gt;&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;p&gt;copy and paste this code in the Query Tool and click &lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhiMpSO8ySYAidXj4ckezmLdc8hWsp4anameXu0yLs0RU0LrKypbRAiB_pmEw6Ft60lMdXDXTb__AVh0JU_6M-RwkCzu_-jFkSTo9nOtXMPHC54XE8PyhbC3H7Z7PoW9GIAPCAe8tyzDA/s1600-h/Query%252520-%252520book%252520on%252520postgres%252540localhost5432%252520_2013-06-24_16-54-24%25255B2%25255D.png&quot;&gt;&lt;img style=&quot;background-image: none; border-right-width: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px&quot; title=&quot;Query - book on postgres@localhost5432 _2013-06-24_16-54-24&quot; border=&quot;0&quot; alt=&quot;Query - book on postgres@localhost5432 _2013-06-24_16-54-24&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiOSpOHBncGOon6aohDW06JJSeBjC3Q8Oycq4Q20ZzX-MkQ4S3UZtMtYqBapE4E8niMiH2Anb5G-f5z6FQhGdwSkFFT8S4FTyOIVfr-CQ-iPmJgCvMZEK5IvwSOi1norGSJ9aG7dW5jdg/?imgmax=800&quot; width=&quot;81&quot; height=&quot;59&quot;&gt;&lt;/a&gt; on the toolbar to run it.&lt;/p&gt;&lt;br /&gt;&lt;p&gt;To insert values in our countries table:&lt;/p&gt;&lt;pre class=&quot;prettyprint lang-sql&quot;&gt;INSERT INTO countries (country_code, country_name)&lt;br /&gt;VALUES (&#39;us&#39;,&#39;United States&#39;), (&#39;mx&#39;,&#39;Mexico&#39;), (&#39;au&#39;,&#39;Australia&#39;),&lt;br /&gt;(&#39;uk&#39;,&#39;United Kingdom&#39;), (&#39;de&#39;,&#39;Germany&#39;), (&#39;ll&#39;,&#39;Loompaland&#39;);&lt;br /&gt;&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;p&gt;To select from our table:&lt;/p&gt;&lt;pre class=&quot;prettyprint lang-sql&quot;&gt;SELECT * FROM countries;&lt;br /&gt;&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;p&gt;To delete :&lt;/p&gt;&lt;pre class=&quot;prettyprint lang-sql&quot;&gt;DELETE FROM countries&lt;br /&gt;WHERE country_code = &#39;ll&#39;;&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;p&gt;Now, let’s add a cities table. To ensure any inserted country_code also exists in our countries table, we add the REFERENCES keyword. Since the country_code column references another table’s key, it’s known as the foreign key constraint. &lt;/p&gt;&lt;pre class=&quot;prettyprint lang-sql&quot;&gt;CREATE TABLE cities (&lt;br /&gt;name text NOT NULL,&lt;br /&gt;postal_code varchar(9) CHECK (postal_code &amp;lt;&amp;gt; &#39;&#39;),&lt;br /&gt;country_code char(2) REFERENCES countries,&lt;br /&gt;PRIMARY KEY (country_code, postal_code)&lt;br /&gt;);&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;p&gt;we constrained the name in cities by disallowing NULL values. We constrained postal_code by checking that no values are empty strings (&amp;lt;&amp;gt; means not equal). Furthermore, since a PRIMARY KEY uniquely identifies a row, we created a compound key: country_code + postal_code. Together, they uniquely define a row. now if you try to run this code you will get an error because we violating referential integrity: &lt;/p&gt;&lt;pre class=&quot;prettyprint lang-sql&quot;&gt;INSERT INTO cities&lt;br /&gt;VALUES (&#39;Toronto&#39;,&#39;M4C1B5&#39;,&#39;ca&#39;);&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;p&gt;To update records:&lt;/p&gt;&lt;pre class=&quot;prettyprint lang-sql&quot;&gt;INSERT INTO cities&lt;br /&gt;VALUES (&#39;Portland&#39;,&#39;87200&#39;,&#39;us&#39;);&lt;br /&gt;UPDATE cities&lt;br /&gt;SET postal_code = &#39;97205&#39;&lt;br /&gt;WHERE name = &#39;Portland&#39;;&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;h3&gt;Inner Join&lt;/h3&gt;&lt;br /&gt;&lt;p&gt;Being a relational database gives PostgreSQL the ability to join tables together when reading them. Joining, in essence, is an operation taking two separate tables and combining them in some way to return a single table. It’s somewhat like shuffling up Scrabble pieces from existing words to make new words. The basic form of a join is the inner join. In the simplest form, you specify two columns (one from each table) to match by, using the ON keyword.&lt;/p&gt;&lt;pre class=&quot;prettyprint lang-sql&quot;&gt;SELECT cities.*, country_name&lt;br /&gt;FROM cities INNER JOIN countries&lt;br /&gt;ON cities.country_code = countries.country_code;&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;p&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhowPfd7rt82E5b14jf-3j-R9L1GXYU78WOG4QLCJsdYTMpp-uj6seuYOUmo5upr9sQD05T4VKboOFsGu0lrT3LctE7nd-yUNtOiRiIpJ0UGTI97hdLH5bi2O8BwktzG4X2uFMc6qCDCA/s1600-h/Query%252520-%252520book%252520on%252520postgres%252540localhost5432%252520_2013-06-25_09-07-07%25255B3%25255D.png&quot;&gt;&lt;img style=&quot;background-image: none; border-right-width: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px&quot; title=&quot;Query - book on postgres@localhost5432 _2013-06-25_09-07-07&quot; border=&quot;0&quot; alt=&quot;Query - book on postgres@localhost5432 _2013-06-25_09-07-07&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjuoTx-0s2R0e-Zl3elXFmPdvuRAi22bPbfg5lPPfq1lM_CAHB5C9HBDfV01tYK9RB1vTHFRlOAH-Ievz-csB6gELrTiiFG9n0uXHKrSSjQTTiqlzoeS5LYG9tS6iNe5AfhyphenhyphentvjG2tGjQ/?imgmax=800&quot; width=&quot;503&quot; height=&quot;239&quot;&gt;&lt;/a&gt;&lt;/p&gt;&lt;br /&gt;&lt;p&gt;The join returns a single table, sharing all columns’ values of the cities table plus the matching country_name value from the countries table. We can also join a table like cities that has a compound primary key. To test a compound join, let’s create a new table that stores a list of venues. A venue exists in both a postal code and a specific country. The foreign key must be two columns that reference both cities primary key columns. (MATCH FULL is a constraint that ensures either both values exist or both are NULL.)&lt;/p&gt;&lt;pre class=&quot;prettyprint lang-sql&quot;&gt;CREATE TABLE venues (&lt;br /&gt;venue_id SERIAL PRIMARY KEY,&lt;br /&gt;name varchar(255),&lt;br /&gt;street_address text,&lt;br /&gt;type char(7) CHECK ( type in (&#39;public&#39;,&#39;private&#39;) ) DEFAULT &#39;public&#39;,&lt;br /&gt;postal_code varchar(9),&lt;br /&gt;country_code char(2),&lt;br /&gt;FOREIGN KEY (country_code, postal_code)&lt;br /&gt;REFERENCES cities (country_code, postal_code) MATCH FULL&lt;br /&gt;);&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;p&gt;This venue_id column is a common primary key setup: automatically incremented integers (1, 2, 3, 4, and so on…). Creating new row will populate this column automatically. We make this identifier using the SERIAL keyword. CHECK keyword check that a column supplied value against a set of predefined values. DEFAULT provide a default value to be inserted in case user supplied nothing. &lt;/p&gt;&lt;pre class=&quot;prettyprint lang-sql&quot;&gt;INSERT INTO venues (name, postal_code, country_code)&lt;br /&gt;VALUES (&#39;Crystal Ballroom&#39;, &#39;97205&#39;, &#39;us&#39;);&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;p&gt;Joining the venues table with the cities table requires both foreign key columns.&lt;/p&gt;&lt;pre class=&quot;prettyprint lang-sql&quot;&gt;SELECT venues.venue_id, venues.name, cities.name&lt;br /&gt;FROM venues INNER JOIN cities &lt;br /&gt;ON venues.postal_code = cities.postal_code AND venues.country_code = cities.country_code;&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;p&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEi9HNFjXKwlyN5emTRag84m2TC0TZI10Jt98wJeVKHofkb0ezX1dwMjbmsSyHGMoNpYdn0uOXJGQ-IULhx_YRfT9xa474AJuHxeCdooE7OueJYknzsNWHVabIkIHFuc7UOqMjNAOPCbXw/s1600-h/Query%252520-%252520book%252520on%252520postgres%252540localhost5432%252520_2013-06-25_11-03-08%25255B5%25255D.png&quot;&gt;&lt;img style=&quot;background-image: none; border-right-width: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px&quot; title=&quot;Query - book on postgres@localhost5432 _2013-06-25_11-03-08&quot; border=&quot;0&quot; alt=&quot;Query - book on postgres@localhost5432 _2013-06-25_11-03-08&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgNoCf2pP67ZGoVzWWPv1iGPpt-CFvQ781uecx0_jUdywgtVu2a9ZimLv58UKm3rrSdmyaukJkR5et5JS87vJY6CCWlGgjMvT8OEjsrS-ovGx32xA7AKM-idw683HzMVC1NBuHjgWc28w/?imgmax=800&quot; width=&quot;528&quot; height=&quot;174&quot;&gt;&lt;/a&gt;&lt;/p&gt;&lt;br /&gt;&lt;h3&gt;Outer Join&lt;/h3&gt;&lt;br /&gt;&lt;p&gt;Outer joins are a way of merging two tables when the results of one table must always be returned, whether or not any matching column values exist on the other table. Let&#39;s create a table and populate it for testing this:&lt;/p&gt;&lt;pre class=&quot;prettyprint lang-sql&quot;&gt;CREATE TABLE events (&lt;br /&gt;event_id SERIAL PRIMARY KEY,&lt;br /&gt;title varchar(255),&lt;br /&gt;starts timestamp,&lt;br /&gt;ends timestamp,&lt;br /&gt;venue_id integer,&lt;br /&gt;FOREIGN KEY (venue_id)&lt;br /&gt;REFERENCES venues (venue_id) MATCH FULL&lt;br /&gt;);&lt;br /&gt;&lt;br /&gt;INSERT INTO events (title, starts, ends, venue_id)&lt;br /&gt;VALUES (&#39;LARP Club&#39;, &#39;2012-02-15 17:30:00&#39;, &#39;2012-02-15 19:30:00&#39;, 1);&lt;br /&gt;INSERT INTO events (title, starts, ends)&lt;br /&gt;VALUES (&#39;April Fools Day&#39;, &#39;2012-04-01 00:00:00&#39;, &#39;22012-04-01 23:59:00&#39;);&lt;br /&gt;INSERT INTO events (title, starts, ends)&lt;br /&gt;VALUES (&#39;Christmas Day&#39;, &#39;2012-12-25 00:00:00&#39;, &#39;2012-04-01 23:59:00&#39;);&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;p&gt;Now the results of the following two queries showing you the difference between INNER JOIN and OUTER JOIN.&lt;/p&gt;&lt;pre class=&quot;prettyprint lang-sql&quot;&gt;SELECT events.title, venues.name&lt;br /&gt;FROM events JOIN venues&lt;br /&gt;ON events.venue_id = venues.venue_id;&lt;br /&gt;&lt;br /&gt;SELECT events.title, venues.name&lt;br /&gt;FROM events LEFT JOIN venues&lt;br /&gt;ON events.venue_id = venues.venue_id;&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;p&gt;Finally, there’s the FULL JOIN, which is the union of LEFT and RIGHT; you’re guaranteed all values from each table, joined wherever columns match. &lt;/p&gt;&lt;br /&gt;&lt;h3&gt;Indexes &lt;/h3&gt;&lt;br /&gt;&lt;p&gt;RDBMSs uses indexes to reducing disk reads and query optimization (among other things). If we select the title of Christmas Day from the events table, the algorithm must scan every row for a match to return. Without an index, each row must be read from disk to know whether a query should return it. An index is a special data structure built to avoid a full table scan when performing a query. PostgreSQL (like any other RDBMS) automatically creates an index on the primary key, where the key is the primary key value and where the value points to a row on disk. Using the UNIQUE keyword is another way to force an index on a table column. PostgreSQL also creates indexes for columns targeted by FOREIGN KEY constraint.&lt;/p&gt;&lt;br /&gt;&lt;p&gt;You can explicitly add a hash index using the CREATE INDEX command, where each value must be unique. &lt;em&gt;btree&lt;/em&gt; is the suitable data structure for ranges. For more information, refer to &lt;a href=&quot;http://www.postgresql.org/docs/9.1/static/sql-createindex.html&quot; target=&quot;_blank&quot;&gt;online documentation&lt;/a&gt;.&lt;/p&gt;&lt;pre class=&quot;prettyprint lang-sql&quot;&gt;CREATE INDEX events_starts&lt;br /&gt;ON events USING btree (starts);&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;h3&gt;Aggregate Functions&lt;/h3&gt;&lt;br /&gt;&lt;p&gt;An aggregate query groups results from several rows by some common criteria. It can be as simple as counting the number of rows in a table or calculating the average of some numerical column. Examples:&lt;/p&gt;&lt;pre class=&quot;prettyprint lang-sql&quot;&gt;SELECT count(title)&lt;br /&gt;FROM events&lt;br /&gt;&lt;br /&gt;SELECT min(starts), max(ends)&lt;br /&gt;FROM events&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;p&gt;Aggregate functions are useful but limited on their own. If we wanted to count all events at each venue, we could write the following for each venue ID (which is tedious): &lt;/p&gt;&lt;pre class=&quot;prettyprint lang-sql&quot;&gt;SELECT count(*) FROM events WHERE venue_id = 1;&lt;br /&gt;SELECT count(*) FROM events WHERE venue_id = 2;&lt;br /&gt;SELECT count(*) FROM events WHERE venue_id = 3;&lt;br /&gt;SELECT count(*) FROM events WHERE venue_id IS NULL;&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;h3&gt;Grouping&lt;/h3&gt;&lt;br /&gt;&lt;p&gt;With GROUP BY, you tell Postgres to place the rows into groups and then perform some aggregate function (such as count()) on those groups.&lt;/p&gt;&lt;pre class=&quot;prettyprint lang-sql&quot;&gt;SELECT venue_id, count(*)&lt;br /&gt;FROM events&lt;br /&gt;GROUP BY venue_id;&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;p&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEh3Kc6EYsgQgZvyM04VCVv2Kmw1akzoSuAnxAnPqYXA0SR3eWP5X3Y_moJwAobl8TmMUedq5Usj7csGxMZc4fzk_wr8VDxCyWnh2H_K-19x7jgF3oJbhSXHzo6Y6Szw2_Y2GR3_OkrzsA/s1600-h/Query%252520-%252520book%252520on%252520postgres%252540localhost5432%252520_2013-06-25_13-49-47%25255B3%25255D.png&quot;&gt;&lt;img style=&quot;background-image: none; border-right-width: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px&quot; title=&quot;Query - book on postgres@localhost5432 _2013-06-25_13-49-47&quot; border=&quot;0&quot; alt=&quot;Query - book on postgres@localhost5432 _2013-06-25_13-49-47&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhfT24gH8VvOU6re6U8GYi_gjha0yA3rFIOzaXU-KiJ4Pra8DxOd93oQ0XwJtv_Y3Mdkb4rE407eIv8SBPaZHW16nymb-HHsX2NxNR7Byc8a8us9jSCy72VTDzJntd-5avXHeGty1lGfA/?imgmax=800&quot; width=&quot;265&quot; height=&quot;101&quot;&gt;&lt;/a&gt;&lt;/p&gt;&lt;br /&gt;&lt;p&gt;The GROUP BY condition has its own filter keyword: HAVING. HAVING is like the WHERE clause, except it can filter by aggregate functions (whereas WHERE cannot). &lt;/p&gt;&lt;pre class=&quot;prettyprint lang-sql&quot;&gt;SELECT venue_id&lt;br /&gt;FROM events&lt;br /&gt;GROUP BY venue_id&lt;br /&gt;HAVING count(*) = 1;&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;p&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhcdv4hJQ140tSDQ6A_hKaDJEAujFy8lZ7CwTDnVXVU6R11bla4e40UIjlrw4zxaY-cSL-OSJQ7UlUaF3zLWS59uV0i_gMUjkERoKu_s2Mu8Ws2CsH4aMYlUHGbu9XxXIE8UewrJ_o4ew/s1600-h/Query%252520-%252520book%252520on%252520postgres%252540localhost5432%252520_2013-06-25_13-50-56%25255B2%25255D.png&quot;&gt;&lt;img style=&quot;background-image: none; border-right-width: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px&quot; title=&quot;Query - book on postgres@localhost5432 _2013-06-25_13-50-56&quot; border=&quot;0&quot; alt=&quot;Query - book on postgres@localhost5432 _2013-06-25_13-50-56&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEglndaMdqiFOF3V77UeultaDHDOS2NvdWrsfdL3FS6Y4yCqcpp6JJJyIr2bjNMzgNGLubWHCJTktgivrSwO55MM5vZJuQZ8F10utu4KPm6n_t00Re3lKV_YnDot9w_MJ7O66biK-r0KnQ/?imgmax=800&quot; width=&quot;108&quot; height=&quot;59&quot;&gt;&lt;/a&gt;&lt;/p&gt;&lt;br /&gt;&lt;p&gt;You can use GROUP BY without any aggregate functions. If you SELECT one column, you get all unique values.&lt;br&gt;SELECT venue_id FROM events GROUP BY venue_id;&lt;br&gt;This kind of grouping is so common that SQL has a shortcut in the DISTINCT keyword.&lt;br&gt;SELECT DISTINCT venue_id FROM events;&lt;br&gt;The results of both queries will be identical.&lt;/p&gt;&lt;br /&gt;&lt;h3&gt;Window Functions&lt;/h3&gt;&lt;br /&gt;&lt;p&gt;Window functions are similar to GROUP BY queries in that they allow you to run aggregate functions across multiple rows. The difference is that they allow you to use built-in aggregate functions without requiring every single field to be grouped to a single row. If we attempt to select the title column without grouping by it, we can expect an error.&lt;/p&gt;&lt;br /&gt;&lt;p&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEi9zXSdVPo6QEZWQgG4BI__rZuGwPsnByFNeBCU0sdfnQflQEGDWyvbhPauwSZIrcf6Xw1tx9-o58E2op5FamZsG-SMi-WEVUXKK7FMTvdKCN0Yv9ttxXBlJbwfWsm-mdQlTpbKVrjcbw/s1600-h/Query%252520-%252520book%252520on%252520postgres%252540localhost5432%252520_2013-06-25_14-10-42%25255B3%25255D.png&quot;&gt;&lt;img style=&quot;background-image: none; border-right-width: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px&quot; title=&quot;Query - book on postgres@localhost5432 _2013-06-25_14-10-42&quot; border=&quot;0&quot; alt=&quot;Query - book on postgres@localhost5432 _2013-06-25_14-10-42&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiKH9a7eBX6s0D9h9JasaiyEkMbJE9SXSZYwTtJAulYD-_hKe-XuwZLkPxZwoU4YsGn9yyblGDy85HCoE7xsKDJNdLwqNbNFWPt7EABmRWxehV43KHOh34dQUG10qergL8bcC8g28_5Xg/?imgmax=800&quot; width=&quot;465&quot; height=&quot;181&quot;&gt;&lt;/a&gt;&lt;/p&gt;&lt;br /&gt;&lt;p&gt;We are counting up the rows by venue_id, and in the case of LARP Club and Wedding, we have two titles for a single venue_id. Postgres doesn’t know which title to display. Whereas a GROUP BY clause will return one record per matching group value, a window function can return a separate record for each row. Window functions return all matches and replicate the results of any aggregate function. It returns the results of an aggregate function OVER a PARTI TI ON of the result set.&lt;/p&gt;&lt;br /&gt;&lt;p&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjHcG_J59nC6rWXkpNZCWr1mXw2v8ePqC9qz_YN21yCgEEt47P4AuUdziEOw8WsNEaLDCtaG7h4zfSRTnYaMYNtYaVKwZxHENP6rNxuaWQBxu0sHFBGAz2dZDuFwb86zzcL9yFxKQB4mg/s1600-h/Query%252520-%252520book%252520on%252520postgres%252540localhost5432%252520_2013-06-25_14-17-36%25255B3%25255D.png&quot;&gt;&lt;img style=&quot;background-image: none; border-right-width: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px&quot; title=&quot;Query - book on postgres@localhost5432 _2013-06-25_14-17-36&quot; border=&quot;0&quot; alt=&quot;Query - book on postgres@localhost5432 _2013-06-25_14-17-36&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgKWmTkxg1XfYJJzUn7gO8mYKDenwk_Gbl9zBFdekwlnfG9OhE_WkgqV2bZ0WkahaAvO8jGCOKUOZdXmXr6MvGxfgOd8-GwQwg6106Lwle4TXT9U7jIhFPSgPh1ad0GPHxArlVN4eceTQ/?imgmax=800&quot; width=&quot;460&quot; height=&quot;196&quot;&gt;&lt;/a&gt;&lt;/p&gt;&lt;br /&gt;&lt;h3&gt;Transactions&lt;/h3&gt;&lt;br /&gt;&lt;p&gt;Transactions ensure that every command of a set is executed. If anything fails along the way, all of the commands are rolled back like they never happened. It’s the &lt;em&gt;all or nothing&lt;/em&gt; motto that gives relational databases its consistency capability.&lt;/p&gt;&lt;br /&gt;&lt;p&gt;PostgreSQL transactions follow ACID compliance, which stands for &lt;strong&gt;A&lt;/strong&gt;tomic (all ops succeed or none do), &lt;strong&gt;C&lt;/strong&gt;onsistent (the data will always be in a good state—no inconsistent states), &lt;strong&gt;I&lt;/strong&gt;solated (transactions don’t interfere), and &lt;strong&gt;D&lt;/strong&gt;urable (a committed transaction is safe, even after a server crash). Transactions are useful when you’re modifying two tables that you don’t want out of sync.&lt;/p&gt;&lt;br /&gt;&lt;p&gt;We can wrap any transaction within a BEGIN TRANSACTION block. To verify atomicity, we’ll kill the transaction with the ROLLBACK command.&lt;/p&gt;&lt;br /&gt;&lt;h3&gt;Stored Procedures&lt;/h3&gt;&lt;br /&gt;&lt;p&gt;Every command we’ve seen until now has been declarative (executed on the client side), but you can execute code on the database side also. Example of a stored procedure and how to run it:&lt;/p&gt;&lt;pre class=&quot;prettyprint lang-sql&quot;&gt;CREATE OR REPLACE FUNCTION add_event( title text, starts timestamp,&lt;br /&gt;ends timestamp, venue text, postal varchar(9), country char(2) )&lt;br /&gt;RETURNS boolean AS $$&lt;br /&gt;DECLARE&lt;br /&gt;did_insert boolean := false;&lt;br /&gt;found_count integer;&lt;br /&gt;the_venue_id integer;&lt;br /&gt;BEGIN&lt;br /&gt;SELECT venue_id INTO the_venue_id&lt;br /&gt;FROM venues v&lt;br /&gt;WHERE v.postal_code=postal AND v.country_code=country AND v.name ILIKE venue&lt;br /&gt;LIMIT 1;&lt;br /&gt;IF the_venue_id IS NULL THEN&lt;br /&gt;INSERT INTO venues (name, postal_code, country_code)&lt;br /&gt;VALUES (venue, postal, country)&lt;br /&gt;RETURNING venue_id INTO the_venue_id;&lt;br /&gt;did_insert := true;&lt;br /&gt;END IF;&lt;br /&gt;-- Note: not an “error”, as in some programming languages&lt;br /&gt;RAISE NOTICE &#39;Venue found %&#39;, the_venue_id;&lt;br /&gt;INSERT INTO events (title, starts, ends, venue_id)&lt;br /&gt;VALUES (title, starts, ends, the_venue_id);&lt;br /&gt;RETURN did_insert;&lt;br /&gt;END;&lt;br /&gt;$$ LANGUAGE plpgsql;&lt;br /&gt;&lt;br /&gt;SELECT add_event(&#39;House Party&#39;, &#39;2012-05-03 23:00&#39;,&lt;br /&gt;&#39;2012-05-04 02:00&#39;, &#39;Run&#39;&#39;s House&#39;, &#39;97205&#39;, &#39;us&#39;);&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;h3&gt;Triggers&lt;/h3&gt;&lt;br /&gt;&lt;p&gt;Triggers automatically fire stored procedures when some event happens, like an insert or update. They allow the database to enforce some required behavior in response to changing data. &lt;/p&gt;&lt;br /&gt;&lt;p&gt;Let&#39;s create a function that logs any event changes into logs table. First we create the table&lt;/p&gt;&lt;pre class=&quot;prettyprint lang-sql&quot;&gt;CREATE TABLE logs (&lt;br /&gt;event_id integer,&lt;br /&gt;old_title varchar(255),&lt;br /&gt;old_starts timestamp,&lt;br /&gt;old_ends timestamp,&lt;br /&gt;logged_at timestamp DEFAULT current_timestamp&lt;br /&gt;);&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;p&gt;Next, we build a function to insert old data into the log. The OLD variable represents the row about to be changed (NEW represents an incoming row, which we’ll see in action soon enough). Output a notice to the console with the event_id before returning. Then we create our trigger to log changes after any row is updated through this function.&lt;/p&gt;&lt;pre class=&quot;prettyprint lang-sql&quot;&gt;CREATE OR REPLACE FUNCTION log_event() RETURNS trigger AS $$&lt;br /&gt;DECLARE&lt;br /&gt;BEGIN&lt;br /&gt;INSERT INTO logs (event_id, old_title, old_starts, old_ends)&lt;br /&gt;VALUES (OLD.event_id, OLD.title, OLD.starts, OLD.ends);&lt;br /&gt;RAISE NOTICE &#39;Someone just changed event #%&#39;, OLD.event_id;&lt;br /&gt;RETURN NEW;&lt;br /&gt;END;&lt;br /&gt;$$ LANGUAGE plpgsql;&lt;br /&gt;&lt;br /&gt;CREATE TRIGGER log_events&lt;br /&gt;AFTER UPDATE ON events&lt;br /&gt;FOR EACH ROW EXECUTE PROCEDURE log_event();&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;p&gt;To test our trigger let&#39;s update an event and see the trigger output:&lt;/p&gt;&lt;br /&gt;&lt;p&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgpIn9h0wn-oVOJ_Tk3hz2zVVgMmboCZhhv3dxAPJWMcaKuu4_oddz43yniHXl2DohUI1B5ZM4-4o-cCfBr2nV3hyphenhyphenoWvzdu1AfRbtpf3uqTuX6YgKZ95RDkX3FxegvPozxdcarFxDtLTQ/s1600-h/Query%252520-%252520book%252520on%252520postgres%252540localhost5432%252520_2013-06-25_15-58-53%25255B3%25255D.png&quot;&gt;&lt;img style=&quot;background-image: none; border-right-width: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px&quot; title=&quot;Query - book on postgres@localhost5432 _2013-06-25_15-58-53&quot; border=&quot;0&quot; alt=&quot;Query - book on postgres@localhost5432 _2013-06-25_15-58-53&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhkjpk2hoecB-y_RfAQ4_dzxdZiOjR2NSM-tpZm5FY6utzD_kxWbpzYU2Age9yVioikwnOVjw8wF1OrIpEy8bNDe3aImF-TYSo6nKka7hWjYGF80CCCUzNm5fpP7W-SNvloyUWu1LeKlw/?imgmax=800&quot; width=&quot;444&quot; height=&quot;171&quot;&gt;&lt;/a&gt;&lt;/p&gt;&lt;br /&gt;&lt;p&gt;and the old event was logged&lt;/p&gt;&lt;br /&gt;&lt;p&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgz1TrcBveQqgOp4XbZYeaW0izcMDE5K1jhucDel9SzQopYQHMO1u1vVG5d1ZsNXTQ7BVj5il-DXrphIjhpjAmg6-XhJzepamD3It0ckGZHf8czw4kIuh3PX-AZupk0yaUHhPVwcjFR6Q/s1600-h/Query%252520-%252520book%252520on%252520postgres%252540localhost5432%252520_2013-06-25_16-00-49%25255B3%25255D.png&quot;&gt;&lt;img style=&quot;background-image: none; border-right-width: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px&quot; title=&quot;Query - book on postgres@localhost5432 _2013-06-25_16-00-49&quot; border=&quot;0&quot; alt=&quot;Query - book on postgres@localhost5432 _2013-06-25_16-00-49&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjau35gduGK9u0f61An_uie_K2IZyqLj1wmlKvbq4GCC8cas7CXTeIbz6tRfL96E9xFZA8PQROZQ-3IvUB3lL-zKItRg9PMEBg7sEwrI4Sp6tYU07v-N5rgB8yyf0BUrmGAz73l-uPINg/?imgmax=800&quot; width=&quot;453&quot; height=&quot;105&quot;&gt;&lt;/a&gt;&lt;/p&gt;&lt;br /&gt;&lt;h3&gt;Views&lt;/h3&gt;&lt;br /&gt;&lt;p&gt;Views are aliased queries that can be queried by its alias like any other table. Creating a view is as simple as writing a query and prefixing it with CREATE VIEW some_view_name AS. Views are good for opening up complex queried data in a simple way. If you want to add a new column to the view, it will have to come from the underlying table.&lt;/p&gt;&lt;pre class=&quot;prettyprint lang-sql&quot;&gt;CREATE VIEW holidays AS&lt;br /&gt;SELECT event_id AS holiday_id, title AS name, starts AS date&lt;br /&gt;FROM events&lt;br /&gt;WHERE title LIKE &#39;%Day%&#39; AND venue_id IS NULL;&lt;br /&gt;&lt;br /&gt;SELECT name, to_char(date, &#39;Month DD, YYYY&#39;) AS date&lt;br /&gt;FROM holidays&lt;br /&gt;WHERE date &amp;lt;= &#39;2012-04-01&#39;;&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;h3&gt;The RULE system&lt;/h3&gt;&lt;br /&gt;&lt;p&gt;The rule system (more precisely speaking, the query rewrite rule system) is totally different from stored procedures and triggers. It modifies queries to take rules into consideration, and then passes the modified query to the query planner for planning and execution. More information can be found &lt;a href=&quot;http://www.postgresql.org/docs/8.2/static/rules.html&quot; target=&quot;_blank&quot;&gt;here&lt;/a&gt;. Example of changing query to allow updating our holidays view:&lt;/p&gt;&lt;pre class=&quot;prettyprint lang-sql&quot;&gt;CREATE RULE update_holidays AS ON UPDATE TO holidays DO INSTEAD&lt;br /&gt;UPDATE events&lt;br /&gt;SET title = NEW.name,&lt;br /&gt;starts = NEW.date&lt;br /&gt;WHERE title = OLD.name;&lt;br /&gt;&lt;br /&gt;UPDATE holidays SET date = &#39;6/25/2013&#39; where name = &#39;Christmas Day&#39;;&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;h3&gt;Crosstab&lt;/h3&gt;&lt;pre&gt;crosstab(text source_sql, text category_sql) &lt;font face=&quot;Arial&quot;&gt;takes two queries to pivot results on one of them on the results of the other. &lt;/font&gt;&lt;/pre&gt;&lt;br /&gt;&lt;ul&gt;&lt;br /&gt;&lt;li&gt;&lt;font face=&quot;Arial&quot;&gt;&lt;em&gt;source_sql&lt;/em&gt; is a SQL statement that produces the source set of data. This statement must return one row_name column, one category column, and one value column. It may also have one or more &quot;extra&quot; columns. The row_name column must be first. The category and value columns must be the last two columns, in that order.&lt;/font&gt; &lt;br /&gt;&lt;li&gt;&lt;em&gt;category_sql&lt;/em&gt; is a SQL statement that produces the set of categories. This statement must return only one column. It must produce at least one row, or an error will be generated. Also, it must not produce duplicate values, or an error will be generated.&lt;/li&gt;&lt;/ul&gt;&lt;br /&gt;&lt;p&gt;If this is the first time you use something from the &lt;a href=&quot;http://www.postgresql.org/docs/current/interactive/tablefunc.html&quot; target=&quot;_blank&quot;&gt;tablefunc module&lt;/a&gt;, you may need to install it to your database by running &lt;code&gt;&lt;u&gt;CREATE EXTENSION tablefunc;&lt;/u&gt;&lt;/code&gt;&lt;/p&gt;&lt;pre class=&quot;prettyprint lang-sql&quot;&gt;create table sales(year int, month int, qty int);&lt;br /&gt;insert into sales values(2007, 1, 1000);&lt;br /&gt;insert into sales values(2007, 2, 1500);&lt;br /&gt;insert into sales values(2007, 7, 500);&lt;br /&gt;insert into sales values(2007, 11, 1500);&lt;br /&gt;insert into sales values(2007, 12, 2000);&lt;br /&gt;insert into sales values(2008, 1, 1000);&lt;br /&gt;&lt;br /&gt;select * from crosstab(&lt;br /&gt;  &#39;select year, month, qty from sales order by 1&#39;,&lt;br /&gt;  &#39;select m from generate_series(1,12) m&#39;&lt;br /&gt;) as (&lt;br /&gt;  year int,&lt;br /&gt;  &quot;Jan&quot; int,&lt;br /&gt;  &quot;Feb&quot; int,&lt;br /&gt;  &quot;Mar&quot; int,&lt;br /&gt;  &quot;Apr&quot; int,&lt;br /&gt;  &quot;May&quot; int,&lt;br /&gt;  &quot;Jun&quot; int,&lt;br /&gt;  &quot;Jul&quot; int,&lt;br /&gt;  &quot;Aug&quot; int,&lt;br /&gt;  &quot;Sep&quot; int,&lt;br /&gt;  &quot;Oct&quot; int,&lt;br /&gt;  &quot;Nov&quot; int,&lt;br /&gt;  &quot;Dec&quot; int&lt;br /&gt;);&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;h3&gt;Full-Text Search&lt;/h3&gt;&lt;br /&gt;&lt;p&gt;Full-text search enables the user to search text columns with parts of the column value, not the exact value like in regular queries.&lt;/p&gt;&lt;br /&gt;&lt;ul&gt;&lt;br /&gt;&lt;li&gt;&lt;strong&gt;LIKE and ILIKE&lt;/strong&gt; : LIKE and ILIKE (case-insensitive LIKE) are the simplest forms of text search. LIKE compares column values against a given pattern string. The % and _ characters are wildcards. % matches any number of any characters, and _ matches exactly one character. &lt;br /&gt;&lt;ul&gt;&lt;br /&gt;&lt;li&gt;&lt;font color=&quot;#0000ff&quot;&gt;SELECT title FROM movies WHERE title ILIKE &#39;stardust%&#39;;&lt;/font&gt; &lt;br /&gt;&lt;ul&gt;&lt;br /&gt;&lt;li&gt;&lt;font color=&quot;#000000&quot;&gt;will return movies with titles like : “Stardust” or “Stardust Memories”&lt;/font&gt;&lt;/li&gt;&lt;/ul&gt;&lt;/li&gt;&lt;/ul&gt;&lt;br /&gt;&lt;li&gt;&lt;font color=&quot;#000000&quot;&gt;&lt;strong&gt;Regex&lt;/strong&gt; : You could write the WHERE part of your queries against text columns in regular expressions. A&lt;/font&gt; regular expression match is led by the ~ operator, with the&lt;br&gt;optional ! (meaning, not matching) and * (meaning case insensitive). So, to count all movies that do not begin with the, the following case-insensitive query will work. The characters inside the string are the regular expression. &lt;br /&gt;&lt;ul&gt;&lt;br /&gt;&lt;li&gt;&lt;font color=&quot;#0000ff&quot;&gt;SELECT COUNT(*) FROM movies WHERE title !~* &#39;^the.*&#39;;&lt;/font&gt;&lt;/li&gt;&lt;/ul&gt;&lt;br /&gt;&lt;li&gt;&lt;font color=&quot;#000000&quot;&gt;&lt;strong&gt;Bride of Levenshtein&lt;/strong&gt; : &lt;/font&gt;Levenshtein is a string comparison algorithm that compares how similar two strings are by how many steps are required to change one string into another. Each replaced, missing, or added character counts as a step (Changes in case cost a point too). The distance is the total number of steps away. levenshtein() function is provided by the &lt;u&gt;fuzzystrmatch&lt;/u&gt; contrib package.The following query return 3 because we need to replace 2 characters and and add 1 character to make bat into fads. &lt;br /&gt;&lt;ul&gt;&lt;br /&gt;&lt;li&gt;&lt;font color=&quot;#0000ff&quot;&gt;SELECT levenshtein(&#39;bat&#39;, &#39;fads&#39;);&lt;/font&gt;&lt;/li&gt;&lt;/ul&gt;&lt;br /&gt;&lt;li&gt;&lt;strong&gt;Trigram&lt;/strong&gt; :&amp;nbsp; A trigram is a group of three consecutive characters taken from a string. The &lt;u&gt;pg_trgm&lt;/u&gt; contrib module breaks a string into as many trigrams as it can. Finding a matching string is as simple as counting the number of matching trigrams. The strings with the most matches are the most similar. It’s useful for doing a search where you’re OK with either slight misspellings or even minor words missing. The longer the string, the more trigrams and the more likely a match. &lt;br /&gt;&lt;ul&gt;&lt;br /&gt;&lt;li&gt;&lt;font color=&quot;#0000ff&quot;&gt;SELECT show_trgm(&#39;Avatar&#39;);&amp;nbsp; -- returns {&quot; a&quot;,&quot; av&quot;,&quot;ar &quot;,ata,ava,tar,vat}&lt;/font&gt;&lt;/li&gt;&lt;/ul&gt;&lt;br /&gt;&lt;li&gt;PostgreSQL have more natural language processing capabilities (&lt;strong&gt;TSVector&lt;/strong&gt; and &lt;strong&gt;TSQuery&lt;/strong&gt;) and even can search by word phonetics (&lt;strong&gt;metaphone&lt;/strong&gt;) &lt;br /&gt;&lt;li&gt;You could combine text search function in many interesting ways like the following query that “Get me names that sound the most like Robi n Williams, in order.” &lt;br /&gt;&lt;ul&gt;&lt;br /&gt;&lt;li&gt;&lt;font color=&quot;#0000ff&quot;&gt;SELECT * FROM actors&lt;br&gt;WHERE metaphone(name,8) % metaphone(&#39;Robin Williams&#39;,8)&lt;br&gt;ORDER BY levenshtein(lower(&#39;Robin Williams&#39;), lower(name));&lt;/font&gt;&lt;/li&gt;&lt;/ul&gt;&lt;/li&gt;&lt;/ul&gt;&lt;br /&gt;&lt;p&gt;&amp;nbsp;&lt;/p&gt;&lt;br /&gt;&lt;p&gt;In this post we introduced PostgreSQL, a popular open source RDBMS. In future posts we will introduce more DBMSs.&lt;/p&gt;  </description><link>http://ebeid-soliman.blogspot.com/2013/06/postgresql-101.html</link><author>noreply@blogger.com (Ebeid Soliman ElSayed)</author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEimUOWML4h23t3RD_6qHXFB4qE1GzkMQ4uF6fQokNks8oHitkdPp_RZFOpZ1BUErwy8lztZJ6lahFRzBOndecsR0-G4djTC1YsOYocUu7R5PFQ8-T3ZxdQOIVrjNmKWCSszKPkrHq00gw/s72-c?imgmax=800" height="72" width="72"/></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-59384554657271185.post-8505498433861402798</guid><pubDate>Thu, 02 May 2013 21:08:00 +0000</pubDate><atom:updated>2013-05-02T16:08:18.632-05:00</atom:updated><category domain="http://www.blogger.com/atom/ns#">Microsoft Pex</category><category domain="http://www.blogger.com/atom/ns#">Parameterized Unit Tests</category><category domain="http://www.blogger.com/atom/ns#">Unit testing</category><category domain="http://www.blogger.com/atom/ns#">Unit Tests</category><title>Parameterized Test Patterns using Microsoft Pex</title><description>&lt;p&gt;We talked before about the difference between unit tests and parameterized unit tests. In this post we will talk about common patterns for writing good parameterized unit tests. Keep in mind that we will use these tests with Microsoft Pex (as an automatic test input generation tool) to get test inputs that trigger all the possible scenarios of the code-under-test. &lt;/p&gt; &lt;blockquote&gt; &lt;p&gt;Before anything, let’s clarify what are the questions we want to answer using the parameterized unit tests. There are&amp;nbsp; two core questions:&lt;/p&gt; &lt;ul&gt; &lt;li&gt;What are good scenarios (sequences of method calls) to exercise the code-under-test? (&lt;font color=&quot;#ff0000&quot;&gt;Coverage&lt;/font&gt;)  &lt;li&gt;What are good assertions that can be stated easily without re-implementing the algorithm? (&lt;font color=&quot;#ff0000&quot;&gt;Verification&lt;/font&gt;)&lt;/li&gt;&lt;/ul&gt; &lt;p&gt;A parameterized unit test is only useful if it provides answers for both questions: &lt;/p&gt; &lt;ul&gt; &lt;li&gt;Without sufficient coverage, i.e. if the scenario is too narrow to reach all the code-under-test, the extent of the test is limited.  &lt;li&gt;Without sufficient verification of the computed results, i.e. if the test does not contain enough assertions, the test does not check that the code is doing the right thing. All it would check for is that the code-under-test does not crash.&lt;/li&gt;&lt;/ul&gt;&lt;/blockquote&gt; &lt;h3&gt;Test Patterns&lt;/h3&gt; &lt;h4&gt;1- Arrange, Act, Assert&lt;/h4&gt; &lt;p&gt;The ’AAA’ (Triple-A) is a well-known pattern for writing unit tests. It applies to parameterized unit tests as well. A parameterized unit test using this patter is organized in three sections:&lt;/p&gt; &lt;ul&gt; &lt;li&gt;&lt;strong&gt;Arrange&lt;/strong&gt;: set up the unit under test  &lt;li&gt;&lt;strong&gt;Act&lt;/strong&gt;: exercise the unit under test, capturing any resulting state  &lt;li&gt;&lt;strong&gt;Assert&lt;/strong&gt;: verify the behavior through assertions&lt;/li&gt;&lt;/ul&gt; &lt;p&gt;An example of this pattern in a traditional unit test:&lt;/p&gt;  &lt;pre class=&quot;prettyprint lang-cs&quot;&gt;&lt;br /&gt;[Test]&lt;br&gt;pubic void AddItem()&lt;br&gt;{&lt;br&gt;      // arrange&lt;br&gt;      var list = new ArrayList();&lt;br&gt;      var item = new object();&lt;br&gt;      // act&lt;br&gt;      list.Add(item);&lt;br&gt;      // assert&lt;br&gt;      Assert.IsTrue(list.Count == 1);&lt;br&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;&lt;p&gt;An example of this pattern in a parameterized unit test:&lt;/p&gt;&lt;br /&gt;&lt;br /&gt;&lt;pre class=&quot;prettyprint lang-cs&quot;&gt;&lt;br /&gt;[PexMethod]&lt;br&gt;pubic void AddItem(object item)&lt;br&gt;{&lt;br&gt;      // arrange&lt;br&gt;      var list = new ArrayList();&lt;br&gt;      // act&lt;br&gt;      list.Add(item);&lt;br&gt;      // assert&lt;br&gt;      Assert.IsTrue(list.Count == 1);&lt;br&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;&lt;h4&gt;2- Assume, Arrange, Act, Assert&lt;/h4&gt;&lt;br /&gt;&lt;p&gt;This pattern is an extension of the first pattern where an Assumption section is added at the beginning. An &lt;strong&gt;assumption&lt;/strong&gt; restricts possible test inputs, acting as a filter. A parameterized unit test using this pattern is organized in four sections: &lt;/p&gt;&lt;br /&gt;&lt;ul&gt;&lt;br /&gt;&lt;li&gt;&lt;strong&gt;Assume&lt;/strong&gt;: assume preconditions over the test inputs &lt;/li&gt;&lt;br /&gt;&lt;li&gt;&lt;strong&gt;Arrange&lt;/strong&gt;: set up the unit under test &lt;/li&gt;&lt;br /&gt;&lt;li&gt;&lt;strong&gt;Act&lt;/strong&gt;: exercise the unit under test, capturing any resulting state &lt;/li&gt;&lt;br /&gt;&lt;li&gt;&lt;strong&gt;Assert&lt;/strong&gt;: verify the behavior through assertions &lt;/li&gt;&lt;br /&gt;&lt;/ul&gt;&lt;br /&gt;&lt;p&gt;The following example tests that adding an element to any list increments the Count property. We use an assumption to filter out the case where list is a null reference.&lt;/p&gt;&lt;br /&gt;&lt;br /&gt;&lt;pre class=&quot;prettyprint lang-cs&quot;&gt;&lt;br /&gt;[PexMethod]&lt;br&gt;void AssumeActAssert(ArrayList list, object item)&lt;br&gt;{&lt;br&gt;     // assume&lt;br&gt;     PexAssume.IsNotNull(list);&lt;br&gt;     // arrange&lt;br&gt;     var count = list.Count;&lt;br&gt;     // act&lt;br&gt;     list.Add(item);&lt;br&gt;     // assert&lt;br&gt;     Assert.IsTrue(list.Count == count + 1);&lt;br&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;&lt;h4&gt;3- Parameterized Stubs&lt;/h4&gt;&lt;br /&gt;&lt;br /&gt;&lt;p&gt;If the code-under-test already contains many assertion statements that verify its behavior, an effective parameterized unit test might be quite simple in itself, because it can leverage the assertions in the code.&lt;/p&gt;&lt;br /&gt;&lt;br /&gt;&lt;pre class=&quot;prettyprint lang-cs&quot;&gt;[PexMethod] &lt;br&gt;public void Add( [PexAssumeUnderTest]ArrayList list, object item) &lt;br&gt;{ &lt;br&gt; list.Add(item); &lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;&lt;p&gt;The attribute PexAssumeUnderTest is a short-hand notation to make sure that the parameter is not null, and has exactly the type indicated by its declaration (not a subtype).&lt;/p&gt;&lt;br /&gt;&lt;br /&gt;&lt;br&gt;&lt;br /&gt;&lt;h4&gt;4- Observed Values&lt;/h4&gt;At any point in the parameterized unit test, if you want to log the value of any variable or parameter, just use &lt;br /&gt;&lt;pre class=&quot;prettyprint lang-cs&quot;&gt;PexObserve.ValueForViewing(&quot;Variable Name&quot;, var_name);&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;&lt;h4&gt;5- Allowed Exceptions&lt;/h4&gt;&lt;br /&gt;&lt;p&gt;Traditional unit test frameworks support the concept of expected exception, where a test case or API call is expected to throw an exception. If the test does not throw the exception or throws an exception that does not match the criteria, the execution fails. The same concept applied to parameterized unit tests. &lt;/p&gt;&lt;br /&gt;&lt;br /&gt;&lt;pre class=&quot;prettyprint lang-cs&quot;&gt;[PexMethod][PexAllowedException(typeof(ArgumentNullException))] &lt;br&gt;void Constructor(string value) &lt;br&gt;{ &lt;br&gt; // throws ArgumentNullException if value is null &lt;br&gt; var myClass = new MyClass(value); &lt;br&gt;}&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;&lt;h4&gt;6- State Relation&lt;/h4&gt;&lt;br /&gt;&lt;p&gt;This pattern applies when an API call causes an internal state change that can be (partially) observed through other API calls. A classic example of such a pattern is the combination of Insert and Contains operation on any collection type:&lt;/p&gt;&lt;br /&gt;&lt;br /&gt;&lt;pre class=&quot;prettyprint lang-cs&quot;&gt;&lt;br /&gt;[PexMethod] &lt;br&gt;void InsertContains(stringvalue) &lt;br&gt;{ &lt;br&gt; var list = new List&lt;string&gt;(); &lt;br&gt; list.Add(value); &lt;br&gt; Assert.IsTrue(list.Contains(value)); &lt;br&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;&lt;h4&gt;7- Roundtrip&lt;/h4&gt;&lt;br /&gt;&lt;p&gt;This pattern applies to an API that transforms its inputs in a reversible way: When the API has a function &lt;em&gt;f&lt;/em&gt; and an inverse function &lt;em&gt;f_1&lt;/em&gt;, then it should hold that &lt;em&gt;f_1(f(x))=x&lt;/em&gt; for all &lt;em&gt;x&lt;/em&gt;. A classic example of such pattern is property setters and getters, where the test fails when the setter rejects a particular argument value.&lt;/p&gt;&lt;br /&gt;&lt;br /&gt;&lt;pre class=&quot;prettyprint lang-cs&quot;&gt;&lt;br /&gt;[PexMethod] &lt;br&gt;void PropertyRoundtrip(string value) &lt;br&gt;{ &lt;br&gt; // arrange &lt;br&gt; var target = new MyClass(); &lt;br&gt; &lt;br&gt; // two-way roundtrip &lt;br&gt; target.Name = value;   // calls setter &lt;br&gt; var roundtripped = target.Name; // calls getter &lt;br&gt;&lt;br&gt; // assert &lt;br&gt; Assert.AreEqual(value, roundtripped); &lt;br&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;&lt;p&gt;Another example is serialization and deserialization of values.&lt;/p&gt;&lt;br /&gt;&lt;pre class=&quot;prettyprint lang-cs&quot;&gt;&lt;br /&gt;[PexMethod] &lt;br&gt;void ToStringParseRoundtrip(int value) &lt;br&gt;{ &lt;br&gt; // two-way roundtrip &lt;br&gt; string s = value.ToString(); &lt;br&gt; int parsed = int.Parse(s); &lt;br&gt;&lt;br&gt; // assert Assert.AreEqual(value, parsed); &lt;br&gt;}&lt;br&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;&lt;h4&gt;8- Normalized Roundtrip&lt;/h4&gt;&lt;br /&gt;&lt;p&gt;The Pattern Roundtrip showed how to test a method for which in inverse operation exists. For example, &lt;strong&gt;int.Parse&lt;/strong&gt; is the inverse of &lt;strong&gt;int.ToString&lt;/strong&gt;. This is not the case in the other direction: &lt;strong&gt;int.ToString&lt;/strong&gt; is not exactly the inverse of &lt;strong&gt;int.Parse&lt;/strong&gt;, because the parsing ignores whitespace (some kind of data normalization): &lt;/p&gt;&lt;br /&gt;&lt;br /&gt;&lt;pre class=&quot;prettyprint lang-cs&quot;&gt;&lt;br /&gt;int.Parse(&quot; 5&quot;).ToString() == &quot;5&quot;;&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;&lt;p&gt;This pattern is applied when the API has a function &lt;strong&gt;f&lt;/strong&gt; and an inverse function &lt;strong&gt;f_1&lt;/strong&gt;, then it should hold that &lt;strong&gt;f_1(f(f_1(x)))=f_1(x)&lt;/strong&gt; for all &lt;strong&gt;x&lt;/strong&gt; where &lt;strong&gt;f_1(x)&lt;/strong&gt; is defined.&lt;/p&gt;&lt;br /&gt;&lt;br /&gt;&lt;pre class=&quot;prettyprint lang-cs&quot;&gt;&lt;br /&gt;[PexMethod] &lt;br&gt;void ThreeWayRoundtrip(string value) &lt;br&gt;{ &lt;br&gt; // ’hello%20world’ &amp;lt;= ’hello world’ &lt;br&gt; var normalized = Uri.EscapeDataString(value); &lt;br&gt; &lt;br&gt; // ’helloworld’ &amp;lt;= ’hello%20world’ &lt;br&gt; var intermediate = Uri.UnescapeDataString(normalized); &lt;br&gt;&lt;br&gt; // ’hello%20world’ &amp;lt;= ’hello world’ &lt;br&gt; var roundtripped = Uri.EscapeDataString(intermediate); &lt;br&gt;&lt;br&gt; // assert &lt;br&gt; Assert.AreEqual(normalized, roundtripped); &lt;br&gt;}&lt;br&gt;&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;&lt;h4&gt;9- Reachability&lt;/h4&gt;&lt;br&gt;&lt;br /&gt;&lt;p&gt;If your test assumptions are so complicated and it is not clear whether there is any test input that fulfills them. You could use &lt;strong&gt;PexAssert.ReachEventually(&quot;GoalName&quot;)&lt;/strong&gt; wherever in your test to make sure that there is at least one input that reach this point in your test. The goal name have to be passed to the &lt;strong&gt;PexAssertReachEventuallyAttribute&lt;/strong&gt; constructor. A parameterized unit test fails when Pex does not find a way to reach a goal, indicated by calling the &lt;strong&gt;PexAssert.Reached&lt;/strong&gt; method in a parameterized unit test annotated with the &lt;strong&gt;PexAssertReachEventuallyAttribute&lt;/strong&gt;.&lt;/p&gt;&lt;br /&gt;&lt;br /&gt;&lt;pre class=&quot;prettyprint lang-cs&quot;&gt;&lt;br /&gt;[PexMethod] &lt;br&gt;[PexAssertReachEventually(&quot;passed&quot;, StopWhenAllReached = true)] &lt;br&gt;public void ParsingSuccesful(string input) &lt;br&gt;{ &lt;br&gt; // complicated parsing code &lt;br&gt; DateTime date; &lt;br&gt; if (DateTime.TryParse(input, out date)) &lt;br&gt; { &lt;br&gt;  // and we want to see at least one case where parsing is successful. &lt;br&gt;  PexAssert.ReachEventually(&quot;passed&quot;); &lt;br&gt; } &lt;br&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;&lt;p&gt;Multiple goals can be combined in a single parameterized unit test for more advanced scenarios by passing a list of goal identifiers in the constructor of the PexAssertReachEventuallyAttribute. Each goal identifier must be reached and notified in order for the parameterized unit test to succeed.&lt;/p&gt;&lt;br /&gt;&lt;br /&gt;&lt;pre class=&quot;prettyprint lang-cs&quot;&gt;&lt;br /&gt;[PexMethod] &lt;br&gt;[PexAssertReachEventually(&quot;parsed&quot;, &quot;y2k&quot;, StopWhenAllReached = true)] &lt;br&gt;public void ParsingSuccesfulWithMoreGoals(string input) &lt;br&gt;{ &lt;br&gt; // complicated parsing code &lt;br&gt; DateTime date;&lt;br&gt; if (DateTime.TryParse(input, out date)) &lt;br&gt; { &lt;br&gt;  // and we want to see at least one case where parsing is successful. &lt;br&gt;  PexAssert.ReachEventually(&quot;parsed&quot;); &lt;br&gt; } &lt;br&gt; if (date.Year == 2000) &lt;br&gt; {&lt;br&gt;  // we want to see at least one test with the year 2000 &lt;br&gt;  PexAssert.ReachEventually(&quot;y2k&quot;); &lt;br&gt; }&lt;br&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;&lt;h4&gt;10- Reachable Implication&lt;/h4&gt;&lt;br /&gt;&lt;br /&gt;&lt;p&gt;Implications assert a property when a predicate (condition) is true. Use &lt;strong&gt;PexAssert.ImpliesEventually&lt;/strong&gt; to make an implication that should be true and that should be executed at least once. The test have to be annotated with the &lt;strong&gt;PexAssertReachEventuallyAttribute&lt;/strong&gt;. A parameterized unit test fails when Pex does not find a way to make the predicate of &lt;strong&gt;PexAssert.ImpliesEventually&lt;/strong&gt; evaluates true at least once. &lt;/p&gt;&lt;br /&gt;&lt;br /&gt;&lt;pre class=&quot;prettyprint lang-cs&quot;&gt;&lt;br /&gt;[PexMethod] &lt;br&gt;[PexAssertReachEventually] &lt;br&gt;public void ParseImpliesParse(string input) &lt;br&gt;{ &lt;br&gt; bool value; &lt;br&gt; // if TryParse succeeds, Parse should succeed too. Also make sure TryParse succeeds at least once &lt;br&gt; PexAssert.ImpliesEventually( bool.TryParse(input, out value), () =&amp;gt; bool.Parse(input) );&lt;br&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;&lt;h4&gt;11- Seed Values to Help Pex&lt;/h4&gt;&lt;br /&gt;&lt;p&gt;A parameterized unit test needs concrete input data to be executed. Pex&#39;s role is to automatically generate relevant input data via code analysis. Sometimes it might be desirable or even necessary to provide manually chosen seed values to Pex to guide the automated code exploration. In effect, Pex will fuzz the provided values in ways that cause alternative execution paths to be taken. The &lt;strong&gt;PexArgumentsAttribute&lt;/strong&gt; can be used to provide primitive data. Each instance of this attribute gives a list of values that must match the parameter types of the parameterized unit test (and in the same parameters order).&lt;br /&gt;&lt;/p&gt;&lt;br /&gt;&lt;br /&gt;&lt;pre class=&quot;prettyprint lang-cs&quot;&gt;&lt;br /&gt;[PexMethod]&lt;br /&gt;[PexArguments(&quot;var i = 0;&quot;, 0)]&lt;br /&gt;[PexArguments(&quot;class Foo {}&quot;, 12)]&lt;br /&gt;public void ParseTest(string text, int line)&lt;br /&gt;{&lt;br /&gt; var parser = new Parser();&lt;br /&gt; parser.SetLine(line);&lt;br /&gt; var node = parser.Parse(text);&lt;br /&gt;&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;p&gt;Before analyzing the branch conditions in the code, Pex will first execute the parameterized unit test with the provided values. This way, Pex acquires knowledge about the code reachable from a test, and during the subsequence code exploration Pex will try to further increase code coverage by slightly modifying the values to trigger different execution paths. In effect, Pex will &lt;a href=&quot;http://en.wikipedia.org/wiki/Fuzz_testing&quot; target=&quot;_blank&quot;&gt;fuzz&lt;/a&gt; the provided values. &lt;/p&gt;&lt;br /&gt;&lt;br /&gt;&lt;h4&gt;12- Regression Tests&lt;/h4&gt;&lt;br /&gt;&lt;br /&gt;&lt;p&gt;In these tests some we could persist a computed value in the generated test so when the generated test is executed in the future, it verifies that the (possible changed) code-under-test still computes the same value. There are several ways how outputs can be logged. For a single output value, one can use the return value of the parameterized unit test:&lt;/p&gt;&lt;br /&gt;&lt;pre class=&quot;prettyprint lang-cs&quot;&gt;&lt;br /&gt;[PexMethod]&lt;br /&gt;public int Add(int a, int b)&lt;br /&gt;{&lt;br /&gt; return a + b;&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;p&gt;Pex will recursively traverse the observable properties and fields of the value and add assertions in the generated test for each one of them:&lt;/p&gt;&lt;br /&gt;&lt;pre class=&quot;prettyprint lang-cs&quot;&gt;&lt;br /&gt;[Test]&lt;br /&gt;[PexGeneratedBy(typeof(Program))]&lt;br /&gt;public void Add866()&lt;br /&gt;{&lt;br /&gt;    int i;&lt;br /&gt;    i = this.Add(0, 0);&lt;br /&gt;    PexAssert.AreEqual&lt;int&gt;(0, i);&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;p&gt;For multiple values, use &lt;strong&gt;out&lt;/strong&gt; parameters in the parameterized unit tests&lt;/p&gt;&lt;br /&gt;&lt;pre class=&quot;prettyprint lang-cs&quot;&gt;&lt;br /&gt;[PexMethod]&lt;br /&gt;public void Add(int a, int b, out int result)&lt;br /&gt;{&lt;br /&gt; result = a + b;&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;p&gt;Which Pex will use to generate the following&lt;/p&gt;&lt;br /&gt;&lt;pre class=&quot;prettyprint lang-cs&quot;&gt;&lt;br /&gt;[Test]&lt;br /&gt;[PexGeneratedBy(typeof(Program))]&lt;br /&gt;public void Add13()&lt;br /&gt;{&lt;br /&gt;    int i = 0;&lt;br /&gt;    this.Add(0, 0, out i);&lt;br /&gt;    PexAssert.AreEqual&lt;int&gt;(0, i);&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;p&gt;If the number of values might be dynamic, you could log these values using &lt;strong&gt;&lt;a href=&quot;http://research.microsoft.com/en-us/um/redmond/projects/pex/wiki/PexObserve.html&quot; target=&quot;_blank&quot;&gt;PexObserve&lt;/a&gt;.Value&lt;/strong&gt; and observe it later using the &lt;strong&gt;&lt;a href=&quot;http://research.microsoft.com/en-us/um/redmond/projects/pex/wiki/PexObserve.html&quot; target=&quot;_blank&quot;&gt;PexObserve&lt;/a&gt;.ValueAtEndOfTest&lt;/strong&gt; method:&lt;/p&gt;&lt;br /&gt;&lt;pre class=&quot;prettyprint lang-cs&quot;&gt;&lt;br /&gt;[PexMethod]&lt;br /&gt;void Add(int a, int b)&lt;br /&gt;{&lt;br /&gt; int result = a * b;&lt;br /&gt; PexObserve.Value&lt;int&gt;(&quot;result&quot;, result);&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;  </description><link>http://ebeid-soliman.blogspot.com/2013/05/parameterized-test-patterns-using.html</link><author>noreply@blogger.com (Ebeid Soliman ElSayed)</author></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-59384554657271185.post-6691406490897728526</guid><pubDate>Mon, 29 Apr 2013 20:00:00 +0000</pubDate><atom:updated>2013-04-28T16:01:25.139-05:00</atom:updated><category domain="http://www.blogger.com/atom/ns#">Microsoft Pex</category><title>Microsoft Pex: Understanding Assumptions, Assertions, and Test-Case Failures</title><description>&lt;p&gt;In a previous post we started using Microsoft Pex and showed how it helped exploring all possible code paths, and how that helped discovering a defect in our program logic. In that example, even our program logic is defective, all test cases succeeded. A test case fails if there is an un-caught exception or a failed assertion.&lt;/p&gt; &lt;p&gt;To see an example of a failed test case and how Pex could help in fixing it, let’s add the following basic function to our code:&lt;/p&gt;&lt;pre class=&quot;prettyprint lang-cs&quot;&gt;public void Add(ArrayList a, object o)&lt;br /&gt;        {&lt;br /&gt;            a.Add(o);&lt;br /&gt;        }&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;p&gt;when you run Pex for that simple method, you get the following results:&lt;/p&gt;&lt;br /&gt;&lt;p&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhmNopAnmrQoO81K3UwsmumD6CPNmeBQeHYF-FHafOxt2MTCHDtWChlaLweTELqe31zXap2gctbBBww0-RHjbVu7Ys1ok6lAYrNl_narsjSXVXKBXZAWsz9QxUnkHLzN04nMWQEAIHLQA/s1600-h/ConsoleApplication2%252520-%252520Microsoft%252520Visual%252520Studio_2013-04-24_15-46-30%25255B4%25255D.jpg&quot;&gt;&lt;img style=&quot;background-image: none; border-right-width: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px&quot; title=&quot;ConsoleApplication2 - Microsoft Visual Studio_2013-04-24_15-46-30&quot; border=&quot;0&quot; alt=&quot;ConsoleApplication2 - Microsoft Visual Studio_2013-04-24_15-46-30&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhE_JIr1jcWXKwavO2Lx5X9o1d7p_eUmCP8jnNJBDei3mk08fmzM13AHscR6tq1tU6-1jHSKyRYLq-oMXvbqjKOvqpv01YaPQJyRcgPIzXKbiLQke5nC0jxPBMPoALXMWfPxfQ8opK8gg/?imgmax=800&quot; width=&quot;727&quot; height=&quot;134&quot;&gt;&lt;/a&gt;&lt;/p&gt;&lt;br /&gt;&lt;p&gt;As you might expected, the ArrayList object might be NULL. In situations similar to this one, when a higher-level component (the code that called Add() method) passes malformed data to a lower-level component(that Add() method), which the lower-level component rejects, then the higher-level component should be prevented from doing so in the first place.&lt;/p&gt;&lt;br /&gt;&lt;p&gt;One way to achieve this is to promote the failure condition of the lower-level component to the abstraction level of the higher-level component. This is what the &lt;u&gt;Add Precondition&lt;/u&gt; feature of Pex does: It expresses a low-level failure condition at the abstraction level of the code under test. When added to the code-under-test as argument validation code—also called a precondition—then this effectively prevents the code under test from causing a failure somewhere in its execution. In other words, the Add Precondition feature doesn’t completely fix an error, but it promotes the failure condition to a higher, more appropriate abstraction level.&lt;/p&gt;&lt;br /&gt;&lt;p&gt;To add a precondition to your code, click the failed test case row, then on the details section (right) click &lt;u&gt;Add Precondition&lt;/u&gt;, as in picture below&lt;/p&gt;&lt;br /&gt;&lt;p&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiIFJJshmEjPOEvsmzTLRvdPSUj_PZWAeGahVE0lQcp4EujKQN62XPzp8_RXYgJMGmT4wKq6dd944wy3VxPXYebf_ABdJGemvgKSqCYbsY0GwDQle15kUxSFCI4p2zp8x1JL-f1hz8IQw/s1600-h/002%252520-%252520200%252520-%252520Exploring%252520Code%252520with%252520Microsoft%252520Pex.docx%252520%25255BCompatibility%252520Mode%25255D%252520-%252520Word_2013-04-25_08-56-05%25255B4%25255D.jpg&quot;&gt;&lt;img style=&quot;background-image: none; border-right-width: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px&quot; title=&quot;002 - 200 - Exploring Code with Microsoft Pex.docx [Compatibility Mode] - Word_2013-04-25_08-56-05&quot; border=&quot;0&quot; alt=&quot;002 - 200 - Exploring Code with Microsoft Pex.docx [Compatibility Mode] - Word_2013-04-25_08-56-05&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhneUfBNIRhvuAmQB7-ZA8OFtcAodVroDtW6TMTL-zRStUZFCj7QqIm8Zj9hcsjooTXHPBpCgsoCIg7qcQxDqBmL8hyphenhyphen-3z1DmGIJ2ONXLBLFnjOmjPhlFMZQxtDTYDtoprRj31XgOrC0Q/?imgmax=800&quot; width=&quot;581&quot; height=&quot;392&quot;&gt;&lt;/a&gt;&lt;/p&gt;&lt;br /&gt;&lt;p&gt;Pex will open &lt;u&gt;Preview and Apply updates&lt;/u&gt; dialog box to show you the proposed code modifications that Pex will do. &lt;/p&gt;&lt;br /&gt;&lt;p&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgcPwX7lK571_JPD08DZCP3IfP74Fnw7psJ9k617fS3Xg3JON4qu6xVyTbyokbby83Pp1xy0L_h3Jbj5IVZbLZvKPJcTCTTWYMAZKVOYaVjzq5pZFfkFylrgDF3dcAdIBPMl5YmtVoa-Q/s1600-h/Preview%252520and%252520Apply%252520updates_2013-04-25_09-00-24%25255B3%25255D.jpg&quot;&gt;&lt;img style=&quot;background-image: none; border-right-width: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px&quot; title=&quot;Preview and Apply updates_2013-04-25_09-00-24&quot; border=&quot;0&quot; alt=&quot;Preview and Apply updates_2013-04-25_09-00-24&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhwWpYaW3xwr-N42tC3H2hbto3h9mUORDPvZcx1pQTc-9lID_w3AI2I-PnqWw3jipzGxvDkiznsl_URwX17blm_buNwzoxMW9KFgZczhsYQnIOPnf2L1-pJlVj-Ktcit0VTPXncGo4mEA/?imgmax=800&quot; width=&quot;480&quot; height=&quot;311&quot;&gt;&lt;/a&gt;&lt;/p&gt;&lt;br /&gt;&lt;p&gt;Review and Click &lt;u&gt;Apply&lt;/u&gt;. The modified method will look like:&lt;/p&gt;&lt;pre class=&quot;prettyprint lang-cs&quot;&gt;        &lt;br /&gt;public void Add(ArrayList a, object o)&lt;br /&gt;        {&lt;br /&gt;            // &lt;pex&gt;&lt;br /&gt;            Debug.Assert(a != (ArrayList)null, &quot;a&quot;);&lt;br /&gt;            // &lt;/pex&gt;&lt;br /&gt;            a.Add(o);&lt;br /&gt;        }&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;p&gt;When you run Pex for our method now, we will not find a failed test case. &lt;/p&gt;&lt;br /&gt;&lt;p&gt;The concept of assertions is well known in unit test frameworks. Pex understands the built-in Assert classes provided by each supported test framework. However, most frameworks do not provide a corresponding Assume class as Pex did. &lt;strong&gt;&lt;a href=&quot;http://research.microsoft.com/en-us/um/redmond/projects/pex/wiki/pexassume.html&quot; target=&quot;_blank&quot;&gt;PexAssume&lt;/a&gt;&lt;/strong&gt; is a class to express assumptions, i.e. a precondition. The methods of this class can be used to filter out undesirable test inputs. If you do not want to use an existing test framework, Pex also has the &lt;a href=&quot;http://research.microsoft.com/en-us/um/redmond/projects/pex/wiki/PexAssert.html&quot; target=&quot;_blank&quot;&gt;PexAssert&lt;/a&gt; class. Some functionalities can be achieved using attributes instead of PexAssume methods, like &lt;strong&gt;&lt;a href=&quot;http://research.microsoft.com/en-us/um/redmond/projects/pex/wiki/PexAssumeNotNullAttribute.html&quot; target=&quot;_blank&quot;&gt;PexAssumeNotNullAttribute&lt;/a&gt;&lt;/strong&gt; and &lt;a href=&quot;http://research.microsoft.com/en-us/um/redmond/projects/pex/wiki/PexAssumeUnderTestAttribute.html&quot; target=&quot;_blank&quot;&gt;&lt;strong&gt;PexAssumeUnderTestAttribute&lt;/strong&gt;&lt;/a&gt;.&lt;strong&gt; &lt;/strong&gt;&lt;/p&gt;&lt;pre class=&quot;prettyprint lang-cs&quot;&gt; &lt;br /&gt;[PexMethod]&lt;br /&gt;public void Test1(object o)  //precondition: o should not be null&lt;br /&gt;{&lt;br /&gt; PexAssume.IsNotNull(o);&lt;br /&gt; ...&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;[PexMethod]&lt;br /&gt;public void Test2([PexAssumeNotNull]object o) //precondition: o should not be null&lt;br /&gt;{ &lt;br /&gt; ...&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;p&gt;When you write an assertion, Pex will not only passively detect assertion violations, but Pex will in fact actively try to compute test inputs that will cause the assertion to fail (just as an assertion might throw a &lt;strong&gt;PexAssertFailedException&lt;/strong&gt;). Pes uses these exceptions internally to stop a test case when an assumption fails.&lt;/p&gt;&lt;br /&gt;&lt;h3&gt;Expected Exceptions&lt;/h3&gt;&lt;br /&gt;&lt;p&gt;You can annotate the test—or the test class, or the test assembly—with one of the following attributes to indicate which exception types can or must be thrown by the test in order to be considered successful: &lt;br /&gt;&lt;ul&gt;&lt;br /&gt;&lt;li&gt;&lt;strong&gt;PexAllowedExceptionAttribute&lt;/strong&gt; indicates that a test method, or any other method that it calls directly or indirectly, can throw a particular type of exception for some test inputs. &lt;pre class=&quot;prettyprint lang-cs&quot;&gt;using System;&lt;br /&gt;using Microsoft.Pex.Framework;&lt;br /&gt;using Microsoft.Pex.Framework.Validation;&lt;br /&gt;&lt;br /&gt;namespace ConsoleApplication3&lt;br /&gt;{&lt;br /&gt;    class Stack&lt;br /&gt;    {&lt;br /&gt;        int[] _elements;&lt;br /&gt;        int _count;&lt;br /&gt;        public Stack(int capacity)&lt;br /&gt;        {&lt;br /&gt;            if (capacity &amp;lt; 0) throw new ArgumentOutOfRangeException();&lt;br /&gt;            _elements = new int[capacity];&lt;br /&gt;            _count = 0;&lt;br /&gt;        }&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    [PexClass]&lt;br /&gt;    public partial class StackTest&lt;br /&gt;    {&lt;br /&gt;        [PexMethod]&lt;br /&gt;        [PexAllowedException(typeof(ArgumentOutOfRangeException))]&lt;br /&gt;        public void CtorTest(int capacity) // will not fail&lt;br /&gt;        {&lt;br /&gt;            Stack s = new Stack(capacity); // may throw ArgumentOutOfRangeException&lt;br /&gt;        }&lt;br /&gt;    }&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;li&gt;&lt;strong&gt;PexAllowedExceptionFromTypeAttribute&lt;/strong&gt; indicates that any method of a specified type can throw a particular type of exception for some test inputs. &lt;pre class=&quot;prettyprint lang-cs&quot;&gt;using System;&lt;br /&gt;using System.Collections;&lt;br /&gt;using Microsoft.Pex.Framework;&lt;br /&gt;using Microsoft.Pex.Framework.Validation;&lt;br /&gt;&lt;br /&gt;namespace ConsoleApplication3&lt;br /&gt;{&lt;br /&gt;    [PexClass]&lt;br /&gt;    public partial class ArrayListTest&lt;br /&gt;    {&lt;br /&gt;        [PexMethod]&lt;br /&gt;        [PexAllowedExceptionFromType(typeof(NullReferenceException), typeof(ArrayListTest))]&lt;br /&gt;        public void Add1(ArrayList a, object o) //will not fail&lt;br /&gt;        {&lt;br /&gt;            a.Add(o);&lt;br /&gt;        }&lt;br /&gt;    }&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;li&gt;&lt;strong&gt;PexAllowedExceptionFromTypeUnderTestAttribute&lt;/strong&gt; indicates that any method of the designated type under test can throw a particular type of exception for some test inputs. &lt;br /&gt;&lt;li&gt;&lt;strong&gt;PexAllowedExceptionFromAssemblyAttribute&lt;/strong&gt; indicates that any method located in a specified assembly can throw a particular type of exception for some test inputs.&lt;/li&gt;&lt;/ul&gt;&lt;br /&gt;&lt;h3&gt;&lt;a name=&quot;_Toc255301736&quot;&gt;When Does Pex Emit a Test Case?&lt;/a&gt;&lt;/h3&gt;&lt;br /&gt;&lt;p&gt;Pex supports different filters that decide when generated test inputs will be emitted as a test case. You can configure these filters with the &lt;strong&gt;&lt;a href=&quot;http://research.microsoft.com/en-us/um/redmond/projects/pex/wiki/TestEmissionFilter.html&quot; target=&quot;_blank&quot;&gt;TestEmissionFilter&lt;/a&gt;&lt;/strong&gt; property that you can set for example in the &lt;strong&gt;PexMethod&lt;/strong&gt; attribute. Possible values are the following:&lt;/p&gt;&lt;br /&gt;&lt;ul&gt;&lt;br /&gt;&lt;li&gt;&lt;strong&gt;All&lt;/strong&gt; Emit every generated test input as a test case, including those that cause assumption violations. &lt;br /&gt;&lt;li&gt;&lt;strong&gt;FailuresAndIncreasedBranchHits&lt;/strong&gt; (&lt;font color=&quot;#ff0000&quot;&gt;&lt;u&gt;default&lt;/u&gt;&lt;/font&gt;) Emit tests for all unique failures, and whenever a test case increases coverage, as controlled by the TestEmissionBranchHits property (take values 1 or 2). &lt;br /&gt;&lt;li&gt;&lt;strong&gt;FailuresAndUniquePaths&lt;/strong&gt; Emit tests for all failures Pex finds, and also for each test input that causes a unique execution path. &lt;br /&gt;&lt;li&gt;&lt;strong&gt;Failures&lt;/strong&gt; Emit tests for failures only.&lt;/li&gt;&lt;/ul&gt;&lt;br /&gt;&lt;p&gt;Regarding increased branch coverage, the TestEmissionBranchHits property controls how a branch is covered. For example: &lt;br /&gt;&lt;ul&gt;&lt;br /&gt;&lt;li&gt;&lt;strong&gt;TestEmissionBranchHits=1&lt;/strong&gt;: Whether Pex should just consider whether a branch was covered at all. This gives a very small test suite that covers all branches Pex could reach. In particular, this test suite also covers all reached basic blocks and statements. &lt;br /&gt;&lt;li&gt;&lt;strong&gt;TestEmissionBranchHits=2&lt;/strong&gt;: Whether a test covered it either once or twice.&lt;/li&gt;&lt;/ul&gt;&lt;br /&gt;&lt;p&gt;The default is TestEmissionBranchHits=2, which generates a more expressive test suite that is also better suited to detect future regression errors. &lt;pre class=&quot;prettyprint lang-cs&quot;&gt;using System;&lt;br /&gt;using Microsoft.Pex.Framework;&lt;br /&gt;using Microsoft.Pex.Framework.Settings;&lt;br /&gt;&lt;br /&gt;namespace ConsoleApplication3&lt;br /&gt;{&lt;br /&gt;    [PexClass]&lt;br /&gt;    partial class TestEmission&lt;br /&gt;    {&lt;br /&gt;        int max(int x, int y)&lt;br /&gt;        {&lt;br /&gt;            if (x &amp;gt; y)&lt;br /&gt;                return x;&lt;br /&gt;            else&lt;br /&gt;                return y;&lt;br /&gt;        }&lt;br /&gt;&lt;br /&gt;        [PexMethod(TestEmissionFilter=Microsoft.Pex.Framework.Settings.PexTestEmissionFilter.All)]&lt;br /&gt;        public void MaxTest1(int a, int b, int c, int d)    // 1 test case generated&lt;br /&gt;        {&lt;br /&gt;            int e = max(a, b);&lt;br /&gt;            PexObserve.ValueForViewing(&quot;max&quot;, e);&lt;br /&gt;        }&lt;br /&gt;&lt;br /&gt;        [PexMethod(TestEmissionFilter = Microsoft.Pex.Framework.Settings.PexTestEmissionFilter.Failures)]&lt;br /&gt;        public void MaxTest2(int a, int b, int c, int d)    // No test cases generated &lt;br /&gt;        {&lt;br /&gt;            int e = max(a, b);&lt;br /&gt;            PexObserve.ValueForViewing(&quot;max&quot;, e);&lt;br /&gt;        }&lt;br /&gt;    }&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;h3&gt;When Does Pex Stop ? &lt;/h3&gt;&lt;br /&gt;&lt;p&gt;If the code under test does not contain loops or unbounded recursion, Pex will typically stop quickly because there is only a (small) finite number of execution paths to analyze. However, most interesting programs contain loops and/or unbounded recursion. In such cases the number of execution paths is (practically) infinite, and it is in general undecidable whether a statement is reachable. In other words, Pex would take forever to analyze all execution paths of the program. &lt;br /&gt;&lt;p&gt;In order to make sure that Pex terminates after a reasonable amount of time, there are several exploration bounds. All bounds have predefined default values, which you can override to let Pex analyze more and longer execution paths. The bounds are parameters of the PexMethod, PexClass, and PexAssemblySettings attributes. There are different kinds of bounds: &lt;br /&gt;&lt;ul&gt;&lt;br /&gt;&lt;li&gt;&lt;strong&gt;Constraint Solving Bounds:&lt;/strong&gt; apply to each attempt of Pex to determine whether an execution path is feasible or not. Pex might need several constraint solving attempts to compute the next test inputs. &lt;br /&gt;&lt;ul&gt;&lt;br /&gt;&lt;li&gt;&lt;strong&gt;ConstraintSolverTimeOut&lt;/strong&gt; Seconds the constraint solver has to figure out inputs that will cause a different execution path to be taken. &lt;br /&gt;&lt;li&gt;&lt;strong&gt;ConstraintSolverMemoryLimit&lt;/strong&gt; Megabytes the constraint solver can use to figure out inputs.&lt;/li&gt;&lt;/ul&gt;&lt;br /&gt;&lt;li&gt;&lt;strong&gt;Exploration Path Bounds:&lt;/strong&gt; apply to each execution path that Pex executes and monitors. These bounds make sure that the program does not get stuck in an infinite loop, or recursive method. &lt;br /&gt;&lt;ul&gt;&lt;br /&gt;&lt;li&gt;&lt;strong&gt;MaxBranches&lt;/strong&gt; Maximum number of branches that can be taken along a single execution path. &lt;br /&gt;&lt;li&gt;&lt;strong&gt;MaxCalls&lt;/strong&gt; Maximum number of calls that can be taken during a single execution path. &lt;br /&gt;&lt;li&gt;&lt;strong&gt;MaxStack&lt;/strong&gt; Maximum size of the stack at any time during a single execution path, measured in number of active call frames. &lt;br /&gt;&lt;li&gt;&lt;strong&gt;MaxConditions&lt;/strong&gt; Maximum number of conditions over the inputs that can be checked during a single execution path.&lt;/li&gt;&lt;/ul&gt;&lt;br /&gt;&lt;li&gt;&lt;strong&gt;Exploration Bounds&lt;/strong&gt; apply to the exploration of each parameterized unit test. &lt;br /&gt;&lt;ul&gt;&lt;br /&gt;&lt;li&gt;&lt;strong&gt;MaxRuns&lt;/strong&gt; Maximum number of runs that will be tried during an exploration (each run uses different test inputs; not every run will result in the emission of a new test case). &lt;br /&gt;&lt;li&gt;&lt;strong&gt;MaxRunsWithoutNewTests &lt;/strong&gt;Maximum number of consecutive runs without a new test being emitted. &lt;br /&gt;&lt;li&gt;&lt;strong&gt;MaxRunsWithUniquePaths &lt;/strong&gt;Maximum number of runs with unique execution paths that will be tried during an exploration. &lt;br /&gt;&lt;li&gt;&lt;strong&gt;MaxExceptions&lt;/strong&gt; Maximum number of exceptions that can be found over all discovered execution paths combined. &lt;br /&gt;&lt;li&gt;&lt;strong&gt;MaxExecutionTreeNodes&lt;/strong&gt; Maximum number of conditions over the inputs that can be checked during all discovered execution paths combined. &lt;br /&gt;&lt;li&gt;&lt;strong&gt;MaxWorkingSet&lt;/strong&gt; Maximum size of working set in megabytes. &lt;br /&gt;&lt;li&gt;&lt;strong&gt;TimeOut&lt;/strong&gt; Seconds after which exploration stops.&lt;/li&gt;&lt;/ul&gt;&lt;/li&gt;&lt;/ul&gt;&lt;br /&gt;&lt;p&gt;The following example shows a parameterized test that involves a loop. The loop bound depends on the test inputs, and the exception can only be triggered if the loop is executed a certain number of times. Here, we used an explicit bound of 10 runs &lt;em&gt;MaxRuns=10 &lt;/em&gt;to let Pex finish quickly. However, with this bound, Pex will most likely not be able to trigger the exception, as Pex will not unroll the loop sufficiently many times:&lt;/p&gt;&lt;pre class=&quot;prettyprint lang-cs&quot;&gt; [PexMethod(MaxRuns = 10)]&lt;br /&gt;        public void TestWithLoop(int n)&lt;br /&gt;        {&lt;br /&gt;            var sum = 0;&lt;br /&gt;            for (int i = 0; i &amp;lt; n; i++)&lt;br /&gt;                sum++;&lt;br /&gt;            if (sum &amp;gt; 20) throw new Exception();&lt;br /&gt;        } &lt;br /&gt; &lt;/pre&gt;&lt;br /&gt;&lt;p&gt;In the Pex Exploration Results you may see the Exception statement reached, but you will see on the Pex tool bar that there is 1 boundry reached. &lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiYblGnaDT0dJuzLTDM43MnDVQNMlclKzedQBopf6Fx-9eBxiW0KLcq1TlyACw5uEd0wR1PLBk31HQ3Buk5c1NnEozaQ3t0ZTXPgqm5dkgAFxHE5FoVjd5NmvzOdyqKTiaGxD2WFD_1_g/s1600-h/ConsoleApplication2%252520-%252520Microsoft%252520Visual%252520Studio_2013-04-28_15-01-11%25255B2%25255D.jpg&quot;&gt;&lt;img style=&quot;background-image: none; border-right-width: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px&quot; title=&quot;ConsoleApplication2 - Microsoft Visual Studio_2013-04-28_15-01-11&quot; border=&quot;0&quot; alt=&quot;ConsoleApplication2 - Microsoft Visual Studio_2013-04-28_15-01-11&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEi7jQU-dWLUkJqKHlbGdQp25bIGXn_vvWDBlxD1oLRbPPOXDGWxQ_7kEusjbxOtdOO3YPSFjlyl0qBNvKJimZcNFX43L0uQXeeZhMoMZkTm6CUgG4shjSJM71CNAnWS52xvAmVLfF4WLw/?imgmax=800&quot; width=&quot;180&quot; height=&quot;86&quot;&gt;&lt;/a&gt; If you click on it, you will see more details:&lt;br&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiStRYiTTXzCuwRTVN4Gcmx6-yb5YOhPh8kEXQJz2HpU0JpB8W_3a6gBuSVqvoI8CnJox7ubLbltC9J-wjL8JXrR9gSuQVzKh5lxeW8R5zkBnw2JdLgxROA9UZUNmYQqjPltGDOYsYYwg/s1600-h/ConsoleApplication2%252520-%252520Microsoft%252520Visual%252520Studio_2013-04-28_15-04-15%25255B3%25255D.jpg&quot;&gt;&lt;img style=&quot;background-image: none; border-right-width: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px&quot; title=&quot;ConsoleApplication2 - Microsoft Visual Studio_2013-04-28_15-04-15&quot; border=&quot;0&quot; alt=&quot;ConsoleApplication2 - Microsoft Visual Studio_2013-04-28_15-04-15&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgbsa9oHbfvhUp2EoAzr05LBy8Rmfv5GJzMMzn4t1VzLSw2w4796WgsA4AlgEoSYzCn1XA9B2tBgJb4Nv8FM_rzgATEyOEelNvdMjlDlwdSm5G1dqtSt_0NLHH2rjqUPu19sphft_g-gQ/?imgmax=800&quot; width=&quot;601&quot; height=&quot;238&quot;&gt;&lt;/a&gt;&lt;br&gt;on the right, you could click Set MaxRuns=20 to increase the MaxRuns boundry. You could do the same from the Pex tool bar &lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgito0hAgSLNloC9olgBYXKwWS8gw8q_G9jJoc2_tSPbjzRDsbhgt8_rBr1L0Bj8S7g224VyJADmooYmTg5iO8VJ5tCBS8bWjvqk4kTP8LPycH1wk-AOCYcDuT2u9gMngy3TD-y28zfkA/s1600-h/ConsoleApplication2%252520-%252520Microsoft%252520Visual%252520Studio_2013-04-28_15-15-32%25255B2%25255D.jpg&quot;&gt;&lt;img style=&quot;background-image: none; border-right-width: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px&quot; title=&quot;ConsoleApplication2 - Microsoft Visual Studio_2013-04-28_15-15-32&quot; border=&quot;0&quot; alt=&quot;ConsoleApplication2 - Microsoft Visual Studio_2013-04-28_15-15-32&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEid5InQjKrXs5H1h4QRU0AbM6eSytz9Vd2hUTHoj3wDOgmc0J9OBgAn08V7Risf_lBrMzhstIsIE6rCh1laa7AD48Y3az52SpPqYFKttuHeCH0xGkmexP-OljBR8anAs62lMKvQrZ7Y-g/?imgmax=800&quot; width=&quot;220&quot; height=&quot;91&quot;&gt;&lt;/a&gt; and also setting boundary to infinity. Both actions will open a dialog to review and approve the code changes. &lt;br /&gt;&lt;p&gt;The following example shows another parameterized test that involves a loop, but this loop does not depend on the test inputs. Here, we used an explicit bound of 10 branches &lt;em&gt;MaxBranches=10&lt;/em&gt; to let Pex finish quickly. However, with this bound, Pex cannot even once execute the code from beginning to end, as executing the embedded loop will cause more than 10 branches to be executed.&lt;/p&gt;&lt;pre class=&quot;prettyprint lang-cs&quot;&gt; [PexMethod(MaxBranches = 10)]&lt;br /&gt;        public void TestWithFixedLoop(int j)&lt;br /&gt;        {&lt;br /&gt;            var sum = 0;&lt;br /&gt;            for (int i = 0; i &amp;lt; 15; i++)&lt;br /&gt;                sum++;&lt;br /&gt;            if (j == 10) throw new Exception();&lt;br /&gt;        }&lt;br /&gt; &lt;/pre&gt;&lt;br /&gt;&lt;p&gt;In those cases, where a particular run exceeded some path-specific bounds, we get a special row in the results. &lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjP-NuzHNVdmDan6j9dy6VigwdhnmA8K8WLklU49W2eHdDjMhoDI65G8kbO81RHalwIaGke0fKJppxBzdy-ImhRbr6YABXIoW-sSrgWkLdrVKwRO0Q9pymE-V8L2AyQhTp5AkHEQdZHkg/s1600-h/ConsoleApplication2%252520-%252520Microsoft%252520Visual%252520Studio_2013-04-28_15-28-43%25255B2%25255D.jpg&quot;&gt;&lt;img style=&quot;background-image: none; border-right-width: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px&quot; title=&quot;ConsoleApplication2 - Microsoft Visual Studio_2013-04-28_15-28-43&quot; border=&quot;0&quot; alt=&quot;ConsoleApplication2 - Microsoft Visual Studio_2013-04-28_15-28-43&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEj8-rQMbYnYaLaaWcJ8eAiv6alg-FccKSxZXSJvmJgjSLE7e-bgLhqaD9m2sCxePJZbQ20nZpPaOZpWARySPMVwaCnd9nxhHTE2INfqom8gUmAuJrL5Ryq0UeZRG22rMQzjn1cAXk4JTQ/?imgmax=800&quot; width=&quot;216&quot; height=&quot;51&quot;&gt;&lt;/a&gt; The Set MaxBranches= button on the results tool can be used to increase the bounds.&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhldaoiKtMug5Vrhnc5dK3zBgpeKueJN9bW1HVBjdpadW077319DudG_8KkFR_s_K-9lzTGMJKGkAinXQSK0lcDJMTOnUJ5kXR_wB8qrQQ7kE2oraffB5T5UScafyxSLJfUVmHhmS8yeQ/s1600-h/ConsoleApplication2%252520-%252520Microsoft%252520Visual%252520Studio_2013-04-28_15-31-57%25255B2%25255D.jpg&quot;&gt;&lt;img style=&quot;background-image: none; border-bottom: 0px; border-left: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top: 0px; border-right: 0px; padding-top: 0px&quot; title=&quot;ConsoleApplication2 - Microsoft Visual Studio_2013-04-28_15-31-57&quot; border=&quot;0&quot; alt=&quot;ConsoleApplication2 - Microsoft Visual Studio_2013-04-28_15-31-57&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEi9hiEZUP5vAZuD1_G2cj_-VWn7rddeTTmD9T5tOboaoG9X9CwtOhaW-Y6V5Y4JDEGk8casYbaoO-4-vr8dweRnXZPy5ItOSfAS1dn7LCUTHrocnbuGOYi3oTbE3GTrvWinzhctcyYxjA/?imgmax=800&quot; width=&quot;229&quot; height=&quot;94&quot;&gt;&lt;/a&gt; If you increased the boundary to 20, you will get all you branched executed and the exception statement reached.&lt;br /&gt;&lt;p&gt;In this post we talked about how and when a test case fail, how to use precondition and assumptions to differentiate between failures from your unit code and failures from malformed input, how to allow specific exception to be raised from your tests without causing it to fail, how to control which test inputs should Pex use as a test case, and finally how to control the Pex stop criteria whether through&amp;nbsp; bounding the constraint solver, or bounding the exploration paths, or bounding the exploration runs.&lt;/p&gt;  </description><link>http://ebeid-soliman.blogspot.com/2013/04/microsoft-pex-understanding-assumptions.html</link><author>noreply@blogger.com (Ebeid Soliman ElSayed)</author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhE_JIr1jcWXKwavO2Lx5X9o1d7p_eUmCP8jnNJBDei3mk08fmzM13AHscR6tq1tU6-1jHSKyRYLq-oMXvbqjKOvqpv01YaPQJyRcgPIzXKbiLQke5nC0jxPBMPoALXMWfPxfQ8opK8gg/s72-c?imgmax=800" height="72" width="72"/></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-59384554657271185.post-1812192897765606868</guid><pubDate>Fri, 26 Apr 2013 08:00:00 +0000</pubDate><atom:updated>2013-04-26T03:00:08.510-05:00</atom:updated><category domain="http://www.blogger.com/atom/ns#">Microsoft Pex</category><title>Getting started with Microsoft Code Digger</title><description>&lt;p&gt;Microsoft Code Digger is Visual Studio 2012 extension that have been released few days ago by RiSE team at Microsoft Research (the same team who developed Pex). You can download the it from the Visual Studio Gallery &lt;a href=&quot;http://visualstudiogallery.msdn.microsoft.com/fb5badda-4ea3-4314-a723-a1975cbdabb4&quot; target=&quot;_blank&quot;&gt;here&lt;/a&gt;.&lt;/p&gt; &lt;p&gt;Microsoft Code Digger uses the same engine that Pex uses, and the same techniques under the hood (dynamic symbolic execution and constraint solvers). The only constrain that Code Digger have is that it only works on public .NET code in Portable Class Libraries. &lt;/p&gt; &lt;h3&gt;Let’s try it&lt;/h3&gt; &lt;p&gt;After installing the Code Digger extension for Visual Studio 2012, create a Portable Class Library. Let’s use the Triang() method we used in previous posts as an example here. Your code should look like:&lt;/p&gt;&lt;pre class=&quot;prettyprint lang-cs&quot;&gt;using System;&lt;br /&gt;using System.Collections.Generic;&lt;br /&gt;using System.Linq;&lt;br /&gt;using System.Text;&lt;br /&gt;&lt;br /&gt;namespace PortableClassLibrary1&lt;br /&gt;{&lt;br /&gt;    public class Class1&lt;br /&gt;    {&lt;br /&gt;        public static int Triang(int Side1, int Side2, int Side3)&lt;br /&gt;        {&lt;br /&gt;            int triOut;&lt;br /&gt;&lt;br /&gt;            // triOut is output from the routine:&lt;br /&gt;            //   Triang = 1 if triangle is scalene&lt;br /&gt;            //   Triang = 2 if triangle is isosceles&lt;br /&gt;            //   Triang = 3 if triangle is equilateral&lt;br /&gt;            //   Triang = 4 if not a triangle&lt;br /&gt;&lt;br /&gt;            // A quick confirmation that it&#39;s a valid triangle&lt;br /&gt;            if (Side1 &amp;lt;= 0 || Side2 &amp;lt;= 0 || Side3 &amp;lt;= 0)&lt;br /&gt;            {&lt;br /&gt;                triOut = 4;&lt;br /&gt;                return (triOut);&lt;br /&gt;            }&lt;br /&gt;&lt;br /&gt;            // Detect any sides of equal sides&lt;br /&gt;            triOut = 0;&lt;br /&gt;            if (Side1 == Side2)&lt;br /&gt;                triOut = triOut + 1;&lt;br /&gt;            if (Side1 == Side3)&lt;br /&gt;                triOut = triOut + 2;&lt;br /&gt;            if (Side2 == Side3)&lt;br /&gt;                triOut = triOut + 3;&lt;br /&gt;            if (triOut == 0)&lt;br /&gt;            {&lt;br /&gt;                if ((Side1 + Side2 &amp;lt;= Side3) || (Side2 + Side3 &amp;lt;= Side1) || (Side1 + Side3 &amp;lt;= Side2)) // confirm that it is a valid triangle &lt;br /&gt;                    triOut = 4;&lt;br /&gt;                else&lt;br /&gt;                    triOut = 1;&lt;br /&gt;                return (triOut);&lt;br /&gt;            }&lt;br /&gt;&lt;br /&gt;            if (triOut &amp;gt; 3)&lt;br /&gt;                triOut = 3;&lt;br /&gt;            else if ((triOut == 1) &amp;amp;&amp;amp; (Side1 + Side2 &amp;gt; Side3))&lt;br /&gt;                triOut = 2;&lt;br /&gt;            else if ((triOut == 2) &amp;amp;&amp;amp; (Side1 + Side3 &amp;gt; Side2))&lt;br /&gt;                triOut = 2;&lt;br /&gt;            else if ((triOut == 3) &amp;amp;&amp;amp; (Side2 + Side3 &amp;gt; Side1))&lt;br /&gt;                triOut = 2;&lt;br /&gt;            else&lt;br /&gt;                triOut = 4;&lt;br /&gt;            return (triOut);&lt;br /&gt;        }&lt;br /&gt;    }&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;p&gt;Right click inside Triang() method and wait for few seconds. You will see the below Inputs / Outputs pane.&lt;/p&gt;&lt;br /&gt;&lt;p&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgNEcipgiWFyGCJ3opXnfLqNOsy91dwy7e2JYzxIBPKDE6nrk8c2gN_FeRxFqa_9KmSCwak8HPTewT1Zhdl1fGZCUQ8sB6chnVw9PeVE9OZBOtaP5rf7swtKktEtT9wR497JbdXZmhpwA/s1600-h/PortableClassLibrary1%252520-%252520Microsoft%252520Visual%252520Studio_2013-04-24_14-17-51%25255B4%25255D.jpg&quot;&gt;&lt;img style=&quot;background-image: none; border-right-width: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px&quot; title=&quot;PortableClassLibrary1 - Microsoft Visual Studio_2013-04-24_14-17-51&quot; border=&quot;0&quot; alt=&quot;PortableClassLibrary1 - Microsoft Visual Studio_2013-04-24_14-17-51&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjUU3ne3xMp-kQSGfJXgsQ1sX8mTeah_AsFGmOjt1xH-F759a9JlLS3jfpoYn_p8D7jPNHWR0HQ5Cdta6sVNinqKpPUJMocNUT6Ngi_N05AATicFHxG4tXWpuJ7rO5mQK4pg0K5W9qcaQ/?imgmax=800&quot; width=&quot;455&quot; height=&quot;221&quot;&gt;&lt;/a&gt;&amp;nbsp;&lt;/p&gt;&lt;br /&gt;&lt;p&gt;It’s the same set we got before from Pex and for the same reasons. No surprises, both tools use the same engine under hood.&lt;/p&gt;  </description><link>http://ebeid-soliman.blogspot.com/2013/04/getting-started-with-microsoft-code.html</link><author>noreply@blogger.com (Ebeid Soliman ElSayed)</author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjUU3ne3xMp-kQSGfJXgsQ1sX8mTeah_AsFGmOjt1xH-F759a9JlLS3jfpoYn_p8D7jPNHWR0HQ5Cdta6sVNinqKpPUJMocNUT6Ngi_N05AATicFHxG4tXWpuJ7rO5mQK4pg0K5W9qcaQ/s72-c?imgmax=800" height="72" width="72"/></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-59384554657271185.post-4891053290521131408</guid><pubDate>Thu, 25 Apr 2013 08:00:00 +0000</pubDate><atom:updated>2013-04-25T13:54:09.601-05:00</atom:updated><category domain="http://www.blogger.com/atom/ns#">Microsoft Pex</category><title>Why Pex Choose These Inputs</title><description>&lt;p&gt;In the example we gave in the previous post, it may seem that Pex chose random numbers as inputs for the Triang() method but it is not. But also its not all possible values for the inputs. &lt;/p&gt; &lt;p&gt;Actually, Pex generates test inputs by analyzing your program code, so it is called whitebox test generation (as opposed to blackbox test generation). For every statement in the code, Pex will eventually try to create a test input that will reach that statement. Pex will do a case analysis for every conditional branch in the code—for example, if statements, assertions, and all operations that can throw exceptions.&lt;/p&gt; &lt;p&gt;In other words, the number of test inputs that Pex generates depends on the number and possible combinations of conditional branches in the code (if interested to know more about that, search for &lt;a href=&quot;http://en.wikipedia.org/wiki/Symbolic_execution&quot; target=&quot;_blank&quot;&gt;symbolic execution&lt;/a&gt;). Pex operates in a feedback loop: it executes the code multiple times and learns about the program behavior by monitoring the control and data flow. &lt;/p&gt; &lt;p&gt;After each run, Pex does the following:  &lt;ul&gt; &lt;li&gt;Chooses a branch that was not covered previously.  &lt;li&gt;Builds a constraint system that describes how to reach that branch.  &lt;li&gt;Uses a constraint solver to determine new test inputs that fulfill the constraints, if any exist. &lt;/li&gt;&lt;/ul&gt; &lt;p&gt;The test is executed again with the new inputs, and the process repeats. On each run, Pex might discover new code and dig deeper into the implementation. In this way, Pex explores the behavior of the code.&amp;nbsp; &lt;p&gt;Because our code doesn’t have any conditions that test zero length sides, Pex generated zero an input and also shows that our program is defective (because it considers a triangle with (0,0,0) as equilateral and (1,0,1) as isosceles). If we added the following lines of code after declaring triOut and before doing anything.  &lt;p&gt;&lt;pre class=&quot;prettyprint lang-cs&quot;&gt;            &lt;br&gt;// A quick confirmation that it&#39;s a valid triangle            &lt;br&gt;if (Side1 &amp;lt;= 0 || Side2 &amp;lt;= 0 || Side3 &amp;lt;= 0)      &lt;br&gt;{&lt;br&gt; triOut = 4;&lt;br&gt; return (triOut);&lt;br&gt;}&lt;br&gt;&lt;/pre&gt;&lt;br /&gt;&lt;p&gt;You will get a different set of test inputs from Pex that reveal more code path combinations.&lt;/p&gt;&lt;br /&gt;&lt;p&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjxh2KvPB7AKEx9pwoU-FRkma7sMJ65HhhsOCwsYBbuOnvJqLATul4gyLvdirQ9vAk6MZaQHo6z5k2xjzW8xlJi4Vra4Gv3o2zvdsRR6F3PzKBNXgSQTN65slJqEgOdkOz_KxjuAtmwHw/s1600-h/ConsoleApplication2%252520-%252520Microsoft%252520Visual%252520Studio_2013-04-24_13-06-48%25255B3%25255D.jpg&quot;&gt;&lt;img style=&quot;background-image: none; border-right-width: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px&quot; title=&quot;ConsoleApplication2 - Microsoft Visual Studio_2013-04-24_13-06-48&quot; border=&quot;0&quot; alt=&quot;ConsoleApplication2 - Microsoft Visual Studio_2013-04-24_13-06-48&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiTgNIXaBamP7OmmVOYoA_-E3tXask4iMLstkVgJBZrMp8qIgRKx-XQ6AGTKMBwyIbsXR1BuSThqQjXSq4LZYNXZJrdOVyDgBDK6M2o2_MFrC_S_GMRqx6Au_FDvNMqnDoOWx2EhA8vTw/?imgmax=800&quot; width=&quot;320&quot; height=&quot;255&quot;&gt;&lt;/a&gt;&lt;/p&gt;&lt;br /&gt;&lt;p&gt;We mentioned before that pex generates test input by performing a symoblic analysis of the code under test. You can use the method &lt;strong&gt;GetPathConditionString&lt;/strong&gt; of the &lt;strong&gt;PexSymbolicValue&lt;/strong&gt; class to obtain a textual representation of the current path condition, a predicate (condition) that characterizes an execution path. The &lt;strong&gt;ToString&lt;/strong&gt; method of &lt;strong&gt;PexSymbolicValue&lt;/strong&gt; class gives you a textual representation of how a value was derived from the test input provided. To do so, add reference to Pex Framework dll (located at &quot;C:\Program Files\Microsoft Moles\PublicAssemblies\Microsoft.Pex.Framework.dll&quot;). Add &lt;strong&gt;&lt;em&gt;using Microsoft.Pex.Framework;&lt;/em&gt;&lt;/strong&gt; to your code then add the following code anywhere in your code to get details about the code path at that point. &lt;/p&gt;&lt;pre class=&quot;prettyprint lang-cs&quot;&gt;&lt;br&gt; PexObserve.ValueForViewing(&quot;Condition&quot;, PexSymbolicValue.GetPathConditionString());&lt;br&gt; PexObserve.ValueForViewing(&quot;Return Value&quot;, PexSymbolicValue.ToString(Triang(1, 1, 1)) );&lt;br&gt;&lt;/pre&gt;&lt;br /&gt;&lt;p&gt;Here I added it into the Triang() method we used before. Run Pex and you will see the new columns added to the results populated with conditions that led to .&lt;/p&gt;&lt;br /&gt;&lt;p&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjFYXoy7LVrlzCVGf7OgDXx_oUuiJ_kQvodyCEWLdF10f3LqHfg16Pb5O3y_NLFm9qHkXHL6-A8i1QXszuRCLY0QIlD84tM0CVn7I-9TeuVRydnLhLGf4Rv98pvDW-r-e88BQa1ahs3hQ/s1600-h/ConsoleApplication2%252520-%252520Microsoft%252520Visual%252520Studio_2013-04-25_11-49-50%25255B4%25255D.jpg&quot;&gt;&lt;img style=&quot;background-image: none; border-right-width: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px&quot; title=&quot;ConsoleApplication2 - Microsoft Visual Studio_2013-04-25_11-49-50&quot; border=&quot;0&quot; alt=&quot;ConsoleApplication2 - Microsoft Visual Studio_2013-04-25_11-49-50&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhLzc2HFYSUpl9taRgSYa0aqpTJpEv2p7b3XtUWeM3ZtLaiNDNZhm2sQdl62w_NRzGoH03-1Vmj-t-k-u5tHaIT2jpVj7ZoFa_pvD_-pL9-Al0erDyGiYNRa8wqn9qR13yRXNBtR9ZXEg/?imgmax=800&quot; width=&quot;539&quot; height=&quot;232&quot;&gt;&lt;/a&gt;&lt;/p&gt;&lt;br /&gt;&lt;p&gt;&lt;strong&gt;ToRawString&lt;/strong&gt; method and &lt;strong&gt;GetRawPathConditionString&lt;/strong&gt; method return expressions representing symbolic values and the path condition, formatted as &lt;a href=&quot;http://en.wikipedia.org/wiki/S-expression&quot; target=&quot;_blank&quot;&gt;S-expressions&lt;/a&gt;.&lt;/p&gt;&lt;br /&gt;&lt;p&gt;Method PexObserve.ValueForViewing can also be used to display the value picked by Pex for any variable at any point in your code. &lt;/p&gt;&lt;br /&gt;&lt;p&gt;The same engine Pex uses is now available as part of &lt;a href=&quot;http://research.microsoft.com/en-us/projects/codedigger/default.aspx&quot; target=&quot;_blank&quot;&gt;Code Digger&lt;/a&gt;, a Visual Studio 2012 extension. We will talk about it in a future post.&lt;/p&gt;  </description><link>http://ebeid-soliman.blogspot.com/2013/04/why-pex-choose-these-inputs.html</link><author>noreply@blogger.com (Ebeid Soliman ElSayed)</author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiTgNIXaBamP7OmmVOYoA_-E3tXask4iMLstkVgJBZrMp8qIgRKx-XQ6AGTKMBwyIbsXR1BuSThqQjXSq4LZYNXZJrdOVyDgBDK6M2o2_MFrC_S_GMRqx6Au_FDvNMqnDoOWx2EhA8vTw/s72-c?imgmax=800" height="72" width="72"/><thr:total>0</thr:total></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-59384554657271185.post-8954316392130663203</guid><pubDate>Wed, 24 Apr 2013 08:06:00 +0000</pubDate><atom:updated>2013-04-25T13:53:19.381-05:00</atom:updated><category domain="http://www.blogger.com/atom/ns#">Microsoft Pex</category><category domain="http://www.blogger.com/atom/ns#">NUnit</category><category domain="http://www.blogger.com/atom/ns#">Parameterized Unit Tests</category><category domain="http://www.blogger.com/atom/ns#">Unit Tests</category><title>Getting started with Microsoft Pex</title><description>&lt;p&gt;&lt;a href=&quot;http://research.microsoft.com/en-us/projects/pex/&quot; target=&quot;_blank&quot;&gt;Microsoft Pex&lt;/a&gt; is a &lt;a href=&quot;http://research.microsoft.com/pubs/81193/fulltext.pdf&quot; target=&quot;_blank&quot;&gt;white box test generation for .NET&lt;/a&gt; that came out of Microsoft Research and have been successfully integrated into Visual Studio 2010. It have been a result of collaborative work between Microsoft Research and the &lt;a href=&quot;https://sites.google.com/site/asergrp/&quot; target=&quot;_blank&quot;&gt;Automated Software Engineering Research Group&lt;/a&gt; at &lt;a href=&quot;http://www.ncsu.edu/&quot; target=&quot;_blank&quot;&gt;North Carolina State University&lt;/a&gt; led by&amp;nbsp; &lt;a href=&quot;http://www.csc.ncsu.edu/faculty/xie/&quot; target=&quot;_blank&quot;&gt;Dr. Tao Xie&lt;/a&gt;.&lt;/p&gt; &lt;p&gt;You can download and install Microsoft Pex for Visual Studio 2010 from &lt;a href=&quot;http://research.microsoft.com/en-us/projects/pex/downloads.aspx&quot; target=&quot;_blank&quot;&gt;here&lt;/a&gt;. We have talked in a previous &lt;a href=&quot;http://ebeid-soliman.blogspot.com/2013/04/unit-tests-vs-parameterized-unit-tests.html&quot; target=&quot;_blank&quot;&gt;post&lt;/a&gt; about parameterized unit tests and the possibilities it brings. In this post and the following we will explore Microsoft Pex and how it can help you in understanding the input/output behavior of your code, finding inputs that cause the code-under-test to crash, and exploring parameterized unit tests to check whether your code implements the desired functionality for all inputs. &lt;/p&gt; &lt;h3&gt;Running Pex for the First Time&lt;/h3&gt; &lt;p&gt;In Visual Studio click &lt;u&gt;File&lt;/u&gt; &amp;gt; &lt;u&gt;New&lt;/u&gt; &amp;gt; &lt;u&gt;Project&lt;/u&gt;. In the left pane of the New Project dialog box, click &lt;u&gt;Visual C#&lt;/u&gt;. In the center pane, click Console Application, pick a Name for it and click &lt;u&gt;OK&lt;/u&gt;. Replace your class Program with the following class. It just the classic triangle classification program :&lt;/p&gt;&lt;pre class=&quot;prettyprint lang-cs&quot;&gt;class Program&lt;br /&gt;    {&lt;br /&gt;        public static String[] triTypes = { &quot;&quot;, // Ignore 0.&lt;br /&gt;                                               &quot;scalene&quot;, &quot;isoscelese&quot;, &quot;equilateral&quot;, &quot;not a valid triangle&quot;};&lt;br /&gt;        public static String instructions = &quot;This is the ancient TriType program.\nEnter three integers that represent the lengths of the sides of a triangle.\nThe triangle will be categorized as either scalene, isosceles, equilateral\n or invalid.\n&quot;;&lt;br /&gt;&lt;br /&gt;        public static void Main()&lt;br /&gt;        {&lt;br /&gt;            int A, B, C;&lt;br /&gt;            int T;&lt;br /&gt;&lt;br /&gt;            Console.WriteLine(instructions);&lt;br /&gt;            Console.WriteLine(&quot;Enter side 1: &quot;);&lt;br /&gt;            A = getN();&lt;br /&gt;            Console.WriteLine(&quot;Enter side 2: &quot;);&lt;br /&gt;            B = getN();&lt;br /&gt;            Console.WriteLine(&quot;Enter side 3: &quot;);&lt;br /&gt;            C = getN();&lt;br /&gt;            T = Triang(A, B, C);&lt;br /&gt;&lt;br /&gt;            Console.WriteLine(&quot;Result is: &quot; + triTypes[T]);&lt;br /&gt;            Console.ReadLine();&lt;br /&gt;        }&lt;br /&gt;&lt;br /&gt;        public static int Triang(int Side1, int Side2, int Side3)&lt;br /&gt;        {&lt;br /&gt;            int triOut;&lt;br /&gt;&lt;br /&gt;            // triOut is output from the routine:&lt;br /&gt;            //   Triang = 1 if triangle is scalene&lt;br /&gt;            //   Triang = 2 if triangle is isosceles&lt;br /&gt;            //   Triang = 3 if triangle is equilateral&lt;br /&gt;            //   Triang = 4 if not a triangle&lt;br /&gt;&lt;br /&gt;            // A quick confirmation that it&#39;s a valid triangle&lt;br /&gt;            if (Side1 &amp;lt;= 0 || Side2 &amp;lt;= 0 || Side3 &amp;lt;= 0)&lt;br /&gt;            {&lt;br /&gt;                triOut = 4;&lt;br /&gt;                return (triOut);&lt;br /&gt;            }&lt;br /&gt;&lt;br /&gt;            // Detect any sides of equal sides&lt;br /&gt;            triOut = 0;&lt;br /&gt;            if (Side1 == Side2)&lt;br /&gt;                triOut = triOut + 1;&lt;br /&gt;            if (Side1 == Side3)&lt;br /&gt;                triOut = triOut + 2;&lt;br /&gt;            if (Side2 == Side3)&lt;br /&gt;                triOut = triOut + 3;&lt;br /&gt;            if (triOut == 0)&lt;br /&gt;            {&lt;br /&gt;                if ((Side1 + Side2 &amp;lt;= Side3) || (Side2 + Side3 &amp;lt;= Side1) || (Side1 + Side3 &amp;lt;= Side2)) // confirm that it is a valid triangle &lt;br /&gt;                    triOut = 4;&lt;br /&gt;                else&lt;br /&gt;                    triOut = 1;&lt;br /&gt;                return (triOut);&lt;br /&gt;            }&lt;br /&gt;&lt;br /&gt;            if (triOut &amp;gt; 3)&lt;br /&gt;                triOut = 3;&lt;br /&gt;            else if ((triOut == 1) &amp;amp;&amp;amp; (Side1 + Side2 &amp;gt; Side3))&lt;br /&gt;                triOut = 2;&lt;br /&gt;            else if ((triOut == 2) &amp;amp;&amp;amp; (Side1 + Side3 &amp;gt; Side2))&lt;br /&gt;                triOut = 2;&lt;br /&gt;            else if ((triOut == 3) &amp;amp;&amp;amp; (Side2 + Side3 &amp;gt; Side1))&lt;br /&gt;                triOut = 2;&lt;br /&gt;            else&lt;br /&gt;                triOut = 4;&lt;br /&gt;            return (triOut);&lt;br /&gt;        }&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;p&gt;In the &lt;u&gt;Build&lt;/u&gt; menu, click &lt;u&gt;Build Solution&lt;/u&gt;.&lt;/p&gt;&lt;br /&gt;&lt;p&gt;To run Pex on your code, right-click in the body of the Triang method, and click &lt;u&gt;Run Pex&lt;/u&gt;. If this is your first time running Pex, the &lt;u&gt;Pex: Select a Test Framework&lt;/u&gt; dialog box appears. You could select your preferred test frame (Visual Studio Unit test, or NUnit)&amp;nbsp; and provide the installation path for its, then click &lt;u&gt;OK&lt;/u&gt;. This dialog box will not appear again after you select the test framework. After a brief pause, Pex shows the results of its analysis in the Pex Exploration Results window. When you run Microsoft Pex on your .NET code, Pex generates test cases by analyzing the code-under-test. For every statement in the code, Pex will eventually try to create a test input that will reach that statement. Pex will do a case analysis for every conditional branch in the code—for example, if statements, assertions, and all operations that can throw exceptions. Each row in the table contains input/output values for the method under consideration(Traing). In the Pex Exploration Results window, click one row in the table on the left to see details in the right pane. You could select these rows and save them as unit tests. These details also displayed on the right in the &lt;u&gt;Pex Explorer&lt;/u&gt; pane as test cases. &lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjEG-FKRA6Gd93tYu4oWyZ-WIvatC-noUXe3oPzbcqWWBfQ2wLI6EHXH2wqrXiHjFhSEBp9Y2yKH00j4lRZn757-iYRLOaQJQv1ytgbARGiWMmJkCkNO8KgT_VidFtyUspKl2Sw6R5M_A/s1600-h/ConsoleApplication2%252520-%252520Microsoft%252520Visual%252520Studio_2013-04-23_16-45-40%25255B6%25255D.jpg&quot;&gt;&lt;img style=&quot;background-image: none; border-right-width: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px&quot; title=&quot;ConsoleApplication2 - Microsoft Visual Studio_2013-04-23_16-45-40&quot; border=&quot;0&quot; alt=&quot;ConsoleApplication2 - Microsoft Visual Studio_2013-04-23_16-45-40&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEg1eeUwyVK7P7DAia2VmlhGdMqnnCXeG1KvFICFKEI1vNlsqt0YVw0pPz9vYNnJpe69v3wXUbjGUebjocNrLqB9t6ueWqZZlFmq_0wBF4FTv8vRusZo0s7DIjoiGqndjD5K3n8V61j1fA/?imgmax=800&quot; width=&quot;716&quot; height=&quot;624&quot;&gt;&lt;/a&gt;&lt;/p&gt;&lt;br /&gt;&lt;p&gt;On the next post we will explain why Pex chose these values, and other Pex stuff :)&lt;/p&gt;  </description><link>http://ebeid-soliman.blogspot.com/2013/04/getting-started-with-microsoft-pex.html</link><author>noreply@blogger.com (Ebeid Soliman ElSayed)</author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEg1eeUwyVK7P7DAia2VmlhGdMqnnCXeG1KvFICFKEI1vNlsqt0YVw0pPz9vYNnJpe69v3wXUbjGUebjocNrLqB9t6ueWqZZlFmq_0wBF4FTv8vRusZo0s7DIjoiGqndjD5K3n8V61j1fA/s72-c?imgmax=800" height="72" width="72"/></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-59384554657271185.post-1187183382641437833</guid><pubDate>Mon, 22 Apr 2013 22:17:00 +0000</pubDate><atom:updated>2013-04-25T05:52:01.166-05:00</atom:updated><category domain="http://www.blogger.com/atom/ns#">Microsoft Pex</category><category domain="http://www.blogger.com/atom/ns#">Parameterized Unit Tests</category><category domain="http://www.blogger.com/atom/ns#">Unit Tests</category><title>Unit Tests vs Parametrized Unit Tests</title><description>&lt;h3&gt;Unit Tests&lt;/h3&gt; &lt;p&gt;Using the conventions of NUnit unit tests as test methods contained in test classes. A parameterless method decorated with a custom attribute like [TestMethod] is a test method. Usually, each unit test explores a particular aspect of the behavior of the class-under-test.  &lt;p&gt;Here is a unit test written in C# that adds an element to a .NET ArrayList instance. The test first creates a new array list, where the parameter to the constructor is the initial capacity, then adds a new object to the array list, and finally checks that the addition was correctly performed by verifying that a subsequent index lookup operation returns the new object. &lt;/p&gt;
&lt;pre class=&quot;prettyprint lang-cs&quot;&gt;
[TestMethod] 
void TestAdd() 
{ 
 ArrayList a = new ArrayList(0); 
 object o = new object(); 
 a.Add(o); 
 Assert.IsTrue(a[0] == o); 
}
&lt;/pre&gt;
&lt;p&gt;It is important to note that unit tests include a test oracle that compares observed behavior with expected results. By convention, the test oracle of a unit test is encoded using assertions. The test fails if any assertion fails or an exception is thrown. Unit test frame- works can also deal with expected exceptions. For a quick introduction about NUnit refer previous &lt;a href=&quot;http://ebeid-soliman.blogspot.com/search/label/NUnit&quot; target=&quot;_blank&quot;&gt;posts&lt;/a&gt;. &lt;br /&gt;&lt;p&gt;A test suite produced by unit testing with high code coverage gives confidence in the correctness of the tested code. However, writing unit tests to achieve high coverage can be time-consuming and tedious given that test execution frameworks only automate the test executions. You still have to write your test cases !&lt;br /&gt;&lt;p&gt;To address this problem, several automatic unit test generation tools such as Parasoft JTest or jCUTE can automatically generate conventional unit tests. These tools, nevertheless, cannot guarantee high code coverage, unless testers manually write some tests.&lt;br /&gt;&lt;h3&gt;&amp;nbsp;&lt;/h3&gt;&lt;br /&gt;&lt;h3&gt;Parametrized Unit Tests&lt;/h3&gt;&lt;br /&gt;&lt;p&gt;The unit test above specifies the behavior of the array list by example. Strictly speaking, this unit test only says that by adding a new object to an empty array list, this object becomes the first element of the list. What about other array lists and other objects? &lt;/p&gt;
&lt;pre class=&quot;prettyprint lang-cs&quot;&gt;
[TestAxiom]
void TestAdd(ArrayList a, object o) 
{
 Assume.IsTrue(a!=null);
 int i = a.Count;
 a.Add(o);
 Assert.IsTrue(a[i] == o);
}
&lt;/pre&gt;
&lt;p&gt;By adding parameters we can turn a closed unit test into a universally quantified conditional axiom that must hold for all inputs under specified assumptions. &lt;br /&gt;&lt;p&gt;Adding parameters to a unit test improves its expressiveness as a specification of intended behavior, but we lose concrete test cases. We can no longer execute this test axiom by itself. We need actual parameters. But which values must be provided to ensure sufficient and comprehensive testing? Which values can be chosen at all? &lt;br /&gt;&lt;p&gt;In the ArrayList example, if we study the internal structure of the .NET Framework implementation, we observe that there are two cases of interest. One occurs when adding an element to an array list that already has enough room for the new element (i.e. the array list’s capacity is greater than the current number of elements in the array list). The other occurs when the internal capacity of the array list must be increased before adding the element. &lt;br /&gt;&lt;p&gt;If we assume that library methods invoked by the ArrayList implementation are themselves correctly implemented, we can deduce that running exactly two test cases is sufficient to guarantee that the parametrized TestAdd(...) succeeds for all array lists and all objects. &lt;/p&gt;
&lt;pre class=&quot;prettyprint lang-cs&quot;&gt;
[TestMethod]
void TestAddNoOverflow() 
{
 TestAdd(new ArrayList(1), new object());
}

[TestMethod]
void TestAddWithOverflow() 
{
 TestAdd(new ArrayList(0), new object());
}
&lt;/pre&gt;
&lt;p&gt;Splitting axioms and test cases in this way is a separation of concerns: &lt;br /&gt;&lt;ul&gt;&lt;br /&gt;&lt;li&gt;First, we describe expected behavior as parametrized unit tests. &lt;br /&gt;&lt;li&gt;Then we study the case distinctions made by the code paths of the program under test to determine which inputs make sense for testing.&lt;/li&gt;&lt;/ul&gt;&lt;br /&gt;&lt;p&gt;So, parametrized unit tests are more general specifications than conventional unit tests because it specifies the behavior for the whole input classes other than for a single concrete value of the input. But it needs concrete parameter values to be executed. &lt;/p&gt;&lt;br /&gt;&lt;p&gt;The good news is, Given a parametrized unit test, a test-generation tool, such as Microsoft Pex, can automatically generate tests with concrete inputs for the parameters to achieve high coverage. Pex explores the behaviors of a parametrized unit test using a technique called dynamic &lt;a href=&quot;http://en.wikipedia.org/wiki/Symbolic_execution&quot; target=&quot;_blank&quot;&gt;symbolic execution&lt;/a&gt;. Dynamic Symbolic Execution (DSE) is a variation of symbolic execution, which systematically explores feasible paths of the program under test by running the program with different test inputs to achieve high structural coverage. It collects the symbolic constraints on inputs obtained from predicates (condition statements like if else, switch,…) in branch statements along the execution and relies on a &lt;a href=&quot;http://en.wikipedia.org/wiki/Constraint_satisfaction_problem&quot; target=&quot;_blank&quot;&gt;constraint solver&lt;/a&gt; [like &lt;a href=&quot;http://research.microsoft.com/apps/pubs/default.aspx?id=70224&quot; target=&quot;_blank&quot;&gt;Zap&lt;/a&gt; or &lt;a href=&quot;http://www.hpl.hp.com/techreports/2003/HPL-2003-148.html&quot; target=&quot;_blank&quot;&gt;Simplify&lt;/a&gt;] to solve the constraints and generate new test input for exploring new path. For each set of concrete test input that leads to a new path that achieves new coverage, Pex generates a corresponding conventional unit test. So, all what you have to do is write your parametrized unit test.&lt;/p&gt;&lt;br /&gt;&lt;p&gt;In this post we gave a brief overview about parametrized unit tests and its related research areas. It’s a very important concept to understand before start learning Microsoft Pex, which we will start . In later posts, we will explore Microsoft Pex in detail.&lt;/p&gt;  </description><link>http://ebeid-soliman.blogspot.com/2013/04/unit-tests-vs-parameterized-unit-tests.html</link><author>noreply@blogger.com (Ebeid Soliman ElSayed)</author></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-59384554657271185.post-7346921535986352379</guid><pubDate>Sun, 31 Mar 2013 00:06:00 +0000</pubDate><atom:updated>2013-04-25T14:48:20.497-05:00</atom:updated><category domain="http://www.blogger.com/atom/ns#">JPF</category><category domain="http://www.blogger.com/atom/ns#">Model Checking</category><title>Getting Started with Java PathFinder</title><description>&lt;p&gt;Java™ Pathfinder, or &lt;strong&gt;&lt;em&gt;&quot;JPF&quot;&lt;/em&gt; &lt;/strong&gt;as we call it from here, is a highly customizable execution environment for verification of Java™ bytecode programs. &lt;strong&gt;&lt;a href=&quot;http://babelfish.arc.nasa.gov/trac/jpf/&quot; target=&quot;_blank&quot;&gt;JPF&lt;/a&gt;&lt;/strong&gt; was developed at the &lt;a href=&quot;http://www.arc.nasa.gov&quot;&gt;NASA Ames Research Center&lt;/a&gt;, open sourced in 2005, and is freely available &lt;a href=&quot;http://babelfish.arc.nasa.gov/trac/jpf/&quot; target=&quot;_blank&quot;&gt;here&lt;/a&gt; under the &lt;a href=&quot;http://javapathfinder.sourceforge.net/NOSA-1.3-JPF.txt&quot;&gt;NOSA 1.3&lt;/a&gt; license. &lt;strong&gt;JPF&lt;/strong&gt; started as a software model checker but it integrates model checking, program analysis and testing.&lt;/p&gt; &lt;p&gt;In this post&amp;nbsp; we will go in a step by step process to setup the&amp;nbsp; environment where Java Path Finder can be used within Eclipse IDE environment. We will show a simple example of using JPF.&lt;/p&gt; &lt;ul&gt; &lt;li&gt;Step 1. Install Eclipse  &lt;ul&gt; &lt;li&gt;Step 1.1 : Download and install the latest JDK fro your platform from &lt;a href=&quot;http://www.oracle.com/technetwork/java/javase/downloads/index.html&quot; target=&quot;_blank&quot;&gt;here&lt;/a&gt;.  &lt;li&gt;Step 1.2 : Download the latest Eclipse from &lt;a href=&quot;http://www.eclipse.org/downloads/&quot; target=&quot;_blank&quot;&gt;here&lt;/a&gt;. Once you have unzipped the previously downloaded file, you will see a folder named eclipse.&amp;nbsp; In that folder you will find the eclipse application.&amp;nbsp; We recommend you create a shortcut on the desktop to simplify the launching of eclipse.&amp;nbsp; Notice that unlike Java, Eclipse does not have an installation process. Once you have unzipped the file you are done.&lt;/li&gt;&lt;/ul&gt; &lt;li&gt;Step 2. Download JPF &lt;/li&gt; &lt;ul&gt; &lt;li&gt;Step 2.1 : Download Mercurial plug-in for Eclipse  &lt;ul&gt; &lt;li&gt;Launch Eclipse. Go to Help &amp;gt;&amp;gt; Install New Software  &lt;li&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEh27GAQtRHt2zWifcgT1ikpMxwN18KQ6nZHFCXqkl2HX3-uYOq3dk5rvy30xpLYukYaDSjkKd-TarJQPOqHczV9Vg5u52xKYRYB5nORZk8vwZtyjNWvITp9oOe6CGvIhy95Up26F-Jd3Q/s1600-h/2013-03-28%25252013_54_12-Java%252520-%252520jpf_junit_demo_src_TestGenerator.java%252520-%252520Eclipse%252520SDK%25255B3%25255D.png&quot;&gt;&lt;img title=&quot;2013-03-28 13_54_12-Java - jpf_junit_demo_src_TestGenerator.java - Eclipse SDK&quot; style=&quot;border-left-width: 0px; border-right-width: 0px; border-bottom-width: 0px; display: inline; border-top-width: 0px&quot; border=&quot;0&quot; alt=&quot;2013-03-28 13_54_12-Java - jpf_junit_demo_src_TestGenerator.java - Eclipse SDK&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjjQSIAnZR8AkQMeAc6m-iiEIHZF3HKTHOSdoLExxHVhTuhHda7WeinRESqFFQKQhckJpB5TxuIUKQZzQGMieOjmiPVKZXiJOdhDEsqawzqsfFq_DBanQK1oUIWfA65Si-92cNYHR7wyQ/?imgmax=800&quot; width=&quot;274&quot; height=&quot;211&quot;&gt;&lt;/a&gt;  &lt;li&gt;Click Add  &lt;li&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEh0td3JfZwfZy0GNebO7-vZixMhh1kxV7Zf4TcrX_GNL1CnE44YT-sH_9S3ILZPLryPZKGatnUkN9MRaThLcU37EeRpy8XsErw9A_PKLaZor479pSJ4bceoFVG07Ji3QjuazUFdr35oyA/s1600-h/2013-03-28%25252014_01_12-Install%25255B2%25255D.png&quot;&gt;&lt;img title=&quot;2013-03-28 14_01_12-Install&quot; style=&quot;border-left-width: 0px; border-right-width: 0px; border-bottom-width: 0px; display: inline; border-top-width: 0px&quot; border=&quot;0&quot; alt=&quot;2013-03-28 14_01_12-Install&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgH8apSvB38az2Wy4qOe_P_vpZf6km_Uc29Xa_tbACWSS0CqKm94RILZXaDUrCIR9RLF9k5zWM1kh4s31Vx0z9lb30EOgg4gpsoxHXXoDc89DLwW7SzPuAxgDWp2bI1xZ8nFikE3gCIEA/?imgmax=800&quot; width=&quot;244&quot; height=&quot;97&quot;&gt;&lt;/a&gt;  &lt;li&gt;Insert “Mercurial” in the Name box. Insert “&lt;a title=&quot;http://mercurialeclipse.eclipselabs.org.codespot.com/hg.wiki/update_site/stable/&quot; href=&quot;http://mercurialeclipse.eclipselabs.org.codespot.com/hg.wiki/update_site/stable/&quot;&gt;http://mercurialeclipse.eclipselabs.org.codespot.com/hg.wiki/update_site/stable/&lt;/a&gt;” in the Address box. Click Ok.  &lt;li&gt;In the install dialog select the newly added site from Work with drop down box. The list below it will show the available software at this site, select the item named MercurialEclipse and click Next, then finish..  &lt;li&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiyeaiKmC2Qgo7-heaDvCMtRKnWFY0OjX039dYOTckPeX2uhJeWhbrTpt6MVxwnbiNCdQOYUw7TfYPTdHaWXUD17ybhF866msl1A9r7E7hNxRb0ofY0o2C7o9WR18a0kgzgKFSvGg3gLg/s1600-h/2013-03-28%25252014_05_37-Install%25255B2%25255D.png&quot;&gt;&lt;img title=&quot;2013-03-28 14_05_37-Install&quot; style=&quot;border-left-width: 0px; border-right-width: 0px; border-bottom-width: 0px; display: inline; border-top-width: 0px&quot; border=&quot;0&quot; alt=&quot;2013-03-28 14_05_37-Install&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEil2okeEXs4sGyo-K_J1OzoEuPlz__82SAk-xZhyIetQQB4DpgMiWU4pixvrxgWYgD2ZSb1v_f-tsKjEgm8a37PV3P6Iv4gJL-YY1YVav6bTok089UHtvQ-spAMJ5pCMpLg1RKgSghpeA/?imgmax=800&quot; width=&quot;244&quot; height=&quot;193&quot;&gt;&lt;/a&gt; &lt;/li&gt;&lt;/ul&gt; &lt;li&gt;Step 2.2 : Download the JPF source code  &lt;ul&gt; &lt;li&gt;In Eclipse menu : File &amp;gt;&amp;gt; Import &amp;gt;&amp;gt; Mercurial &amp;gt;&amp;gt; Clone Existing Mercurial Repository &amp;gt;&amp;gt; Next.  &lt;li&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEggtVegeqquEKSl_JVpzIa1YJ7eTA6I6tylWlSWBg19KIIDusBU_4L-XJpk0b8OQI-SRVde4_Yu3xo6HpNm5Si70jqgQdaj3n-tiymFolJsNSVD3GniSgcl8sOMfSk-izWx1nhPF5vGRg/s1600-h/2013-03-28%25252014_42_31-Mercurial%252520clone%252520repository%252520wizard%25255B2%25255D.png&quot;&gt;&lt;img title=&quot;2013-03-28 14_42_31-Mercurial clone repository wizard&quot; style=&quot;border-left-width: 0px; border-right-width: 0px; border-bottom-width: 0px; display: inline; border-top-width: 0px&quot; border=&quot;0&quot; alt=&quot;2013-03-28 14_42_31-Mercurial clone repository wizard&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjifgSSmYXOYxeryVu4dHSyeB4rAfsH74K0tio7-Uz-cIb-CAiY3N-iWc2Yqu6WnBgIn2g5esuIuJA9DBAmdzMm2RzVI0q-U1op62ej6aG4e1D8nucQYehDMILd_Z13yT-BXZWHnU2kpA/?imgmax=800&quot; width=&quot;244&quot; height=&quot;172&quot;&gt;&lt;/a&gt;  &lt;li&gt;In the repository location URL, insert “&lt;a title=&quot;http://babelfish.arc.nasa.gov/hg/jpf/jpf-core&quot; href=&quot;http://babelfish.arc.nasa.gov/hg/jpf/jpf-core&quot;&gt;http://babelfish.arc.nasa.gov/hg/jpf/jpf-core&lt;/a&gt;”. Click Next, then Finish. The JPF project files will be downloaded to your local computer.&lt;/li&gt;&lt;/ul&gt; &lt;li&gt;Step 2.3 : Build the JPF &lt;/li&gt; &lt;ul&gt; &lt;li&gt;In the package explorer, select the build.xml, right click on it, select “run as” &amp;gt;&amp;gt; “Run as Ant build “.  &lt;li&gt;Eclipse will build JPF and a new folder named “build” will appear in the package explorer (it may not appear even the build was successful, double check the windows explorer for it.) &lt;/li&gt; &lt;ul&gt; &lt;li&gt;If the build failed due to error missing JDK: &lt;/li&gt; &lt;ul&gt; &lt;li&gt;On Eclipse menu : Project &amp;gt;&amp;gt; Properties. Select Builders from the lift hand side list &lt;li&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEilE28D-G1VtKtYPWdzErJJ6Of07Eoe0ZGwfeEm-5T6j0upnzHE9NpPv70SEDKsOp_FCo0ddYci8s4q8MhxHUjWSDnM29QCxrAUuPsRcfAZTe3MG8Cm01R8NYCrZKY9qbTUbEVY4Y5a2A/s1600-h/2013-03-30%25252019_52_18-Java%252520-%252520jpf_junit_demo_test_CalculatorTest.java%252520-%252520Eclipse%252520SDK%25255B2%25255D.png&quot;&gt;&lt;img title=&quot;2013-03-30 19_52_18-Java - jpf_junit_demo_test_CalculatorTest.java - Eclipse SDK&quot; style=&quot;border-top: 0px; border-right: 0px; border-bottom: 0px; border-left: 0px; display: inline&quot; border=&quot;0&quot; alt=&quot;2013-03-30 19_52_18-Java - jpf_junit_demo_test_CalculatorTest.java - Eclipse SDK&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhXkSmgi8KQ6CEH51SQSrTvtiyU2tyUnuuryU3uTO1iLE83iqjSzWuj68X5Ev7COClRojBXBbT-9ANT5C1hUGBI26pl1AkF2rKER2Iegd56EXPjQEKCcMn2kAK6J0VpS0-Y_3EBB68oqw/?imgmax=800&quot; width=&quot;244&quot; height=&quot;171&quot;&gt;&lt;/a&gt;  &lt;li&gt;Select Ant Builder and click New. &lt;li&gt;Select Ant Builder and click New. &lt;li&gt;In the Edit Configuration dialog, select the “JRE” tab, then select “Separate JRE” from the “Runtime JRE section”. In the drop down list, select JDK: &lt;li&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhWzCRjbsia3V39OfMvs289XUWWkhfypUl4wKggQl2pctZJHzEcjXnhahSj2H7yLjkGx9EVP5wf-0Ray8eW2m5vbqjF52IBncKe_onf2TPa6uNIL1BS9yOmlBmMkv9zm_LzI9zb-lP_ag/s1600-h/2013-03-30%25252020_01_41-Edit%252520Configuration%25255B2%25255D.png&quot;&gt;&lt;img title=&quot;2013-03-30 20_01_41-Edit Configuration&quot; style=&quot;border-top: 0px; border-right: 0px; border-bottom: 0px; border-left: 0px; display: inline&quot; border=&quot;0&quot; alt=&quot;2013-03-30 20_01_41-Edit Configuration&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjyYmXvATLdMmzjBlaiuwQmdaFMomlsYJ57iSV_3iICUtTq00Mnbjj_DOPV8mFOXFknX98-epPxp41uUTRfm_vcJGvcle50OKfaaFFFQt0F_2Rt7ez_nHp_MS6EZalaekdm3Bn0Zbv18w/?imgmax=800&quot; width=&quot;244&quot; height=&quot;76&quot;&gt;&lt;/a&gt;  &lt;li&gt;If you couldn’t find the JDK in the drop down list, click “Installed JRE …” &lt;li&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEg4kLXyPDgEbY23NT5U03M5zgJP8lEetxJ07-RFAV23ej45sXWwbHj4DGRrCL9LFj6ynge20p6qV-ga3lGJb80_VazSxjUCh2gOnhMZ71-jnCNWLXimJxHAcnJ6LP6Joxeaddv_0-b4jA/s1600-h/2013-03-30%25252020_05_18-Preferences%252520%252528Filtered%252529%25255B2%25255D.png&quot;&gt;&lt;img title=&quot;2013-03-30 20_05_18-Preferences (Filtered)&quot; style=&quot;border-top: 0px; border-right: 0px; border-bottom: 0px; border-left: 0px; display: inline&quot; border=&quot;0&quot; alt=&quot;2013-03-30 20_05_18-Preferences (Filtered)&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjBK1ViO7cJu5-LKUkZm9f36cFR1iftTYaqf-QkatYAcZlwyHprSByM3udI5SFl5xqZsOvoGGgF0HPMGQ_TcYvWQgfxqKM2bWLjw3jV5WxpMNTOz30MjbgbbJxmqce022ZDu3LBdPH-gw/?imgmax=800&quot; width=&quot;244&quot; height=&quot;191&quot;&gt;&lt;/a&gt;  &lt;li&gt;In the “Preferences” dialog, click “Add” &lt;li&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhfETFF4rPbpIRbP-_W2k8Q6uD8L28fHLUbic-tPec_nEFAueEEIYwLL8nMhQTnIAXxlxZJqhKrJaIKX2EkuUyDk71AlxT4x8y48Nn8EnkIq7ecKgPRn7zyMW5tpvlx_6sm_6nCCCOPzQ/s1600-h/2013-03-30%25252020_07_40-Preferences%252520%252528Filtered%252529%25255B2%25255D.png&quot;&gt;&lt;img title=&quot;2013-03-30 20_07_40-Preferences (Filtered)&quot; style=&quot;border-top: 0px; border-right: 0px; border-bottom: 0px; border-left: 0px; display: inline&quot; border=&quot;0&quot; alt=&quot;2013-03-30 20_07_40-Preferences (Filtered)&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgzRffkz9B8Y33SaG7IgseiBT63mDuOoZOyRc-CRVjpvqIHXgJwnl7Wd4_Uuatm5sXGDHwm_NBrm-YWAt_z5kCthRaLKfsRfSXkBR1rKz7QXocA_tSaxT7tVwAUYKM-G_TDTdfLoHDbPA/?imgmax=800&quot; width=&quot;237&quot; height=&quot;244&quot;&gt;&lt;/a&gt;  &lt;li&gt;Select “Standard VM” and click “Next” &lt;li&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjL3kEyu6v8HjHL62hYmQxDhKecq5B2qPiZ1sFEAVsW8o99K7q4Y9csgh-9T6Gnsk6q8puv0iKHtWJcJq9_wzeiypWNCTGDpOz5id1vLoZReC_l_nWTajIpbPjXplDQVumoGu8KlZCYuw/s1600-h/2013-03-30%25252020_10_06-Edit%252520Configuration%25255B2%25255D.png&quot;&gt;&lt;img title=&quot;2013-03-30 20_10_06-Edit Configuration&quot; style=&quot;border-top: 0px; border-right: 0px; border-bottom: 0px; border-left: 0px; display: inline&quot; border=&quot;0&quot; alt=&quot;2013-03-30 20_10_06-Edit Configuration&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiS2mJcchkyW5dDq7nlLaFbMR-5p_k1s2apnyByZaFDA5GjsE7czs070YjGP7zHI3ekFUBtJsDHzKSW5o0mcbcbIciyqSu2ufDEmiVi6WK8zglDyX4KlsfNqksxsXANYHmtuS9KVPLE2w/?imgmax=800&quot; width=&quot;244&quot; height=&quot;239&quot;&gt;&lt;/a&gt;  &lt;li&gt;Click “Directory” and navigate to your JDK installation directory. Then click “Finish” to return to the previous dialog. &lt;li&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEg6sRJ2nAC3yg7rngp0WW_3wxfdpShOmHmqpPVLKgEha-dqMXGFfLY-TTrNBrR9dJVE2NH-FfkIgOZ3luQuQst3TS-RxZinn0IjY4s-nH6VkGjxCsfeK8osclXoB7CHWVpW1B6l4-XPIQ/s1600-h/2013-03-30%25252020_11_56-Preferences%252520%252528Filtered%252529%25255B2%25255D.png&quot;&gt;&lt;img title=&quot;2013-03-30 20_11_56-Preferences (Filtered)&quot; style=&quot;border-top: 0px; border-right: 0px; border-bottom: 0px; border-left: 0px; display: inline&quot; border=&quot;0&quot; alt=&quot;2013-03-30 20_11_56-Preferences (Filtered)&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEg1Iy3SHntyTBLyyEkWH2j3_qDqFh8o6aHQCHVVgIhNYleR2tus4aN0KqKQHALEEJ0hVwcKnxTomAKHeSSQFI63OJ6FiE0vXh4zck64s_1TeWxzYSLCBiMzYnORQYrfEW7FBhH7fX_sqw/?imgmax=800&quot; width=&quot;244&quot; height=&quot;73&quot;&gt;&lt;/a&gt;&amp;nbsp;&amp;nbsp; &lt;li&gt;Select the JDK and click Ok. &lt;li&gt;Select JDK in the drop down box and click OK &lt;li&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjB3hGDDRbZNrJH175ku0Re0VqB6jEGo97LDSaV7rFftzHCHUr-gdano4OOo3aCFkmmQcswn-KOz7O_n8xvFbgR5pHOnrtZFEI_bgY6fA6MBmt_iSOw01JhnkaCVZczxIiKmwGxkt8FBA/s1600-h/2013-03-30%25252020_13_43-Edit%252520Configuration%25255B2%25255D.png&quot;&gt;&lt;img title=&quot;2013-03-30 20_13_43-Edit Configuration&quot; style=&quot;border-top: 0px; border-right: 0px; border-bottom: 0px; border-left: 0px; display: inline&quot; border=&quot;0&quot; alt=&quot;2013-03-30 20_13_43-Edit Configuration&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiKZSqz5xDWCdT-4ORSKJ3Xlw-5JEG2nt-F7wl4oj6uKNkP2z8KhGVJlJpibuiZmmUuOpPmub4YI_XbPZQoNLC1po90lGin8kxvs0rdJPD3ugyT2qTGF30GAFTVxLO4Yc-EeO4GFJBSvw/?imgmax=800&quot; width=&quot;244&quot; height=&quot;23&quot;&gt;&lt;/a&gt; &lt;/li&gt;&lt;/ul&gt;&lt;/ul&gt;&lt;/ul&gt;&lt;/ul&gt; &lt;li&gt;Step 3 : Install and configure JPF  &lt;ul&gt; &lt;li&gt;Step 3.1 : Install JPF files : Copy the whole jpf-core project folder into &amp;lt;user.home&amp;gt;/projects/jpf  &lt;li&gt;Step 3.2 : Create site.properties  &lt;ul&gt; &lt;li&gt;Create site.properties under &amp;lt;user.home&amp;gt;/.jpf folder.  &lt;li&gt;To create the folder on windows, use the following command on the command window after navigating to the user home: &lt;u&gt;mkdir .jpf&lt;/u&gt; .  &lt;li&gt;Paste the following content into the site.properties file.  
&lt;pre class=&quot;prettyprint lang-java&quot;&gt;
# JPF site configuration

jpf.home = ${user.home}/projects/jpf

# can only expand system properties
jpf-core = ${user.home}/projects/jpf/jpf-core

# annotation properties extension
jpf-aprop = ${jpf.home}/jpf-aprop
extensions+=,${jpf-aprop}
# numeric extension
jpf-numeric = ${jpf.home}/jpf-numeric
extensions+=,${jpf-numeric}
# concurrent extension
#jpf-concurrent = ${jpf.home}/jpf-concurrent
#extensions+=,${jpf-concurrent}
jpf-shell = ${jpf.home}/jpf-shell
extensions+=,${jpf-shell}
jpf-awt = ${jpf.home}/jpf-awt
extensions+=,${jpf-awt}

jpf-awt-shell = ${jpf.home}/jpf-awt-shell
extensions+=,${jpf-awt-shell}
&lt;/pre&gt;

&lt;/li&gt;&lt;/ul&gt; &lt;li&gt;Step 3.3 : Install Eclipse plug-in  &lt;ul&gt; &lt;li&gt;The JPF Eclipse plug-in allows you to invoke JPF directly from Eclipse.  &lt;li&gt;In Eclipse go to Help &amp;gt;&amp;gt; Install New Software.  &lt;li&gt;In the new window click Add. In the name insert JPF. In the location insert “&lt;a href=&quot;http://babelfish.arc.nasa.gov/trac/jpf/raw-attachment/wiki/install/eclipse-plugin/update/&quot;&gt;http://babelfish.arc.nasa.gov/trac/jpf/raw-attachment/wiki/install/eclipse-plugin/update/&lt;/a&gt;” then click Ok.  &lt;li&gt;From the “Work with:” drop down menu select the newly added site.  &lt;li&gt;In the list, check “Eclipse-JPF”, click Next, then Finish.&lt;/li&gt;&lt;/ul&gt;&lt;/li&gt;&lt;/ul&gt; &lt;li&gt;Step 4 : Start the demo project  &lt;ul&gt; &lt;li&gt;Step 4.1 : Create and configure project  &lt;ul&gt; &lt;li&gt;In Eclipse menu : File &amp;gt;&amp;gt; New &amp;gt;&amp;gt; Java project : project name = jpf_junit_demo  &lt;li&gt;In the package explorer, right click on the project name. Choose “Build Path” &amp;gt;&amp;gt; “Add libraries”  &lt;li&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEg52OxEXoSGBF1R4wkDur-6mODnwHC_HBwgTufH3kbXiSEUnw4StYfXFIt6X9r6zgdg1x5pdJsc4GyqXrlxFLqWZ_dlg1wQgnSbTJU3pl1apD01uZAsyatVOxptYrZ6dbyQRei3rCY0gQ/s1600-h/2013-03-28%25252015_41_55-Add%252520Library%25255B2%25255D.png&quot;&gt;&lt;img title=&quot;2013-03-28 15_41_55-Add Library&quot; style=&quot;border-left-width: 0px; border-right-width: 0px; border-bottom-width: 0px; display: inline; border-top-width: 0px&quot; border=&quot;0&quot; alt=&quot;2013-03-28 15_41_55-Add Library&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEg5GLQ9dSxu-3TgpKfFl6jCv0eCAEh8CiqMyFNkTYlBWR_ruFBT-owakpWLPxJY52ZjQffZlJzMR6tlwHuBfUs8q5eL4pm8bi11vTAEcsOdWr2mEZJjfuJymPM_hPo7vUtE0GilwCxNiw/?imgmax=800&quot; width=&quot;244&quot; height=&quot;167&quot;&gt;&lt;/a&gt;&amp;nbsp; &lt;li&gt;Select User Library and click Next.  &lt;li&gt;Click User libraries. Then New. You will see a window for creating a library. Put “jpf” as the library name and click Ok to return to the previous dialog.  &lt;li&gt;Select the newly added jpf library and click “Add External JARs …”.  &lt;li&gt;Select all the jar files under &amp;lt;user.home&amp;gt;/jpf/jpf-core/build and click “Open” to add them under library jpf  &lt;li&gt;Click New to create a new user library. Name it “jpf-support”.  &lt;li&gt;Select the newly added jpf-support library and click “Add External JARs …”.  &lt;li&gt;Select all the jar files under &amp;lt;user.home&amp;gt;/jpf/jpf-core/lib and click “Open” to add them under library jpf-support  &lt;li&gt;Now the User Libraries should look like the following:  &lt;li&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjLPHE9xY02c7C54DmlTEn556Mmzr-6jjkQYAPz-xTm2ANUqQ2Wfu79G5DA3c5sEnt0x6VWJqzCe7UEuPfIiToygbs7EKflDUXmpIaQqbdG9CRGLipfgVTKTRVfzPBF-wrPGzQi5mgeqA/s1600-h/2013-03-28%25252015_54_32-Preferences%252520%252528Filtered%252529%25255B2%25255D.png&quot;&gt;&lt;img title=&quot;2013-03-28 15_54_32-Preferences (Filtered)&quot; style=&quot;border-left-width: 0px; border-right-width: 0px; border-bottom-width: 0px; display: inline; border-top-width: 0px&quot; border=&quot;0&quot; alt=&quot;2013-03-28 15_54_32-Preferences (Filtered)&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiH_OByU4p5Y29D4wykvsSM0IW_nLlcz1ApDUBAuHx9f0y52aotcVy62ihA1_-DkCzCUVdy47wJ4zem5PynDYENLkcIjRW1peP2Wi195QGzSs7xRHAg3uSImw7vSbuhlb-Yu8yQZUtaDA/?imgmax=800&quot; width=&quot;244&quot; height=&quot;160&quot;&gt;&lt;/a&gt;&amp;nbsp; &lt;li&gt;Right click on the project name and select : New &amp;gt;&amp;gt; Folder, name the folder as test. Right click on the newly created test folder and select : Build Path &amp;gt;&amp;gt; Use as Source Folder. This folder will be used in the future to hold the JUnit test classes.  &lt;li&gt;Now the project folder should look like the following:  &lt;li&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEh8w2VBn9RYnUR8Z6NRwBWrtJF3YnLFTsYHuKnGkJ4Cu1DacO1HABwsp_XpvlTqS0V-p73xUHop894UTWyrcsGfxlfCv86ONtMQhLA__rciiFBwH4-jaSkymUncQ6FVJ8iGXhnWHQ_81Q/s1600-h/2013-03-28%25252016_00_38-Java%252520-%252520jpf_junit_demo_src_TestGenerator.java%252520-%252520Eclipse%252520SDK%25255B2%25255D.png&quot;&gt;&lt;img title=&quot;2013-03-28 16_00_38-Java - jpf_junit_demo_src_TestGenerator.java - Eclipse SDK&quot; style=&quot;border-left-width: 0px; border-right-width: 0px; border-bottom-width: 0px; display: inline; border-top-width: 0px&quot; border=&quot;0&quot; alt=&quot;2013-03-28 16_00_38-Java - jpf_junit_demo_src_TestGenerator.java - Eclipse SDK&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjygA-xpgfsEUHoIv3Y8UGLfhs5NO7BSyF84Un-AcTRSHQcuMtGo7z-Gyp3-T1czKiI_tEJPYZVuZd8d_xtM7wOazgidxD4A7iWHhKBdimrnZfpkqDf2j8CIoBHZakCYqSQmh_vav1-tA/?imgmax=800&quot; width=&quot;240&quot; height=&quot;244&quot;&gt;&lt;/a&gt; 
&lt;/li&gt;
&lt;/ul&gt; 

&lt;li&gt;
Step 4.2 : Create a class (program under test)  
&lt;ul&gt; 

&lt;li&gt;Right click on the “src” folder and choose: New &amp;gt;&amp;gt; Class. Name it Calculator and click Finish.  
&lt;li&gt;This is the content of the very simple Calculator.java which prints the sum of two integers. The Verify statements are the only JPF statements, the rest is pure java. We will explain the JPF statements through its results in the next step. &lt;p&gt;

&lt;pre class=&quot;prettyprint lang-java&quot;&gt;
import gov.nasa.jpf.jvm.Verify;

public class Calculator {
    int add (int a, int b)
    {
        return a+b;
    }
    public static void main(String[] args)
    {
        int a = Verify.getInt(1,3);
        int b = Verify.getInt(5,8);
        Calculator cal = new Calculator();
        System.out.println(a + &quot;+&quot; + b + &quot;=&quot; + cal.add(a, b));
    }
}
&lt;/pre&gt;
&lt;/li&gt;
&lt;/li&gt;
&lt;/ul&gt; 

&lt;ul&gt;
&lt;li&gt;Step 4.3 : Run JPF from Eclipse  
 &lt;ul&gt;
  &lt;li&gt;Right click on the project name and select: New &amp;gt;&amp;gt; File. Name the file “jpf_junit_demo.jpf”. &lt;/li&gt; 
  &lt;li&gt;This is the content of the newly added file  &lt;p&gt;+classpath=${config_path}/bin&lt;br&gt;target=TestGenerator &lt;/li&gt;
  &lt;li&gt;In the package explorer, right click on the “jpf_junit_demo.jpf” and select “Verify …”. &lt;/li&gt;
  &lt;li&gt;If you couldn’t see the “Verify…” option, this means that you didn’t installed the JPF plug-in properly.&amp;nbsp; See step 3.3.&lt;/li&gt;
  &lt;li&gt;JPF will get started and you will see its output in the console pane. It will be like the following:&lt;/li&gt;
 &lt;/ul&gt;
&lt;/li&gt;
&lt;/ul&gt;

&lt;pre class=&quot;prettyprint lang-java&quot;&gt;
Executing command: java -jar C:\Users\Ebeid\projects\jpf\jpf-core\build\RunJPF.jar +shell.port=4242 C:\Users\Ebeid\projects\jpf_junit_demo\jpf_junit.demo.jpf
JavaPathfinder v6.0 (rev 960+) - (C) RIACS/NASA Ames Research Center

====================================================== system under test
application: Calculator.java

====================================================== search started: 3/28/13 4:41 PM
1+5=6
1+6=7
1+7=8
1+8=9
2+5=7
2+6=8
2+7=9
2+8=10
3+5=8
3+6=9
3+7=10
3+8=11

====================================================== results
no errors detected

====================================================== statistics
elapsed time:       00:00:02
states:             new=5, visited=11, backtracked=16, end=12
search:             maxDepth=3, constraints hit=0
choice generators:  thread=1 (signal=0, lock=1, shared ref=0), data=4
heap:               new=545, released=197, max live=353, gc-cycles=13
instructions:       5098
max memory:         55MB
loaded code:        classes=82, methods=1362

====================================================== search finished: 3/28/13 4:41 PM
&lt;/pre&gt;

&lt;p&gt;According to our program code and the JPF results, you may already guessed what the verify statements are doing in the following lines of code:&lt;/p&gt; &lt;p&gt;int a = Verify.getInt(1,3);&lt;br&gt;int b = Verify.getInt(5,8);&lt;/p&gt; &lt;ul&gt; &lt;li&gt;Simply, Verify.getInt(x, y) get a new integer within the range [x,y].  &lt;li&gt;That is it ?  &lt;li&gt;Partially yes.  &lt;li&gt;But how JPF get 12 print outputs ?  &lt;li&gt;Ok Actually JPF starts a new clone of the program for each value resulted from a Verify.getInt() statement.  &lt;li&gt;This means that JPF will create 3 versions of the program, each one of these versions runs with a different value of a (1, 2, 3).  &lt;li&gt;Each version of these three versions will be used as a base to create another 4 versions of the program for variable b, each one of these versions runs with a different value of b (5, 6, 7, 8). &lt;/li&gt;&lt;/ul&gt; &lt;p&gt;So, the total versions of the program running by JPF is 3 * 4 = 12. Its like a tree where the leafs are the print statements :&lt;/p&gt; &lt;ul&gt; &lt;li&gt;a = 1  &lt;ul&gt; &lt;li&gt;a = 1, b = 5&amp;nbsp;&amp;nbsp;&amp;nbsp; |&amp;nbsp;&amp;nbsp;&amp;nbsp; System.out.println(a + &quot;+&quot; + b + &quot;=&quot; + cal.add(a, b));&amp;nbsp;&amp;nbsp;&amp;nbsp; |&amp;nbsp;&amp;nbsp;&amp;nbsp; 1+5=6  &lt;li&gt;a = 1, b = 6&amp;nbsp;&amp;nbsp;&amp;nbsp; |&amp;nbsp;&amp;nbsp;&amp;nbsp; System.out.println(a + &quot;+&quot; + b + &quot;=&quot; + cal.add(a, b));&amp;nbsp;&amp;nbsp;&amp;nbsp; |&amp;nbsp;&amp;nbsp;&amp;nbsp; 1+6=7  &lt;li&gt;a = 1, b = 7&amp;nbsp;&amp;nbsp;&amp;nbsp; |&amp;nbsp;&amp;nbsp;&amp;nbsp; System.out.println(a + &quot;+&quot; + b + &quot;=&quot; + cal.add(a, b));&amp;nbsp;&amp;nbsp;&amp;nbsp; |&amp;nbsp;&amp;nbsp;&amp;nbsp; 1+7=8  &lt;li&gt;a = 1, b = 8&amp;nbsp;&amp;nbsp;&amp;nbsp; |&amp;nbsp;&amp;nbsp;&amp;nbsp; System.out.println(a + &quot;+&quot; + b + &quot;=&quot; + cal.add(a, b));&amp;nbsp;&amp;nbsp;&amp;nbsp; |&amp;nbsp;&amp;nbsp;&amp;nbsp; 1+8=9&lt;/li&gt;&lt;/ul&gt; &lt;li&gt;a = 2  &lt;ul&gt; &lt;li&gt;a = 1, b = 5&amp;nbsp;&amp;nbsp;&amp;nbsp; |&amp;nbsp;&amp;nbsp;&amp;nbsp; System.out.println(a + &quot;+&quot; + b + &quot;=&quot; + cal.add(a, b));&amp;nbsp;&amp;nbsp;&amp;nbsp; |&amp;nbsp;&amp;nbsp;&amp;nbsp; 2+5=7  &lt;li&gt;a = 1, b = 6&amp;nbsp;&amp;nbsp;&amp;nbsp; |&amp;nbsp;&amp;nbsp;&amp;nbsp; System.out.println(a + &quot;+&quot; + b + &quot;=&quot; + cal.add(a, b));&amp;nbsp;&amp;nbsp;&amp;nbsp; |&amp;nbsp;&amp;nbsp;&amp;nbsp; 2+6=8  &lt;li&gt;a = 1, b = 7&amp;nbsp;&amp;nbsp;&amp;nbsp; |&amp;nbsp;&amp;nbsp;&amp;nbsp; System.out.println(a + &quot;+&quot; + b + &quot;=&quot; + cal.add(a, b));&amp;nbsp;&amp;nbsp;&amp;nbsp; |&amp;nbsp;&amp;nbsp;&amp;nbsp; 2+7=9  &lt;li&gt;a = 1, b = 8&amp;nbsp;&amp;nbsp;&amp;nbsp; |&amp;nbsp;&amp;nbsp;&amp;nbsp; System.out.println(a + &quot;+&quot; + b + &quot;=&quot; + cal.add(a, b));&amp;nbsp;&amp;nbsp;&amp;nbsp; |&amp;nbsp;&amp;nbsp;&amp;nbsp; 2+8=10&lt;/li&gt;&lt;/ul&gt; &lt;li&gt;a = 3  &lt;ul&gt; &lt;li&gt;a = 1, b = 5&amp;nbsp;&amp;nbsp;&amp;nbsp; |&amp;nbsp;&amp;nbsp;&amp;nbsp; System.out.println(a + &quot;+&quot; + b + &quot;=&quot; + cal.add(a, b));&amp;nbsp;&amp;nbsp;&amp;nbsp; |&amp;nbsp;&amp;nbsp;&amp;nbsp; 3+5=8  &lt;li&gt;a = 1, b = 6&amp;nbsp;&amp;nbsp;&amp;nbsp; |&amp;nbsp;&amp;nbsp;&amp;nbsp; System.out.println(a + &quot;+&quot; + b + &quot;=&quot; + cal.add(a, b));&amp;nbsp;&amp;nbsp;&amp;nbsp; |&amp;nbsp;&amp;nbsp;&amp;nbsp; 3+6=9  &lt;li&gt;a = 1, b = 7&amp;nbsp;&amp;nbsp;&amp;nbsp; |&amp;nbsp;&amp;nbsp;&amp;nbsp; System.out.println(a + &quot;+&quot; + b + &quot;=&quot; + cal.add(a, b));&amp;nbsp;&amp;nbsp;&amp;nbsp; |&amp;nbsp;&amp;nbsp;&amp;nbsp; 3+7=10  &lt;li&gt;a = 1, b = 8&amp;nbsp;&amp;nbsp;&amp;nbsp; |&amp;nbsp;&amp;nbsp;&amp;nbsp; System.out.println(a + &quot;+&quot; + b + &quot;=&quot; + cal.add(a, b));&amp;nbsp;&amp;nbsp;&amp;nbsp; |&amp;nbsp;&amp;nbsp;&amp;nbsp; 3+8=11&lt;/li&gt;&lt;/ul&gt;&lt;/li&gt;&lt;/ul&gt; &lt;p&gt;you can use JPF for your JUnit tests to generate explore your code states as we did; just keep in mind that a small increase in the number of states of variables could result in huge number of total program states.&lt;/p&gt; &lt;p&gt;I hope you enjoyed it, and see you later in more posts about JPF.&lt;/p&gt;  </description><link>http://ebeid-soliman.blogspot.com/2013/03/getting-started-with-java-pathfinder.html</link><author>noreply@blogger.com (Ebeid Soliman ElSayed)</author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjjQSIAnZR8AkQMeAc6m-iiEIHZF3HKTHOSdoLExxHVhTuhHda7WeinRESqFFQKQhckJpB5TxuIUKQZzQGMieOjmiPVKZXiJOdhDEsqawzqsfFq_DBanQK1oUIWfA65Si-92cNYHR7wyQ/s72-c?imgmax=800" height="72" width="72"/></item></channel></rss>