How read use an ADO.NET DataSet to read XML files designed with nested attributes?

I am working on a project that is XML driven and I am using ADO.NET DataSet functionality to make reading the XML easier. However, I ran into a problem that really just a lack of knowledge on my part.

Problem
So I have DataSet created using an XML. The XML is using Nested attributes. And I just need to know how to loop properly through the DataSet Tables and their columns.

I have the following XML.

<?xml version="1.0" encoding="utf-8" ?>
<plugin PluginName="TestName" GroupName="Operating System Settings" Type="Single">
  <title>Plugin 1</title>
  <startTime>1:57:47 PM 2/16/2010</startTime>
  <endTime>1:58:03 PM 2/16/2010</endTime>
  <description>Runs the TestName process to determine something.</description>
  <section SectionName="Section1">
    <field FieldName="Field Name">
      <value Operand="EQ">Some Correct Setting1</value>
      <actionPlugin Name="" Type="Link" URL="">
        <executable>SomeAction1.exe</executable>
        <parameters>Param1 Param2</parameters>
      </actionPlugin>
    </field>
    <field FieldName="Field2">
      <value Operand="RG">900</value>
      <warningLevel>10%</warningLevel>
      <errorLevel>20%</errorLevel>
      <actionPlugin Name="ActionPlugin1" Type="Link" URL="http://www.somesite.tld/some/path/file.htm" />
    </field>
  </section>
  <section SectionName="Section2">
    <field FieldName="Field1">
      <value Operand="EQ">Some Correct Setting2</value>
      <actionPlugin Name="" Type="Link" URL="">
        <executable>SomeAction2.exe</executable>
        <parameters>Param1 Param2</parameters>
      </actionPlugin>
    </field>
    <field FieldName="Field2">
      <value Operand="RG">900</value>
      <warningLevel>10%</warningLevel>
      <errorLevel>20%</errorLevel>
      <actionPlugin Name="ActionPlugin1" Type="Link" URL="http://www.somesite.tld/some/path/file.htm" />
    </field>
  </section>
  <section SectionName="Section3">
    <field FieldName="Field1">
      <value Operand="EQ">Some Correct Setting3</value>
      <actionPlugin Name="" Type="Link" URL="">
        <executable>SomeAction3ds.exe</executable>
        <parameters>Param1 Param2</parameters>
      </actionPlugin>
    </field>
    <field FieldName="Field2">
      <value Operand="RG">900</value>
      <warningLevel>10%</warningLevel>
      <errorLevel>20%</errorLevel>
      <actionPlugin Name="ActionPlugin1" Type="Link" URL="http://www.somesite.tld/some/path/file.htm" />
    </field>
  </section>
</plugin>

So the DataSet is created with these tables (this is copied from the debugger):

– List Count = 5 System.Collections.ArrayList
+ [0] {Plugin} object {System.Data.DataTable}
+ [1] {Section} object {System.Data.DataTable}
+ [2] {Field} object {System.Data.DataTable}
+ [3] {Value} object {System.Data.DataTable}
+ [4] {ActionPlugin} object {System.Data.DataTable}

Table [1] {Section} has 3 rows.
Table [2] {Field} has 6 rows.

So the data looks like this:

Sections Table
Row 1
Row 2
Row 3

Fields Table
Row 1
Row 2
Row 3
Row 4
Row 5
Row 6

But I need to read it as follows:

Sections Table
Row 1  
Fields Table
Row 1
Row 2
Row 2  
Fields Table
Row 3
Row 4
Row 3  
Fields Table
Row 5
Row 6

So I had the code below, but for each Section Row it would loop through all six field rows, which is not what I intend.

string mFullPathToXML = "C:\My.xml";
DataSet ds;
ds.ReadXml(mFullPathToXML);

foreach (DataRow SectionRow in ds.Tables["Section"].Rows)
{
    foreach(DataRow FieldRow in ds.Tables["Field"].Rows)
    {
        // Looping through all rows, not just those that pertain to the section.
        // How to get only the two rows that belong to each Section row here?
    }
}

Solution
Well, I set out on a journey to figure this out. In a few search engines I use search phrases like:
DataSet XML Nested
DataSet XML Nested Relation
DataSet DataTable XML Nested Row
DataSet DataTable XML Nested Row

A lot of documentation on Microsoft’s site to XMLs and DataSets showed up, but nothing describing this problem/solution.

