My online notes – Section 0002

Note 1: Wait from GUI Thread

private void cmdStart_Click(object sender, RoutedEventArgs e)
{
	thr = new Thread(new ParameterizedThreadStart(Test));
	thr.Start(this);
}

public void Test(object obj)
{
	var wnd = (MainWindow)obj;
	int i = 0;
	while (true)
	{
		i++;
		if (i % 1000000 == 0) //Ab ca. 1000000 schafft die UI es
		{
			var __op = wnd.Dispatcher.BeginInvoke(new Action(UpdateGUI));
			__op.Wait(); //Magische Methode mit der der Arbeitsthread wartet?!
		}
	}
}

public void UpdateGUI()
{
	Random r = new Random();

	txt.Text = "";
	txt.Text = ((char)r.Next(65, 91)).ToString();
}
		

Note 2: Sort with ContextView

public ICommand SortCommand
{
	get
	{
		if (m_SortCommand == null)
		{
			m_SortCommand = new RelayCommand(param => CanSort(), param => Sort());
		}

		return m_SortCommand;
	}
}

private static bool CanSort()
{
	return true;
}

private void Sort()
{
	var direction = m_lastDirection == ListSortDirection.Ascending ? ListSortDirection.Descending : ListSortDirection.Ascending;

	using (m_EmployeesView.DeferRefresh())
	{
		m_EmployeesView.SortDescriptions.Clear();
		m_EmployeesView.SortDescriptions.Add(new SortDescription("LastName", direction));
	}

	m_lastDirection = m_lastDirection == ListSortDirection.Ascending ? ListSortDirection.Descending : ListSortDirection.Ascending;
}

Note 3: TwoWay Binding at DataGrid with AutoGenerateColumns=”True” and Microsoft Entities
It won’t work because the object set of entity doesn’t implement the INotifyPropertyChanged. The simplest solution is to create an ObservableCollection containing the object set of entity.

Note 4: List all triggers with their statements

SELECT t.name, OBJECT_DEFINITION(t.object_id) FROM sys.triggers t
INNER JOIN [dbname].[sys].[all_objects] o on o.object_id = t.object_id
INNER JOIN [dbname].[sys].[schemas] s ON s.schema_id = o.schema_id
WHERE o.[type] LIKE ‘TR’

Note 5: Office 97 Professional Download
Part 1: http://www.megaupload.com/?d=FF8EBPPK
Part 2: http://www.megaupload.com/?d=CV72GDQT
Part 3: http://www.megaupload.com/?d=IDCDIMUC

Note 6: Byte array to struct

static object ByteArrayToStruct(byte[] array, int offset, Type structType)
{
    if (array == null)
        throw new ArgumentNullException("array");

    if (!structType.IsValueType)
        throw new ArgumentException("structType");

    int size = Marshal.SizeOf(structType);

    if ((offset < 0) || (offset + size > array.Length))
        throw new ArgumentOutOfRangeException("offset");

    object structure;
    GCHandle structHandle = GCHandle.Alloc(array, GCHandleType.Pinned);
    try
    {
        IntPtr ptr = structHandle.AddrOfPinnedObject();
        ptr += offset;
        structure = Marshal.PtrToStructure(structHandle.AddrOfPinnedObject(), structType);
    }
    finally
    {
        structHandle.Free();
    }
    return structure;
}


Note 7: Directory and Files enumeration with exception handling

Fast with little information

public static void TraverseFileSystem (String strDir) {
   try {
      // 1. Für alle Dateien im aktuellen Verzeichnis
      foreach (String strFile in Directory.GetFiles (strDir)) {
         // 1a. Statt Console.WriteLine hier die gewünschte Aktion
         Console.WriteLine (strFile);
      }

      // 2. Für alle Unterverzeichnisse im aktuellen Verzeichnis
      foreach (String strSubDir in Directory.GetDirectories (strDir)) {
         // 2a. Statt Console.WriteLine hier die gewünschte Aktion
         Console.WriteLine (strSubDir);

         // 2b. Rekursiver Abstieg
         TraverseFileSystem (strSubDir);
      }
   }
   catch (Exception) {
      // 3. Statt Console.WriteLine hier die gewünschte Aktion
      Console.WriteLine ("error: " + strDir);
   }
}

Slow with more information

