.Net C# using the params[] keyword

A simple example to show how the C# params[] array can be used to pass in multiple items into a method.

using System;
using System.Linq;

namespace CsharpParamsDemo
{
    public class CsharpParamsExample
    {
        /// <summary>
        /// Defines the entry point of the application.
        /// </summary>
        static void Main()
        {
            Console.WriteLine(ConcatStrings("Fri","day"));

            Console.WriteLine();

            Console.WriteLine(ConcatStrings("a", "b","c","d","e"));

            Console.ReadKey();
        }

        /// <summary>
        /// Concatenates the strings.
        /// </summary>
        /// <param name="values">The values.</param>
        /// <returns>Concatenated string</returns>
        private static string ConcatStrings(params string[] values)
        {
            return values.Aggregate(string.Empty, (current, value) => current + value);
        }
    }
}

Returns:

Friday

abcde

Using Apache Solr 4.5.0 and .Net C# – part 1 installation and setup

I’m going to spend some time looking at some interesting services that really extend and enhance what’s possible with web applications. Over this series I’ll build up a fully working app with all the source code starting with an enterprise search engine I’ve been interested in for a while.

Apache Solr is an open source enterprise search platform from the Apache Lucene project. It has some useful features that include full-text search, hit highlighting, faceted search, near real-time indexing, dynamic clustering, database integration, rich document handling and geospatial capabilities.

Solr is also highly reliable, scalable and can be setup into fault tolerant modes. It’s heavily used on the Internet as listed on Solr public sites.

The homepage for Solr is: https://lucene.apache.org/solr/.

Before you can run Solr, grab and install the latest Java SE Oracle SE download.

If you don’t want the Oracle version, Solr apparently supports other Java versions according to the Lucene tutorial.

For this installation, the latest Oracle SDK is used. Solr versions greater than 4 require a Java version 1.6 or greater.

Grab the installation files from: http://www.apache.org/dyn/closer.cgi/lucene/solr/4.5.0 and select the most appropriate mirror. This installation on this post is performed on a Windows server.

Grab the conpressed file, decompress it and save the output to a location on your disk.

Navigate to the installation directory and run the following in a command prompt:

D:\Solr\solr-4.5.0\example

Then:

java –jar start.jar

This will present two URIs which you can browse at:

The Apache Solr dashboard: http://localhost:8983/solr/#/

Solr admin screen

And an example search engine: http://localhost:8983/solr/collection1/browse/?

Solr example screen

Once these are running, the next task is to index some content, to do this run the following java:

java -jar post.jar *.xml

This will produce the following output:

D:\Solr\solr-4.5.0\example\exampledocs>java -jar post.jar *.xml
SimplePostTool version 1.5
Posting files to base url http://localhost:8983/solr/update using content-type a
pplication/xml..
POSTing file gb18030-example.xml
POSTing file hd.xml
POSTing file ipod_other.xml
POSTing file ipod_video.xml
POSTing file manufacturers.xml
POSTing file mem.xml
POSTing file money.xml
POSTing file monitor.xml
POSTing file monitor2.xml
POSTing file mp500.xml
POSTing file sd500.xml
POSTing file solr.xml
POSTing file utf8-example.xml
POSTing file vidcard.xml
14 files indexed.
COMMITting Solr index changes to http://localhost:8983/solr/update..
Time spent: 0:00:01.205

If you return the the example search interface, You will find a number of documents have been indexed.

More info on Solr setup can be found at: http://lucene.apache.org/solr/3_6_2/doc-files/tutorial.html.

In part 2, We’ll take a look at some of the more advanced features of Solr.

.Net C# using the Dapper ORM

A quick look at the Dapper ORM and a simple example to grab some data from a SQL Server.

using System;
using System.Data.SqlClient;
using Dapper;

