Work with Exchange Web Services

# February 21, 2012 - 10:47 by
Last Update: 21.2.2012 - 19:18

The following code has cost me allot of time. It was very hard to find the pieces and put them together. So I hope I can help a few of you with that post ;-)

The Problem

The problem was that I need to access different Exchange accounts via Exchange Web Services (EWS) and read out the mailbox size.

First

To do this I first used a view only account in the active directory that I have activated for impersonation by typing the following code into the Exchange-Shell:

Get-ExchangeServer
| where {$_.IsClientAccessServer -eq $TRUE}
| ForEach-Object {Add-ADPermission -Identity $_.distinguishedname -User (Get-User -Identity User1 | select-object)
    .identity -extendedRight ms-Exch-EPI-Impersonation}

You can find an explanation to this code on msdn: http://msdn.microsoft.com/en-us/library/bb204095(EXCHG.80).aspx

Second

Then I set up the connection string to the EWS:

// Certification Validation always true
ServicePointManager.ServerCertificateValidationCallback =
                    delegate(
                        Object obj,
                        X509Certificate certificate,
                        X509Chain chain,
                        SslPolicyErrors errors)
                    {
                        return true;
                    };

// Setup connection string
ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2007_SP1);
service.Credentials = new NetworkCredential("viewadmin", "password", "FQDN");
service.AutodiscoverUrl("viewadmin@FQDN");

Third

Thirdly I used impersonation to connect to another mailbox account:

// Impersonate
service.ImpersonatedUserId = new ImpersonatedUserId(ConnectingIdType.SmtpAddress, "user@FQDN");

Finally

And finally I requested the folder size with this nice little piece of code:

private static readonly ExtendedPropertyDefinition PidTagMessageSizeExtended = new ExtendedPropertyDefinition(0xe08, MapiPropertyType.Long);

/// <summary>
/// Gets the size of the mailbox in kilobytes.
/// </summary>
/// <param name="service">The ExchangeService object.</param>
/// <returns>Returns the used kilobytes in double.</returns>
public static double GetMailboxSize(ExchangeService service)
{
    var offset = 0;
    const int pagesize = 12;
    long size = 0;

    FindFoldersResults folders;
    do
    {
        folders = service.FindFolders(WellKnownFolderName.MsgFolderRoot,
                                      new FolderView(pagesize, offset, OffsetBasePoint.Beginning)
                                      {
                                          Traversal = FolderTraversal.Deep,
                                          PropertySet =
                                              new PropertySet(BasePropertySet.IdOnly, PidTagMessageSizeExtended,
                                                              FolderSchema.DisplayName)
                                      });

        foreach (var folder in folders)
        {
            long folderSize;
            if (folder.TryGetProperty(PidTagMessageSizeExtended, out folderSize))
                size += folderSize;
        }
        offset += pagesize;
    } while (folders.MoreAvailable);

    return size;
}

 

I hope I could help you. If you have improvements on the code don´t hazle to comment ;-)

PHP-Script: Verzeichnisstruktur auflisten

# December 17, 2011 - 14:55 by
Last Update: 17.12.2011 - 15:05

Dieses Script stammt aus meinen alten PHP-Zeite. Ich nutze es, in abgewandelter Form, zurzeit auf jwillmer.de und dachte vielleicht kann es ja auch jemand anders gebrauchen ;-)

<?php
/*
   Dieses kleine Script listet die Verzeichnisstrukturen auf und verlinkt deren Inhalte.
   Viel Spaß damit! - Gruß jEns
*/

if (!function_exists('scandir')) {
	function scandir($directory, $sorting_order=0) {
		if(!is_dir($directory)) {
			return false;
		}
		$files = array();
		$handle = opendir($directory);
		while (false !== ($filename = readdir($handle))) {
			$files[] = $filename;
		}
		closedir($handle);

		if($sorting_order == 1) {
			rsort($files);
		} else {
			sort($files);
		}
		return $files;
	}
}

function ordnerinhalt($folder='.') {
	$content = "";

	foreach(scandir($folder) as $file) {
		// Versteckte Dateien nicht anzeigen
		if($file[0] != '.') {
			if(is_dir($folder.'/'.$file)) {
				$folderArray[] = $file;
			} else {
				$fileArray[] = $file;
			}
		}
	}

	// Erst die Ordner ausgeben
	if(isset($folderArray)) {
		foreach($folderArray as $row) {
			$content .= '<b>'.$row.'</b><br />';
			// Unterordner nach rechts einrücken
			$content .= '<div style="padding-left:10px;color:#afafaf" />';
			// Rekursive Funktion
			$content .= ordnerinhalt($folder.'/'.$row);
			$content .= '</div>';
		}
	}

	// ...dann die Dateien ausgeben
	if(isset($fileArray)) {
		foreach($fileArray as $row) {
			// Dateien verlinken
			$content .= '<a href="'.$folder.'/'.$row.'">'.$row.'</a><br />';
		}
	}

	return $content;
}

