Archive for Agosto 27th, 2008

CanonStoryboards

CodeKeep C# Feed Agosto 27th, 2008

Description: Playing a series of storyboards in canon using WPF

Link: http://www.codekeep.net/snippets/53d0a024-8ec4-4fe5-b96c-968b479a7d13.aspx

using System;
using System.Collections.Generic;
using System.Text;
using System.Windows;
using System.Windows.Media.Animation;
using System.Diagnostics;

namespace SmartBorderTest.StoryBoards {
    /// <summary>
    /// Plays a series of storyboards in a canon sequence, one after the other
    /// </summary>
    class CanonStoryboards {
        private List<Storyboard> _storyboards = new List<Storyboard>();
        private int _count = -1;

        /// <summary>
        /// The FrameworkElement that contains the storyboards 
        /// </summary>
        private FrameworkElement _containingObject;
        public FrameworkElement ContainingObject {
            get { return _containingObject; }
            set { _containingObject = value; }
        }

        /// <summary>
        /// Initializes a new instance of the CanonStoryboards class
        /// </summary>
        public CanonStoryboards() {
        }
        
        /// <summary>
        /// Initializes a new instance of the CanonStoryboards class and
        /// sets the containing object used when starting the storyboards
        /// </summary>
        /// <param name="containingObject">The FrameworkElement that contains
        /// the storyboards</param>
        public CanonStoryboards(FrameworkElement containingObject) : this() {
            _containingObject = containingObject;
        }

        /// <summary>
        /// Adds a storyboard to the canon sequence.
        /// Storyboards are played in the order they are added.
        /// </summary>
        /// <param name="storyboard">The storyboard to add</param>
        public void AddStoryboard(Storyboard storyboard) {
            if (storyboard == null)
                throw new ArgumentNullException("storyboard");
            _storyboards.Add(storyboard);
        }
        
        /// <summary>
        /// Begins the canon sequence of storyboards
        /// </summary>
        public void Begin() {
            if (_containingObject == null)
                throw new InvalidOperationException(
                    "ContainingObject must be set before Begin can be called");
            
            if (_storyboards.Count == 0)
                throw new InvalidOperationException(
                    "Storyboards must be added before Begin can be called");

            // start the first storyboard
            BeginStoryboard(_storyboards[0]);
        }

        /// <summary>
        /// Handler for storyboards' Completed event
        /// </summary>
        /// <param name="sender">The sender</param>
        /// <param name="e">The event args</param>
        void Storyboard_Completed(object sender, EventArgs e) {
            Debug.WriteLine("CanonStoryboards: storyboard completed");
            // get the next storyboard in the series
            Storyboard nextStoryboard = GetNextStoryboard();
            if (nextStoryboard != null) {
                BeginStoryboard(nextStoryboard);
            }
            else {
                Debug.WriteLine("CanonStoryboards: all storyboards completed");
            }
        }

        /// <summary>
        /// Begins a storyboard in the canon sequence
        /// </summary>
        /// <param name="storyboard">The storyboard to begin</param>
        void BeginStoryboard(Storyboard storyboard) {
            // wire up hanlder to completed event
            storyboard.Completed += new EventHandler(Storyboard_Completed);
            _count++; // increment storyboard counter
            storyboard.Begin(_containingObject);
            Debug.WriteLine("CanonStoryboards: storyboard begun, " + storyboard.Name);
        }

        /// <summary>
        /// Gets the next storyboard in the canon sequence
        /// </summary>
        /// <returns>The next storyboard in the sequence,
        /// null if no other storyboards to play</returns>
        Storyboard GetNextStoryboard() {
            if (_count >= 0 && _storyboards.Count > _count + 1) {
                return _storyboards[_count + 1];
            }
            return null;
        }
    }
}

Run an executable Runas

CodeKeep C# Feed Agosto 27th, 2008

Description: Runas in .net

Link: http://www.codekeep.net/snippets/abd56cf0-2d7a-4726-b7d8-f6e3921da9b7.aspx

Console.Write("Username: ");
string user = Console.ReadLine();
string[] userParts = user.Split('\\');
        
Console.Write("Password: ");
SecureString password = GetPassword();

try
{
    ProcessStartInfo psi = new ProcessStartInfo(args[0]);
    psi.UseShellExecute = false;
            
    if(userParts.Length == 2)
    {
        psi.Domain = userParts[0];
        psi.UserName = userParts[1];
    }
    else
    {
        psi.UserName = userParts[0];
    }

    psi.Password = password;

    Process.Start(psi);
}
catch(Win32Exception e)
{
    Console.WriteLine("Error starting application");
    Console.WriteLine(e.Message);
} 

Run a executable( exe ) and wait for it to close

CodeKeep C# Feed Agosto 27th, 2008

Description: Retrieving the results and waiting until the process stops

Link: http://www.codekeep.net/snippets/de3c2404-c399-4a2b-bf9f-68535ce5a6bc.aspx