namespace CsharpDapperDemo
{
    /// <summary>
    /// Simple demonstration of the Dapper ORM.
    /// </summary>
    class CsharpDapperExample
    {
        static void Main()
        {
            const string myConnectionString = @"Data Source=MYSQLSERVER\SQLEXPRESS;Database=Company;Integrated Security=True;Connect Timeout=15;Encrypt=False";

            using (var connection = new SqlConnection(myConnectionString))
            {
                connection.Open();

                var companyDataResults  = connection.Query<CompanyData>("select * from dbo.EmployeeInfo");

                foreach (var result in companyDataResults)
                    Console.WriteLine("{0} {1} {2} {3} {4}", result.Empno, result.EmpName, result.Salary,
                                      result.DeptName, result.Designation);

                Console.ReadKey();
            }
        }

        /// <summary>
        /// Class for testing results from Dapper.
        /// </summary>
        private class CompanyData
        {
            public int Empno;
            public string EmpName;
            public int Salary;
            public string DeptName;
            public string Designation;
        }
    }
}

.Net C# validate an XML file against an XSL schema (class)

Code sample to demonstrate how to validate an XML file against an XSL schema.

using System;
using System.Xml;
using System.Xml.Schema;

namespace CsharpXmlSchemaValidationExample
{
    /// <summary>
    /// Class to demonstrate XML validation against a XSL schema
    /// </summary>
    public class CsharpXmlSchemaValidationDemo
    {
        private readonly string _schema;

        private const string XmlDoc = "Sample.xml";
        
        private static bool _result = true;

        /// <summary>
        /// Initializes a new instance of the <see cref="ValidDateHrFileWithSchema"/> class.
        /// </summary>
        /// <param name="schema">The schema.</param>
        public ValidDateHrFileWithSchema(string schema)
        {
            _schema = schema;
        }

        /// <summary>
        /// Determines whether [is XML document valid].
        /// </summary>
        /// <returns></returns>
        public bool IsXmlDocValid()
        {
            var schemaSet = new XmlSchemaSet();
          
            schemaSet.Add("", _schema);

            XmlSchema compiledSchema = null;

            foreach (XmlSchema schema in schemaSet.Schemas())
            {
                compiledSchema = schema;
            }

            var settings = new XmlReaderSettings();

            if (compiledSchema != null) settings.Schemas.Add(compiledSchema);

            settings.ValidationEventHandler += ValidationCallBack;
            
            settings.ValidationType = ValidationType.Schema;

            //Create the schema validating reader.
            var vreader = XmlReader.Create(XmlDoc, settings);

            while (vreader.Read()) { }

            vreader.Close();

            return _result;
        }

        /// <summary>
        /// Validations the call back.
        /// </summary>
        /// <param name="sender">The sender.</param>
        /// <param name="args">The <see cref="ValidationEventArgs"/> instance containing the event data.</param>
        private static void ValidationCallBack(object sender, ValidationEventArgs args)
        {
            if (args.Severity != XmlSeverityType.Warning)
            {
                Console.WriteLine("\tValidation error: {0}", args.Message);
                _result = false;
            }
            else
            {
                Console.WriteLine("\tWarning: Matching schema not found.  No validation occurred.{0}", args.Message);
                _result = false;
            }
        }
    }
}

.Net C# match a UK postcode with a regular expression (code fragment)

A quick code fragment to show how to match UK postcodes, the expression is taken from this Stack Overflow article.


 var postcodePattern = "^([A-Z]{1,2})([0-9][0-9A-Z]?) ([0-9])([ABDEFGHJLNPQRSTUWXYZ]{2})$";

 var preg = new Regex(postcodePattern, RegexOptions.IgnoreCase);

 foreach (var xElement in pcode)
 {
  Console.WriteLine(
                    !preg.IsMatch(xElement) ? "Error! The post code fields must be valid: {0}" : "Postcode matched: {0}",
xElement);
 }


A quick look at the ILNumerics library

Just had a really quick play with the ILNumerics library as demonstrated by Scott Hanselman in this post. This is a quick rewrite of the demo code found on the ILNumerics site quick start tutorial. The visualizations look useful so more to follow on this..

using System;
using ILNumerics;