I am happy to say that with help from the MSDN Forums, the solution was found. Please read my post here:
http://social.msdn.microsoft.com/Forums/en-US/adodotnetdataset/thread/2d115ba6-49be-4a5c-bf92-054626109f50

So the solutions is to use the Section_Id assigned to each row in the Sections table inside the Field table’s Select() function as shown:

foreach (DataRow sectionRow in ds.Tables["Section"].Rows)
{
	string sectionId = sectionRow["Section_Id"].ToString();
	Console.WriteLine("Section: {0}", sectionRow["SectionName"]);
	foreach (DataRow fieldRow in ds.Tables["Field"].Select("Section_Id = " + sectionId))
	{
		foreach (object item in fieldRow.ItemArray)
		{
			// Do something here
		}
	}
}

This solution works for me.

How to modify the default new class template for C# in Visual Studio 2008 or 2010?

Updated: 5/17/2010 using information aquired from here: http://www.thecodinghumanist.com/Content/HowToEditVSTemplates.aspx

Ok, so I don’t like the way that the default new class template in Visual Studio 2008/2010 looks. I end up typing a lot of things over and over again.

Here is what it a new class looks like:

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

namespace MyNameSpace
{
	class MyClass
	{
	}
}

Here is what I want it to look like:

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

namespace MyNameSpace
{
	public class MyClass
	{
		#region Member Variables
		#endregion

		#region Constructors

		/// <summary>
		/// The default Constructor.
		/// </summary>
		public MyClass()
      		{
		}

		#endregion

		#region Properties
		#endregion

		#region Functions
		#endregion

		#region Enums
		#endregion
	}
}

So making this change is easy to do. All you have to do is edit a text file that is compressed.

Copy the zip file file located here to the desktop:
Visual Studio 2008

  • For 64 bit: C:\Program Files (x86)\Microsoft Visual Studio 9.0\Common7\IDE\ItemTemplates\CSharp\Code\1033\Class.zip
  • For 32 bit: C:\Program Files\Microsoft Visual Studio 9.0\Common7\IDE\ItemTemplates\CSharp\Code\1033\Class.zip

Visual Studio 2010

  • For 64 bit: C:\Program Files (x86)\Microsoft Visual Studio 10.0\Common7\IDE\ItemTemplates\CSharp\Code\1033\Class.zip
  • For 32 bit: C:\Program Files\Microsoft Visual Studio 10.0\Common7\IDE\ItemTemplates\CSharp\Code\1033\Class.zip

Extract the zip file.

Using a text editor, open the Class.cs file.

The file will have the following text:

using System;
using System.Collections.Generic;
$if$ ($targetframeworkversion$ >= 3.5)using System.Linq;
$endif$using System.Text;

namespace $rootnamespace$
{
	class $safeitemrootname$
	{
	}
}

Change it to have this text:

using System;
using System.Collections.Generic;
$if$ ($targetframeworkversion$ >= 3.5)using System.Linq;
$endif$using System.Text;

namespace $rootnamespace$
{
	public class $safeitemrootname$
	{
		#region Member Variables
		#endregion

		#region Constructors

		/// <summary>
		/// The default Constructor.
		/// </summary>
		public $safeitemrootname$()
		{
		}

		#endregion

		#region Properties
		#endregion

		#region Functions
		#endregion

		#region Enums
		#endregion
	}
}

Save the file.

Rebuild the zip file with the new Class.cs.  Be careful to build the zip file correctly.

Copy the new zip file back here and overwrite the existing one:
Visual Studio 2008

  • For 64 bit: C:\Program Files (x86)\Microsoft Visual Studio 9.0\Common7\IDE\ItemTemplates\CSharp\Code\1033\Class.zip
  • For 32 bit: C:\Program Files\Microsoft Visual Studio 9.0\Common7\IDE\ItemTemplates\CSharp\Code\1033\Class.zip

Visual Studio 2010

  • For 64 bit: C:\Program Files (x86)\Microsoft Visual Studio 9.0\Common7\IDE\ItemTemplates\CSharp\Code\1033\Class.zip
  • For 32 bit: C:\Program Files\Microsoft Visual Studio 9.0\Common7\IDE\ItemTemplates\CSharp\Code\1033\Class.zip

