Search This Blog

Tuesday, December 24, 2013

SelectSingleNode C# XML Example

C# > XML > SelectSingleNode

SelectSingleNode selects the first node that matches the XPath expression.

Example

Select node based on attribute value

Products.xml

xml version='1.0'?>
<products xmlns="urn:products-schema">
  <product name="Product1">
    <price>100</price>
  </product>
  <product name="Product2">
    <price>200</price>
  </product>
</products>

C# Code

XmlDocument doc = new XmlDocument();
doc.Load(@"D:\Products.xml");

XmlNamespaceManager nsmgr = new XmlNamespaceManager(doc.NameTable);
nsmgr.AddNamespace("pp", "urn:products-schema");

XmlElement root = doc.DocumentElement;
XmlNode product = root.SelectSingleNode("pp:product[@name='Product1']", nsmgr);










C# XML Examples

C# > XML

XML is Extensible Markup Language is a markup language. It defines a set of rules for encoding documents in a format that is both human-readable and machine-readable. (read more on http://en.wikipedia.org/wiki/XML)


The System.Xml namespace provides standards-based support for processing XML.





Classes


Examples

Why SelectSingleNode always returns null?

C# > XML > XmlNamespaceManager > SelectSingleNode null

Why SelectSingleNode always returns null?

Because is missing the XML namespace defined SelectSingleNode call.

Solution:

XmlDocument doc = new XmlDocument();
doc.Load(xmlfile);

XmlNamespaceManager nsMgr = new XmlNamespaceManager(doc.NameTable);
nsMgr.AddNamespace("ns", "urn:www.data.com/feed");

var node = doc.SelectSingleNode("ns:ParentNode/ns:ChildNode", nsMgr);










OLE DB is an API for accessing data.

C# > Data > OLE DB

OLE DB is an API for accessing data. It is common to access Microsoft Access databases, or Microsoft Excel spreadsheets.

Examples:












Monday, December 23, 2013

C# ComponentModel

C# > System > ComponentModel

ComponentModel provides classes that are used to implement the run-time and design-time behavior of components and controls.











BackgroundWorker and progress bar C# example

C# > SystemComponentModel > BackgroundWorker

The BackgroundWorker runs an operation on a separate and dedicated thread.
Time-consuming operations can cause the user interface (UI) to seem as frozen and stop responding while they are running.
BackgroundWorker class represents a solution to this.






Example

Use BackgroundWorker and progress bar to display a progress of import operation






using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.OleDb;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Forms;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace BackgroundWorker 
{
    

    /// Interaction logic for MainWindow.xaml
    ///

    public partial class MainWindow : Window
    {
        private BackgroundWorker worker = null;
        public MainWindow()
        {        
        }
        void worker_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {          
            pBar.Value = e.ProgressPercentage;
            lblStatus.Content = "Processing......" + pBar.Value.ToString() + "%";
        }
        private void worker_DoWork(object sender, DoWorkEventArgs e)
        {
            // do your task here
            for (int i = 0; i <= 100; i++)
            {
                Thread.Sleep(500);
                if (worker == null)
                    break;
                worker.ReportProgress(i);
            }
        }
        private void worker_RunWorkerCompleted(object sender,RunWorkerCompletedEventArgs e)
        {
            lblStatus.Content = "Task finished";
        }
        private void Button_Click(object sender, RoutedEventArgs e)
        {
            if (worker == null)
            {
                worker = new BackgroundWorker();
                worker.DoWork += worker_DoWork;
                worker.RunWorkerCompleted += worker_RunWorkerCompleted;
                worker.ProgressChanged += worker_ProgressChanged;
                worker.WorkerReportsProgress = true;
                worker.WorkerSupportsCancellation = true;
            }
            if (worker.IsBusy != true)
            {
                // Start the asynchronous operation.
                worker.RunWorkerAsync();
            }
        }
        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            pBar.Maximum = 100;
        }
        private void btnCancel_Click(object sender, RoutedEventArgs e)
        {
            worker.CancelAsync();
            worker = null;
        }
    }
}






Parentheses () Operator C# Example

C# > Operators() Operator

Parentheses operator is used for

1. Casting

double a = 4.5;
int b;
a = (int)q; // Cast double to int   

2. Invoke

Method(); // Call method

Note: This operator cannot be overloaded!








Predicate Delegate C# Example

C# > System > Predicate<T> Delegate

This delegate is used to search for elements in the collection.
Predicate<T> delegate is represented by a lambda expression.

Example


public class Student
{
       public string Name { get; set; }
       public int Year { get; set; }
       public Student(string name, int year)
       {
              this.Name = name;
              this.Year  = year;
       }
}


List<Student> groups = new List<Student>();
groups.AddRange(new Student[] { new Student("Stud1", 1973),
                                new Student("Stud2", 2000),
                                new Student("Stud3", 2010),
                                new Student("Stud4", 1999),
                                new Student("Stud5", 1995) });


foreach (var g in groups.FindAll(x => x.Year >= 2000))
              System.Windows.MessageBox.Show(g.Name);



  





C# System Interfaces

C# > System > Interfaces





IEquatable C# Example

C# > System > Interfaces > IEquatable

IEquatable<T> Interface defines Equals method for determining equality of instances.
Example

public class Car : IEquatable<Car>
{
            public int Power { get; set; }
       public bool Equals(Car other)
       {
              if (other == null)
                    return false;
              if(this.Power == other.Power)
                    return true;
              return false;
       }
       public override bool Equals(Object obj)
       {
              if (obj == null)
                    return false;
              Car carObj = obj as Car;
              if (carObj == null)
                    return false;
              else
                    return Equals(carObj);
       }  
}

Car c1 = new Car();
c1.Power = 100;
Car c2 = new Car();
c2.Power = 100;
if (c1.Equals(c2))
    System.Windows.MessageBox.Show("Same power");





Friday, December 20, 2013

Identify feature DotSpatial Map

DotSpatial > Controls > Map

Identify feature DotSpatial Map on MouseUP event.


private void map1_MouseUp(object sender, MouseEventArgs e)
{
      Coordinate cor =  map1.PixelToProj(e.Location);
      Extent ex = new Extent(cor.X, cor.Y, cor.X, cor.Y);
      var  mLayer = map1.Layers[0];
      IFeatureLayer il = (IFeatureLayer) mLayer;
      List<IFeature> result = il.DataSet.Select(ex);
      if (result.Count>0) 
      {
           IFeature ift = result.FirstOrDefault();
           MessageBox.Show(ift.DataRow[0].ToString());
       }
}





PATINDEX SQL Server Example

SQL Server > Built-in Functions > PATINDEX

PATINDEX returns the start position of pattern occurrence in an expression.

Warning! If pattern or expression is NULL, PATINDEX returns NULL.

Example



SELECT 'This is PATINDEX example' AS 'Expression'

SELECT PATINDEX('%pat%', 'This is PATINDEX example') as 'Find any position pat';

SELECT PATINDEX('%a_p%', 'This is PATINDEX example') as 'Find any a followed by any caracter and then p';