namespace CsharpILNumericsDemo
{
    class CsharpILNumericsExample : ILMath
    {
        static void Main()
        {
            // Create a matrix testArray , give values explicitly
            ILArray<double> testArray = array(
                    new double[]
                        {
                            1, 1, 1, 1, 1, 2, 3, 4, 1, 3, 6, 10, 1, 4, 10, 20
                        }, 4, 4
                        );
            
            // use a creation function for testCounter 
            ILArray<double> testCounter = counter(4,2);

            // use a function of the base class: ILMath.linsolve 
            ILArray<double> result = linsolve(testArray, testCounter);

            Console.WriteLine("Test Array: {0}{1}", Environment.NewLine, testArray);

            Console.WriteLine();

            Console.WriteLine("Test Counter: {0}{1}", Environment.NewLine, testCounter);

            Console.WriteLine();

            Console.WriteLine("A * [Result] = B: {0}{1}", Environment.NewLine, result.ToString());

            Console.WriteLine();

            // check result:

            // uses norm, multiply, epsilon and binary operators 
            Console.WriteLine(norm(multiply(testArray, result) - testCounter) <= eps ? "Result is true" : "Result is false");

            Console.ReadKey();            
        }
    }
}

Returns:

Test Array:
<Double> [4,4]
         1          1          1          1
         1          2          3          4
         1          3          6         10
         1          4         10         20

Test Counter:
<Double> [4,2]
         1          5
         2          6
         3          7
         4          8

A * [Result] = B:
<Double> [4,2]
         0          4
         1          1
         0          0
         0          0

Result is true

.Net C# 2 minutes with NodaTime

Very quick and dirty play with NodaTime, I’ll tidy this up on a future blog post. More info on NodaTime can be found at: Noda-Time on code.google.com.

using System;
using System.Collections.Generic;
using System.Linq;
using NodaTime.Calendars;

namespace NodaTime
{
    /// <summary>
    /// API here: http://noda-time.googlecode.com/hg-history/1.0.x/docs/api/Index.html
    /// Implement IClock interface
    /// </summary>
    public class Program : IClock
    {
        static void Main()
        {
            // Get Now from implementing IClock interface
            var now = Instant.FromDateTimeUtc(DateTime.UtcNow);

            Console.WriteLine("This is now: " + now);

            // Call Noda Calendar system
            NodaCalendarSystem();

            // Show time zones
            ShowTimeZones();

            var timeZoneDb = new TimeZoneDb();

            var timeZones = timeZoneDb.GetTimeZones("CA");

            foreach (var timeZone in timeZones)
            {
                Console.WriteLine(timeZone);
            }

            Console.ReadKey();
        }

        private static void NodaCalendarSystem()
        {
            // calendar system eras
            var gregorianCalendar = CalendarSystem.GetGregorianCalendar(7);

            var julianCalendar = CalendarSystem.GetJulianCalendar(7);

            var copticCalendar = CalendarSystem.GetCopticCalendar(7);

            var islamicCalendar = CalendarSystem.GetIslamicCalendar(IslamicLeapYearPattern.Base16, IslamicEpoch.Civil);

            var calendarSystems = new List<CalendarSystem>
                         {
                             gregorianCalendar, 
                             julianCalendar, 
                             copticCalendar, 
                             islamicCalendar
                         };

            foreach (var calendarSystem in calendarSystems)
            {
                var eras = calendarSystem.Eras.ToList();

                foreach (var era in eras)
                {
                    Console.WriteLine(era);

                    Console.WriteLine(calendarSystem.GetAbsoluteYear(1982, era));
                }

                Console.WriteLine("Days in month:");

                for (var year = 1974; year < 2012; year++)
                {
                    Console.WriteLine("{0} {1}", year, calendarSystem.GetDaysInMonth(year, 02));
                }

                Console.WriteLine("Max Month:");

                for (var year = 1974; year < 2012; year++)
                {
                    Console.WriteLine("{0} {1}", year, calendarSystem.GetMaxMonth(year));
                }

                Console.WriteLine("Is leap year?:");

                for (var year = 1974; year < 2012; year++)
                {
                    Console.WriteLine("{0} {1}", year, calendarSystem.IsLeapYear(year));
                }

                Console.WriteLine("Calendar ID: {0}", calendarSystem.Id);

                Console.WriteLine("Calendar Name: {0}", calendarSystem.Name);

                Console.WriteLine("Use ISO: {0}", calendarSystem.UsesIsoDayOfWeek);

                Console.ReadKey();
            }
        }