Now, you have to rebuild the template classes.  To do this:

  1. Open a command prompt as Administrator.
  2. Change to the appropriate directory:
    Visual Studio 2008
    64-bit

    cd C:\Program Files (x86)\Microsoft Visual Studio 9.0\Common7\IDE\

    32-bit

    cd C:\Program Files\Microsoft Visual Studio 9.0\Common7\IDE\

    Visual Studio 2010
    64-bit

    cd C:\Program Files (x86)\Microsoft Visual Studio 10.0\Common7\IDE\

    32-bit

    cd C:\Program Files\Microsoft Visual Studio 10.0\Common7\IDE\
  3. Run this command:
    devenv.exe /installvstemplates

Now any new class you create will have your new format.


Copyright ® Rhyous.com – Linking to this article is allowed without permission and as many as ten lines of this article can be used along with this link. Any other use of this article is allowed only by permission of Rhyous.com.

How to get the relative path (folder the executable was launched in) as a string in C#?

Well, lets say you launch an application and you want to know the relative path.

In C# you can use the System.Reflection.Assembly.GetExecutingAssembly().Location value. I have searched through many online sites that tell different ways, and some of the more experienced C# developers say that some of the other ways are not always accurate or won’t always work, while this one should always work.

So if you make a class and add two String class variables, you can use this function to populate them:


        private void GetPaths()
        {
            mExecutablePath = System.Reflection.Assembly.GetExecutingAssembly().Location;
            mExecutableRootDirectory = System.IO.Path.GetDirectoryName(mExecutablePath);
        }

Ok, so I like to make sure any newbie can pull this off, so the whole file with it working (using a New WPF project):

using System;
using System.Collections.Generic;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace TestPath
{
    /// <summary>
    /// Interaction logic for Window1.xaml
    /// </summary>
    public partial class Window1 : Window
    {
        DataSet mDataSet;
        String mExecutablePath;
        String mExecutableRootDirectory;

        public Window1()
        {
            GetPaths();
            InitializeComponent();
        }

        private void GetPaths()
        {
            mExecutablePath = System.Reflection.Assembly.GetExecutingAssembly().Location;
            mExecutableRootDirectory = System.IO.Path.GetDirectoryName(mExecutablePath);
        }
    }
}

A new style guide or a new way to format your code in C++ or C# or any language: "Code like you speak"

Code Like You Speak

Ok, so I wrote a post about why I use long variable names, where I discussed how it is very easy to use long filenames with today’s IDEs. As I code more and more I realize how I want to write like I speak.

As I try to read other people’s code, I have to wonder if they could even understand it themselves if they went six months without touching it.

For example, lets say I am working with a database that has phone numbers and for each phone number I want to do check if it is valid:

Example 1

PhoneNumber p = new PhoneNumber("555-555-5555");
if (p.isValid())
{
    // do something
} else
{
    // Do something different
}

There is nothing wrong with the above code. It even makes sense, mostly because the first line where p is created is right next to the if statement. But of course that is not always the case.

Maybe I have dozens of objects for different database attributes including multiple ojects that start with ‘p’: PhoneNumber, PartList, PersonID, and they all have an isValid() method and those objects are created elsewhere in the code, who knows where. Also, your isValid() function in PhoneNumber checks if the PhoneNumber is formatted correctly, but the isValid() function in PartList checks if it is a valid part in the database and the isValid() function in PersonID does something different, now the above code would be more confusing, especially to some one else reading it (or to yourself six months after writing it).

if (p.isValid())
{
    // do something
} else
{
    // Do something different
}

So if we don’t have the declaration right next to the code, it is hard to understand…

You might say, “Load it in a debugger and just look…why is it so hard?”

My response is this. “What about your Team Leads for you Tech Support team? What about your documentation team? They may have that has access to read the code but they don’t have the tools or know how to compile it. But they may need to see your code to get their job done. And I don’t want to offend your project managers, but there sure are a lot of Project Managers that either never had the ability or have lost the skill to compile code.”

So someone else reading your code is lost. What does p represent? PhoneNumber, PartList, PersonId? What is the object? What does isValid() check for on this object?

So lets code like we speak. First you should say what we really want to do in your language. The sentence below is a valid English sentence and anybody who speaks English can understand it.

If the current phone number is formatted correctly, do something, else do something different.

Well, what if the code were written like this:

// This could be anywhere in code
PhoneNumber theCurrentPhoneNumber = new PhoneNumber("555-555-5555");

// A code like you speak if statement
if (theCurrentPhoneNumber.isFormattedCorrectly())
{
    // do something
} else
{
    // do something different
}

See how it is in “code like you speak” format?