public static void TraverseFileSystem (String strDir) {

   // 0. Einstieg in die Rekursion auf oberster Ebene
   TraverseFileSystem (new DirectoryInfo (strDir));
}

private static void TraverseFileSystem (DirectoryInfo di) {
   try {
      // 1. Für alle Dateien im aktuellen Verzeichnis
      foreach (FileInfo fi in di.GetFiles ()) {
         // 1a. Statt Console.WriteLine hier die gewünschte Aktion
         Console.WriteLine (fi.FullName);
      }

      // 2. Für alle Unterverzeichnisse im aktuellen Verzeichnis
      foreach (DirectoryInfo diSub in di.GetDirectories ()) {
         // 2a. Statt Console.WriteLine hier die gewünschte Aktion
         Console.WriteLine (diSub.FullName);

         // 2b. Rekursiver Abstieg
         TraverseFileSystem (diSub);
      }
   }
   catch (Exception) {
      // 3. Statt Console.WriteLine hier die gewünschte Aktion
      Console.WriteLine ("error: " + di.FullName);
   }
}

Note 8: Standard implementation of INotifyPropertyChanged

    #region INotifyPropertyChanged Member
    /// <summary>
    /// Tritt ein, wenn sich ein Eigenschaftenwert ändert.
    /// </summary>
    public virtual event PropertyChangedEventHandler PropertyChanged;

    /// <summary>
    /// Prüft ob sich der alte Wert und der neu Wert unterscheiden. Wenn dies der Fall ist, wird der alte Wert überschrieben und das <see cref="E:PropertyChanged"/>-Event ausgelöst.
    /// </summary>
    /// <typeparam name="T">Der Typ der Werte.</typeparam>
    /// <param name="propertyName">Der Name des Properties, das überprüft wird.</param>
    /// <param name="oldValue">Der alte Wert, normal das vom Property gekapselte Feld.</param>
    /// <param name="newValue">Der neue Wert, normal <c>value</c> des <c>set</c>-Operators des Properties.</param>
    /// <returns>Giebt <c>true</c> zurück, wenn oldValue gegegen newValue ausgetauscht wurde, ansonsten <c>false</c>.</returns>
    protected bool VerursachePropertyChanged<T>(string propertyName, ref T oldValue, ref T newValue)
    {
      if (oldValue == null && newValue == null)
      {
        return false;
      }
      if ((oldValue == null && newValue != null) || !oldValue.Equals((T)newValue))
      {
        oldValue = newValue;
        this.OnPropertyChanged(new PropertyChangedEventArgs(propertyName));
        return true;
      }
      return false;
    }

    /// <summary>
    /// Löst das <see cref="E:PropertyChanged"/>-Event aus.
    /// </summary>
    /// <param name="e">Die <see cref="System.ComponentModel.PropertyChangedEventArgs"/> enthält die Daten für das Event.</param>
    protected virtual void OnPropertyChanged(PropertyChangedEventArgs e)
    {
      if (this.PropertyChanged != null)
      {
        this.PropertyChanged(this, e);
      }
    }
    #endregion
public T MyProperty
{
  get { return this._MyProperty; }
  set { VerursachePropertyChanged("MyProperty",ref this._MyProperty, ref value); }
}

Snippet