echo ordnerinhalt();
?>

How to use Eventhandlers in C#

# August 23, 2011 - 7:45 by
Last Update: 17.12.2011 - 15:06
class Program
{
	static void Main()
    {
		//init stock
        Stock s1 = new Stock();

		//add handler
        s1.PriceChanged += new PriceChangedHandler(s1_PriceChanged);
		s1.MyFunction += new MyFunctionhandler(s1_MyFunction);

		//change something
        s1.Price = 12;
        s1.myFunction(2);

        Console.Read();
    }

    public static void s1_PriceChanged(decimal a, decimal b)
    {
        Console.WriteLine("Old value: " + a + " - new value: " + b);
    }

    public static void s1_MyFunction(string s, int i)
    {
        Console.WriteLine(s + " - number:" + i.ToString());
    }
}

public delegate void PriceChangedHandler (decimal oldPrice, decimal newPrice);
public delegate void MyFunctionhandler (string hand, int p);

class Stock
{
    decimal price;

	//eventhandlers
    public event PriceChangedHandler PriceChanged;
    public event MyFunctionhandler MyFunction;

    public decimal Price
    {
        get { return price; }
        set {
            if (price == value) return;
			//if handler was added trow the event
            if (PriceChanged != null)
                PriceChanged(price, value);
            price = value;
        }
    }

    public void myFunction(int i)
    {
        if (i == 2 && MyFunction != null)
            MyFunction("left", 3);
    }
}

Threading in C# und WPF

# June 21, 2011 - 11:15 by
Last Update: 17.12.2011 - 15:06

Anbei der Code womit sich neue WPF-Fenster in einem eigenen Thread öffnen lassen. War eine unsere Aufgaben in der Vorlesung Betriebssysteme.

MainWindow.xaml.cs

...
..
using System.Threading;

namespace Threading
{
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();

            Thread thread = Thread.CurrentThread;
            this.DataContext = new
            {
                ThreadId = thread.ManagedThreadId
            };
        }

        private void OnCreateNewWindow( object sender, RoutedEventArgs e)
        {
            Thread thread = new Thread(() =>
            {
                MainWindow w = new MainWindow();
                w.Show();

                System.Windows.Threading.Dispatcher.Run();
            });

            thread.SetApartmentState(ApartmentState.STA);
            thread.Start();
        }
    }
}

MainWindow.xaml

 

<Window x:Class="Threading.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="132" Width="210">
    <StackPanel>
        <StackPanel Orientation="Horizontal">
            <TextBlock Text="Thread's ID is "/>
            <TextBlock Text="{Binding ThreadId}"/>
        </StackPanel>
        <Button Click="OnCreateNewWindow" Content="Create new Window" />
    </StackPanel>
</Window>

 

How to use the BackgroundWorker Thread in C#

# March 6, 2011 - 21:00 by
Last Update: 17.12.2011 - 15:06

BackgroundWorker-Thread

Pils  wird in einem neuen Thread ausgeführt und nach Fertigstellung wird bw_RunWorkerCompleted aufgerufen und im alten Thread ausgeführt.

private BackgroundWorker bw = new BackgroundWorker();

public Form1()
{
    InitializeComponent();
    bw.WorkerReportsProgress = true;
    bw.WorkerSupportsCancellation = true;
    bw.ProgressChanged += new ProgressChangedEventHandler(bw_ProgressChanged);
    bw.DoWork += new DoWorkEventHandler(bw_DoWork);
    bw.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bw_RunWorkerCompleted);
}

public void buttonStart_Click(object sender, EventArgs e)
{
    if (bw.IsBusy != true)
        bw.RunWorkerAsync(12); //Start
}

public int Pils(int i)
{
    Thread.Sleep(2000);
    bw.ReportProgress(70, "In the middle of the work..");
    Thread.Sleep(2000);
    bw.ReportProgress(90, "Returning the result..");
    Thread.Sleep(2000);
    return (2 * i);
}

private void bw_DoWork(object sender, DoWorkEventArgs e)
{
    bw.ReportProgress(20, "Waiting for cancel..");
    Thread.Sleep(2000);
    if ((bw.CancellationPending == true))
        e.Cancel = true;
    else
    {
        bw.ReportProgress(50, "Starting process..");
        e.Result = Pils((int)e.Argument);
    }
}

private void bw_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
    bw.ReportProgress(100, "Work done..");
    if ((e.Cancelled == true))
         textBox1.Text = "Canceled!";
    else if (e.Error != null)
         textBox1.Text = ("Error: " + e.Error.Message);
    else textBox1.Text = e.Result.ToString();
}

private void buttonCancel_Click(object sender, EventArgs e)
{
    if (bw.WorkerSupportsCancellation == true)
        bw.CancelAsync();
}

private void bw_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
    listBox1.Items.Add((e.ProgressPercentage.ToString() + "%") + " - " + e.UserState as String);
}