So you may here different theories about writing code and whether to document with comments or not document and have clear code. I am for the theory that when you write your code you should assume that the person reading your code:
1. Doesn’t understand code.
2. Has no technical skills
3. Has an average IQ (in the 90s).
4. Is the worst technical ever who has to document your code…
etc, etc, etc…

So that is why “Code like you speak” is a great way to code. If your technical writer reads the first example, he is confused, but if he read the second, he fully understands the idea what it going one.

Now, it is important that you don’t over do it. You don’t need to have perfect English. Broken English is fine. As you practice you will get better at it. As you get better at it, your code becomes more readable and others can work on it easier. This is especially usefully when working in teams, or one a community-developed open source application.

Don’t go overboard! I mean, there is not reason to define the word “othewise” to replace “else”. If you did that, you may actually confuse veteran developers.

// In a header somewhere...
#define otherwise else

// This could be anywhere in code
PhoneNumber theCurrentPhoneNumber = new PhoneNumber("555-555-5555");

// A code like you speak if statement
if (theCurrentPhoneNumber.isFormattedCorrectly())
{
    // do something
}
otherwise
{
    // do something different
}

However, if the “Code like you speak” development style takes off, the above may not be so overboard, and may become a standard practice to define many English synonyms to help one code in a more clear and understandable method.

One might argue that because not every one speaks english, a language barrier would be more likely, and I would have to disagree. If you code like you speak, someone who doesn’t speak your language could still figure it out a lot faster using something like a language translation tool (such as google’s or babblefish’s) than they could by trying to figure out what a random object is.

As for other style guide information, there are lots of style guides. If you need one and don’t have one, start with this one:
http://google-styleguide.googlecode.com/svn/trunk/cppguide.xml

How to execute SQL statement that has a single quote in C# or insert a row with a value that has a quote?

Imagine you have a query such as the following:

SELECT * FROM User WHERE LastName='O'Conner'

INSERT INTO User (FirstName, LastName, UserName, Email) VALUES ('John','O'Conner','jo'conner','joconner@somedomain.tld')

Well, that is obviously not going to work, because the apostrophe or single quote in the name O’Conner is going to break the query syntax.

You have to have two single quotes to use a quote.

SELECT * FROM User WHERE LastName='O''Conner'