        /// <summary>
        /// Gets the current <see cref="T:NodaTime.Instant" /> on the time line according to this clock.
        /// </summary>
        public Instant Now { get; private set; }

        /// <summary>
        /// Shows the time zones.
        /// </summary>
        private static void ShowTimeZones()
        {
            var timeZones = TimeZoneInfo.GetSystemTimeZones();

            foreach (var timeZoneInfo in timeZones)
            {
                Console.WriteLine(timeZoneInfo.DisplayName);
            }
        }
    }
}

.Net C# class serialization

A quick demonstration of the [Serializable] attribute applied to a class.

using System;
using System.IO;
using System.Runtime.Serialization.Formatters.Soap;

namespace CsharpSerializableDemo
{
    /// <summary>
    /// Program to demonstrate class serialization
    /// </summary>
    class CsharpSerializableExample
    {
        static void Main()
        {
            //Creates a new SerializableClass object.
            var serializableClass = new SerializableClass();

            Console.WriteLine(SerializableClass.TestString);
            Console.WriteLine(SerializableClass.TestInt);
            Console.WriteLine(SerializableClass.TestDouble);
            Console.WriteLine(SerializableClass.TestBoolean);
            Console.WriteLine(SerializableClass.TestFloat);

            Console.WriteLine();

            var stream = File.Open("temp.xml", FileMode.Create);

            var formatter = new SoapFormatter();

            formatter.Serialize(stream, serializableClass);
            
            stream.Close();

            stream = File.Open("temp.xml", FileMode.Open);
            
            formatter = new SoapFormatter();

            serializableClass = (SerializableClass)formatter.Deserialize(stream);

            Console.WriteLine(SerializableClass.TestString);
            Console.WriteLine(SerializableClass.TestInt);
            Console.WriteLine(SerializableClass.TestDouble);
            Console.WriteLine(SerializableClass.TestBoolean);
            Console.WriteLine(SerializableClass.TestFloat);
       
            stream.Close();

            Console.ReadKey();
        }
    }

    /// <summary>
    /// Class for testing Serialization.
    /// </summary>
    [Serializable]
    public class SerializableClass
    {
        public const string TestString = "a string";
        public const int TestInt = 42;
        public const double TestDouble = 5.4444;
        public const bool TestBoolean = true;
        [NonSerialized] public const float TestFloat = 0.9f;
    }
}

Returns:

a string
42
5.4444
True
0.9

a string
42
5.4444
True
0.9

.Net C# & Binary and Unary operator example

A quick demo to show the .Net & Binary and Unary operator in action.

using System;

namespace CsharpAmpOperatorDemo
{
    internal class CsharpAmpOperatorExample
    {
        private static void Main()
        {
            Console.WriteLine("Binary operator example:");

            const bool testOne = true & false;
            const bool testTwo = true & true;
            const bool testThree = false & true;
            const bool testFour = false & false;

            Console.WriteLine("Result of true & false: {0}", testOne);
            Console.WriteLine("Result of true & true: {0}", testTwo);
            Console.WriteLine("Result of false & true: {0}", testThree);
            Console.WriteLine("Result of false & false: {0}", testFour);

            Console.WriteLine("Unary operator example:");

            const int x = 0xAA;
            const int y = 0XFF;

            const int testResult = x & y;

            Console.WriteLine("{0:d}", x);
            Console.WriteLine("{0:d}", y);

            Console.WriteLine("Result: {0:d}", testResult);

            Console.ReadKey();
        }
    }
}

Returns:

Binary operator example:
Result of true & false: False
Result of true & true: True
Result of false & true: False
Result of false & false: False
Unary operator example:
170
255
Result: 170