private void runSyncAndGetResults_Click(object sender, System.EventArgs e){
 System.Diagnostics.ProcessStartInfo psi =
   new System.Diagnostics.ProcessStartInfo(@"C:\listfiles.bat");
 psi.RedirectStandardOutput = true;
 psi.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
 psi.UseShellExecute = false;
 System.Diagnostics.Process listFiles;
 listFiles = System.Diagnostics.Process.Start(psi);
 System.IO.StreamReader myOutput = listFiles.StandardOutput;
 listFiles.WaitForExit(2000);
 if (listFiles.HasExited)
  {
  string output = myOutput.ReadToEnd();
  this.processResults.Text = output;
 }
}

Launch URL

CodeKeep C# Feed Agosto 27th, 2008

Description: Open a URL in default browser

Link: http://www.codekeep.net/snippets/565586a3-7494-495d-b23e-e98a191434ae.aspx

private void launchURL_Click(object sender, System.EventArgs e){
 string targetURL = @http://www.duncanmackenzie.net;
 System.Diagnostics.Process.Start(targetURL);
}

Execute application with arguments

CodeKeep C# Feed Agosto 27th, 2008

Description: Execute application with arguments

Link: http://www.codekeep.net/snippets/56c8cadf-5276-4a21-891f-02ed1736e12f.aspx

private void executeApplication( string appName, string args )
{
System.Diagnostics.ProcessStartInfo pInfo = new System.Diagnostics.Process.Start( appName , args );
pInfo.RedirectStandardOutput = true;
pInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden // if you don't want to see the application execute;
pInfo.UseShellExecute = false;

System.Diagnostics.Process listFiles;
listFiles = System.Diagnostics.Process.Start( pInfo );
System.IO.StreamReader processOutput = listFiles.StandardOutput;
processOutput.WaitForExit( 2000 );
if ( listFiles.HasExited )
{
string processResults = processOutput.ReadToEnd();
this.processResults.Text = processResults;
}
}

A template IEquatable implementation

CodeKeep C# Feed Agosto 27th, 2008

Description: Implement the IEquatable interface to get a typed Eauals implementation.

Link: http://www.codekeep.net/snippets/c7a3a7d7-cd3b-48fe-b8c6-7f4a8029d6ad.aspx

public bool Equals(T other)
{
    if (this.GetType() != other.GetType()) return false;
    if (ReferenceEquals(null, other)) return false;
    if (ReferenceEquals(this, other)) return true;

    return this.CompareTo(other) == 0;
}

public override bool Equals(object obj)
{
    if (obj is T)
        return this.Equals(obj as T);
    else
        return base.Equals(obj);
}

Binary Deserialize method

CodeKeep C# Feed Agosto 27th, 2008

Description: Deserializes a object from a given stream using the BinaryFormatter and returns the object as the type specified.

Link: http://www.codekeep.net/snippets/f17b0efc-de2b-4fc8-8bfa-5574d5bb2c68.aspx

public static T Deserialize(Stream input)
{
    BinaryFormatter formatter = new BinaryFormatter();
    return formatter.Deserialize(input) as T;
}

Binary serialization method

CodeKeep C# Feed Agosto 27th, 2008

Description: A method to Serialize a object to a MemoryStream using the BinaryFormatter.

Link: http://www.codekeep.net/snippets/3d2a9511-ac5c-4067-bbea-477be78f5a3b.aspx

public Stream Serialize()
{
    //Use Version Tolerant Serialization cocepts
    BinaryFormatter formatter = new BinaryFormatter();

    MemoryStream stream = new MemoryStream();

    formatter.Serialize(stream, this);
    stream.Position = 0;

    return stream;
}

Attributes that needs to be applied when implementing ISerializable

CodeKeep C# Feed Agosto 27th, 2008

Description: Use this as a template when implementing the ISerializable interface.

Link: http://www.codekeep.net/snippets/5c5d1b96-785e-4757-a968-0933802df2cb.aspx

[SecurityPermissionAttribute(SecurityAction.Demand, SerializationFormatter = true)]
public void GetObjectData(SerializationInfo info, StreamingContext context)
{
}

Create a HashCode code from a given object

CodeKeep C# Feed Agosto 27th, 2008

Description: Use this method as a template to generate a proper hashcode when GetHashCode is called on a class that overides the equals method.

Link: http://www.codekeep.net/snippets/5c56310e-2387-4771-92c9-6b0fcaf6cbfb.aspx

        /// <remarks>
        /// Refer to "C# in a nutshell", page 125 Generating Hash Code.
        /// Use a odd prime constant, e.g. 37 or 397
        /// </remarks>
        private int CreateHashCode(int hashCode, object target)
        {
            int hashPrime = 397;
            unchecked
            {
                return hashPrime * hashCode ^ (target == null ? 0 : target.GetHashCode());
            }
        }