INSERT INTO User (FirstName, LastName, UserName, Email) VALUES ('John','O'Conner','jo''conner','joconner@somedomain.tld')

Ok, so there are two ways to make sure you have two quotes in C#:

  1. You manage the query string yourself.
  2. You use a DataTable and let it manage the query string for you.

Managing the query string yourself

Ok, the answer is simple. You need two single quotes next to each other.

Now, when you have single string, this is easy to do. You need to replace each instance of a single quote with two single quotes using this function which already exists for you:

string.replace(string inStringToBeReplaced, string inNewString)

Here is an example of doing it wrong, then fixing it. Step through this in a debugger.

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

namespace SingleQuoteInSQL
{
    class Program
    {
        static void Main(string[] args)
        {
            string FirstName = "John";
            string LastName  = "O'Conner";
            string UserName  = "joconner";
            string Email     = "joconner@domain.tld";

            // Both these queries are broken because of the space.
            string strQuery1 = "SELECT * FROM User WHERE LastName='" + LastName + "'";
            string strQuery2 = "INSERT INTO User (FirstName, LastName, UserName, Email) VALUES (" +
                        "'" + FirstName + "'," +
                        "'" + LastName + "'," +
                        "'" + UserName + "'," +
                        "'" + Email + "')";

            // This will actually break your query too, because it will replace valid single quotes
            // with two single quotes.  You need to do this on the actually data strings.
            strQuery1 = strQuery1.Replace("'", "''"); //
            strQuery2 = strQuery1.Replace("'", "''");

            // Replace any intance of a single quote with two single quotes, ''.
            // IMPORTANT: Typing two single quotes ('') is not the same as a double quote (").
            FirstName = FirstName.Replace("'", "''");
            LastName = LastName.Replace("'", "''");
            UserName = UserName.Replace("'", "''");
            Email = Email.Replace("'", "''");

            // Both these queries are working now;
            strQuery1 = "SELECT * FROM User WHERE LastName='" + LastName + "'";
            strQuery2 = "INSERT INTO User (FirstName, LastName, UserName, Email) VALUES (" +
                        "'" + FirstName + "'," +
                        "'" + LastName + "'," +
                        "'" + UserName + "'," +
                        "'" + Email + "')";
        }
    }
}

Using a DataTable to manage this for you automagically

This actually looks like more work at first, but really when handling a lot of data, it is much more easy to code using DataTables and DataRows.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Data.SqlClient;

namespace SingleQuoteInSQL
{
    class Program
    {
        static void Main(string[] args)
        {
            string FirstName  = "John";
            string LastName  = "O'Conner";
            string UserName  = "joconner";
            string Email        = "joconner@domain.tld";

            // Create the connection
            string mConnectionString = "Data Source=ServerName; user id=UserName; password=pw; Initial Catalog=DatabaseName;";
            SqlConnection mSqlConnection = new SqlConnection(mConnectionString);

            // Create a data adapter, this is what does the magic.
            String mQueryForSqlDataAdapter = "Select * from TableName";
            SqlDataAdapter tmpSqlDataAdapter;
            SqlCommandBuilder tmpSqlCommandBuilder;
            DataTable tmpDataTable = new DataTable();
            tmpSqlDataAdapter = new SqlDataAdapter(mQueryForSqlDataAdapter, mSqlConnection);

            // Use the SqlDataAdapter to create a table with the right schema but no data
            tmpDataTable = tmpSqlDataAdapter.FillSchema(tmpDataTable, SchemaType.Mapped);

            // Create a SqlCommandBuilder
            tmpSqlCommandBuilder = new SqlCommandBuilder(tmpSqlDataAdapter);

            // Create a DataRow and populate it
            DataRow row = tmpDataTable.NewRow();
            row["FirstName"] = FirstName;
            row["LastName"] = LastName;
            row["UserName"] = UserName;
            row["Email"] = Email;

            // Add this row to the DataTable
            tmpDataTable.Rows.Add(row);

            // Write this to the database
            tmpSqlDataAdapter.Update(tmpDataTable);
        }
    }
}

Notice we didn’t have to do a string replace of ‘ for ”.

How to store a password in an XML file encrypted so it is not in clear text or how to encrypt any textstring?

Ok, so I have an application that needs to take a password and I need to remember that password. All the configuration is stored in XML, which is usually clear text. I want to store the password in the XML file, but I don’t want anyone to be able to open the XML file and be able to see the password in clear text.

So here is what I going to do.

I create a class called PasswordEncoder that is going to use DESCryptoServiceProvider, which is a C# function.

I found a few examples online that helped me create this, such as Microsoft’s site that explains this object and another users blog that shows an example, which I used but only slightly modified.
http://msdn.microsoft.com/en-us/library/system.security.cryptography.descryptoserviceprovider.aspx
http://www.dotnetspider.com/resources/21370-Password-Encryption-using-C.aspx

So here is my source. All you have to do is create your own class and copy in this code and you are ready to encrypt and decrypt passwords you store in XML.

Important! You must change the mInitializationVector and the mByteArray variable values to be your own values. Yes you can simply make up your own values.  We don’t want a everyone using the same keys.

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text;

namespace PasswordEncoder
{
    class PasswordEncoder
    {
        string mEncryptedPassword;
        // Change the two values below to be something other than the example.
        // Once changed and in use, do not change the value below again or you
        // won't be able to decrypt previously stored passwords.
        string mByteArray = "%$#>#%232s+as#l)URa0$!@";
        byte[] mInitializationVector = { 0x01, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xf7, 0xEF };

        public PasswordEncoder()
        {
        }

        public PasswordEncoder(string inPassword)
        {
            mEncryptedPassword = EncryptWithByteArray(inPassword, mByteArray);
        }

        public string EncryptWithByteArray(string inPassword)
        {
            mEncryptedPassword = EncryptWithByteArray(inPassword, mByteArray);
            return mEncryptedPassword;
        }

        private string EncryptWithByteArray(string inPassword, string inByteArray)
        {
            try
            {
                byte[] tmpKey = new byte[20];
                tmpKey = System.Text.Encoding.UTF8.GetBytes(inByteArray.Substring(0, 8));
                DESCryptoServiceProvider des = new DESCryptoServiceProvider();
                byte[] inputArray = System.Text.Encoding.UTF8.GetBytes(inPassword);
                MemoryStream ms = new MemoryStream();
                CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(tmpKey, mInitializationVector), CryptoStreamMode.Write);
                cs.Write(inputArray, 0, inputArray.Length);
                cs.FlushFinalBlock();
                return Convert.ToBase64String(ms.ToArray());
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        public string DecryptWithByteArray()
        {
            return DecryptWithByteArray(mEncryptedPassword, mByteArray);
        }

        private string DecryptWithByteArray(string strText, string strEncrypt)
        {
           try
           {
                byte[] tmpKey = new byte[20];
                tmpKey = System.Text.Encoding.UTF8.GetBytes(strEncrypt.Substring(0, 8));
                DESCryptoServiceProvider des = new DESCryptoServiceProvider();
                Byte[] inputByteArray = inputByteArray = Convert.FromBase64String(strText);
                MemoryStream ms = new MemoryStream();
                CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(tmpKey, mInitializationVector), CryptoStreamMode.Write);
                cs.Write(inputByteArray, 0, inputByteArray.Length);
                cs.FlushFinalBlock();
                System.Text.Encoding encoding = System.Text.Encoding.UTF8;
                return encoding.GetString(ms.ToArray());
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        public string EncryptedPassword
        {
            get { return mEncryptedPassword; }
            set { mEncryptedPassword = value; }
        }

        public string ByteArray
        {
            get { return mByteArray; }
            set { mByteArray = value; }
        }
    }
}

Here is a simple sample of how to use this:

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

namespace PasswordEncoder
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.Write("Enter a password: ");
            string password = Console.ReadLine();
            Console.WriteLine("You entered this password: " + password);

            PasswordEncoder pe = new PasswordEncoder();
            string encryptedPassword = pe.EncryptWithByteArray(password);
            Console.WriteLine("Your encrypted password string: " + encryptedPassword);

            string decryptedPassword = pe.DecryptWithByteArray();
            Console.WriteLine("Your decrypted password string: " + decryptedPassword);

            if (password.Equals(decryptedPassword))
            {
                Console.WriteLine("Good work, your password was successfully encrypted then decrypted.");
            }
            else
            {
                Console.WriteLine("Uh...what did you do wrong, these don't match.");
            }
        }
    }
}