<?xml version="1.0" encoding="utf-8"?>
<CodeSnippets xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet">
	<CodeSnippet Format="1.0.0">
		<Header>
			<Title>Standard INotirfyPropertyChanged</Title>
			<Shortcut>Std::PropertyChanged</Shortcut>
			<Description>Standardimplementation für INotifyPropertyChanged.</Description>
			<Author>Microsoft Corporation</Author>
			<SnippetTypes>
				<SnippetType>Expansion</SnippetType>
			</SnippetTypes>
		</Header>
		<Snippet>
			<Code Language="csharp">
        <![CDATA[   #region INotifyPropertyChanged Member
    /// <summary>
    /// Tritt ein, wenn sich ein Eigenschaftenwert ändert.
    /// </summary>
    public virtual event PropertyChangedEventHandler PropertyChanged;

    /// <summary>
    /// Prüft ob sich der alte Wert und der neu Wert unterscheiden. Wenn dies der Fall ist, wird der alte Wert überschrieben und das <see cref="E:PropertyChanged"/>-Event ausgelöst.
    /// </summary>
    /// <typeparam name="T">Der Typ der Werte.</typeparam>
    /// <param name="propertyName">Der Name des Properties, das überprüft wird.</param>
    /// <param name="oldValue">Der alte Wert, normal das vom Property gekapselte Feld.</param>
    /// <param name="newValue">Der neue Wert, normal <c>value</c> des <c>set</c>-Operators des Properties.</param>
    /// <returns>Giebt <c>true</c> zurück, wenn oldValue gegegen newValue ausgetauscht wurde, ansonsten <c>false</c</returns>
    protected bool VerursachePropertyChanged<T>(string propertyName, ref T oldValue, ref T newValue)
    {
      if (oldValue == null && newValue == null)
      {
        return false;
      }
      if ((oldValue == null && newValue != null) || !oldValue.Equals((T)newValue))
      {
        oldValue = newValue;
        this.OnPropertyChanged(new PropertyChangedEventArgs(propertyName));
        return true;
      }
      return false;
    }

    /// <summary>
    /// Löst das <see cref="E:PropertyChanged"/>-Event aus.
    /// </summary>
    /// <param name="e">Die <see cref="System.ComponentModel.PropertyChangedEventArgs"/> enthält die Daten für das Event.</param>
    protected virtual void OnPropertyChanged(PropertyChangedEventArgs e)
    {
      if (this.PropertyChanged != null)
      {
        this.PropertyChanged(this, e);
      }
    }
    #endregion ]]></Code>
		</Snippet>
	</CodeSnippet>
</CodeSnippets>

Note 9: Detect collision with LINQ

            int CollisionDistance = 1;

            List<List<int>> list = new List<List<int>>();
            list.Add(new List<int>());
            list.Add(new List<int>());

            list[0].Add(3);
            list[0].Add(7);
            list[0].Add(8);

            list[1].Add(9);
            list[1].Add(14);
            list[1].Add(15);

            var many = list.SelectMany(item => item);
            var result = from x in many
                         let collision = many.Where(y => x != y && Math.Abs(y - x) <= CollisionDistance)
                         where collision.Any()
                         select new { item = x, collisionset = collision };

            foreach (var r in result)
            {
                Console.Write("Item: " + r.item + " , Kollisionsmenge: ");
                foreach (var collisionCandidate in r.collisionset)
                    Console.Write(" " + collisionCandidate);
                Console.WriteLine();
            }
            Console.ReadLine();

Note 10: Call VBA function from C#

var excel = new Application { Visible = true };
excel.Workbooks.Open(@"C:\Temp\Test.xls");
var returned = excel.Run("ATEModul.MultiplyModul", (Double)1, (Double)2);
excel.Quit();
Console.WriteLine(returned);
Console.ReadLine();

in Excel file and in ATEModul

Public Function MultiplyModul(a As Double, b As Double) As Double
    MultiplyModul = a * b
End Function


Note 11: Textbox with only allowed characters

http://www.mycsharp.de/wbb2/thread.php?threadid=17535

Note 12: Call StoreProcedure of Oracle with input paramerters and get result back

OracleCommand cmd = new OracleCommand("Begin P1.F1(:inputparam, :result); end;", oc);
cmd.CommandType = CommandType.StoredProcedure;

OracleParameter par = new OracleParameter("inputparam", OracleDbType.Number);
par.Value = inputparam;
par.Direction = ParameterDirection.Input;
cmd.Parameters.Add(par);

cmd.Parameters.Add( new OracleParameter("result", OracleDbType.Number)).Direction = ParameterDirection.Output;

cmd.ExecuteNonQuery();
result = Convert.ToInt32(cmd.Parameters["result"].Value.ToString());

Note 13: Check if a point lies in another point
Source: http://msdn.microsoft.com/en-us/library/ms142543.aspx

private void IsVisibleExample(PaintEventArgs e)
{

    // Create a path and add an ellipse.
    GraphicsPath myPath = new GraphicsPath();
    myPath.AddEllipse(0, 0, 100, 100);

    // Test the visibility of point (50, 50).
    bool visible = myPath.IsVisible(50, 50, e.Graphics);

    // Show the result.
    MessageBox.Show(visible.ToString());
}

Or
http://code.google.com/p/nettopologysuite/

Leave a Reply

Your email address will not be published. Required fields are marked *