Where to get free training and tutorial videos for WPF?

So WPF doesn’t seem very well documented. I have been struggling to find good documentation and learn all its intricacies. I like tutorials and training videos and examples and samples, all of which have been difficult to come by.

So I thought I would share with everyone the following web site where Microsoft provides quite a lot of training videos on WPF.

WPF Videos
http://windowsclient.net/learn/videos_wpf.aspx

If you take time to watch all these videos, you will probably be a master at WPF very quickly.

A good site for learning WPF ListView as GridView development in C# and WPF

So i needed to make a table layout in WPF and I noticed that it is not that simple to learn.

However, I found a really good site that teaches you how to populate a ListView using a GridView from XML, a DataTable, data from a database, etc…

The new WPF GridView customized 1 of 3
http://www.codeproject.com/KB/miscctrl/GridView_WPF.aspx

I spent all day trying to figure out what this site taught me in less than an hour.

How to remove an element from a regular array in C#?

How to remove an element from an regular array in C#?

Well, you can’t really change a regular array or remove an item from it. You have to create a new array that is a copy of the current array without the one value you want.

Here is a quick static class I created that will copy your array, leaving out the one item you don’t want.

namespace ArrayItemDeleter
{
static class ArrayItemDeleter
{
public static void RemoteArrayItem(ref T[] inArray, int inIndex)
{
T[] newArray = new T[inArray.Length – 1];
for (int i = 0, j = 0; i < newArray.Length; i++, j++) { if (i == inIndex) { j++; } newArray[i] = inArray[j]; } inArray = newArray; } } } [/sourcecode] Here is how you would use it in your program. [sourcecode language="csharp"] using System; namespace ArrayItemDeleter { class Program { static void Main(string[] args) { string[] str = {"1","2","3","4","5"}; ArrayItemDeleter.RemoteArrayItem(ref str, 2); } } } [/sourcecode] Now, if you really want to add and remove items a lot, you should use a System.Collections.Generic.List object;

How to connect to Salesforce / SForce with C#?

Step 1 – Download and import the wsdl (sorry no steps for this here yet).

Step 2 – Use the following code example

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;

namespace SforceConnection
{
    public class Program
    {
        static void Main(string[] args)
        {
            SforceService service = new SforceService();
            LoginResult loginResult = new LoginResult();
            string username= "youruser@yourdomain.tld";
            string password= "P@sswd!";
            service.Timeout = 60000;
            loginResult  = service.login(username, password);
            service.Url = loginResult.serverUrl;
            service.SessionHeaderValue = new SessionHeader();
            service.SessionHeaderValue.sessionId = loginResult.sessionId;

            // Do something you are now connected

        }
    }
}