My online notes – Section 0004

Note 1: Proxy of HttpWebRequest for uploading

HttpWebRequest HttpRequest = (HttpWebRequest)WebRequest.Create(this.fullUrl);
<system.net>
    <defaultProxy enabled ="false">
		<proxy autoDetect ="True"/>
    </defaultProxy>
</system.net>

Note 2: Walkthrough: Implementing Virtual Mode in the Windows Forms DataGridView Control for page loading
http://msdn.microsoft.com/en-us/library/15a31akc.aspx

Note 3: Create login dialog to MS SQL Server
Explorer -> Right mouse click -> new text file -> Change file extension to “.udl” -> Double click. In “Provider” register, choose SQL Server, in “Connection” register enter all information and check with the “Test” Button. If the connection won’t be opened, an appropriate error comes.

Note 4: Open new window with MVVMLight

public class ViewModel1 : ViewModelBase
{
    public RelayCommand ShowView2Command { private set; get; }

    public ViewModel1() : base()
    {
        ShowView2Command = new RelayCommand(ShowView2CommandExecute);
    }

    public void ShowView2CommandExecute()
    {
        Messenger.Default.Send(new NotificationMessage("ShowView2"));
    }
}

public partial class View1 : UserControl
{
    public View1()
    {
        InitializeComponent();
        Messenger.Default.Register(this, NotificationMessageReceived);
    }

    private void NotificationMessageReceived(NotificationMessage msg)
    {
        if (msg.Notification == "ShowView2")
        {
            var view2 = new view2();
            view2.Show();
        }
    }
}

Note 5: Get selected text in WebBrowser

using mshtml;

...

IHTMLDocument2 htmlDocument = webBrowser1.Document.DomDocument as IHTMLDocument2;
IHTMLSelectionObject currentSelection= htmlDocument.selection;
if (currentSelection!=null)
{
	IHTMLTxtRange range= currentSelection.createRange() as IHTMLTxtRange;
	if (range != null)
	{
		MessageBox.Show(range.text);
	}
}

Note 5: Get range of range in Excel

workSheet.get_Range("A1").Value = "Wert1";
workSheet.get_Range("B1").Value = "Wert2";
workSheet.get_Range("C1").Value = "Wert3";
workSheet.get_Range("D1").Value = "Wert4";
workSheet.get_Range("E1").Value = "Wert5";
workSheet.get_Range("A2").Value = "Wert6";
workSheet.get_Range("B2").Value = "Wert7";
workSheet.get_Range("C2").Value = "Wert8";
workSheet.get_Range("D2").Value = "Wert9";
workSheet.get_Range("E2").Value = "Wert10";

Excel looks like
{
Reihe 1: Wert1 Wert2 Wert3 Wert4 Wert5
Reihe 2: Wert6 Wert7 Wert8 Wert9 Wert10
}

Excel.Range range = workSheet.get_Range("A1:A5");
foreach (Excel.Range item in range)
	Console.WriteLine(item.Value);

returns :
Range 1: Wert1 Wert2 Wert3 Wert4 Wert5
Range 2: Wert6 Wert7 Wert8 Wert9 Wert10

Excel.Range range = workSheet.get_Range("A1:E2");
Excel.Range range2 = range.get_Range("A1:E1")
foreach (Excel.Range item in range2)
	Console.WriteLine(item.Value);

returns:
Wert1
Wert2
Wert3
Wert4
Wert5

Note 6: Update GUI with Task Parallel

class BorderedImage : Border
{
	public BorderedImage(string fileName, double borderWidth) {
		Image image = CreateImage();
		StyleBorder(borderWidth, fileName);
		this.Child = image;
	}

	private Image CreateImage() {
		Image image = new Image();
		image.Margin = new Thickness(5);
		return image;
	}

	private void StyleBorder(double borderWidth, string fileName) {
		SolidColorBrush borderBrush = new SolidColorBrush(Colors.LightGray);
		this.BorderBrush = borderBrush;
		this.BorderThickness = new Thickness(1);
		this.Margin = new Thickness(2);
		this.CornerRadius = new CornerRadius(5);
		this.Background = new SolidColorBrush(Colors.White);
		this.Width = borderWidth;
		this.ToolTip = (new ToolTip()).Content = fileName;
		this.Tag = fileName;
		this.MouseEnter += new MouseEventHandler(border_MouseOver);
		this.MouseLeave += new MouseEventHandler(border_MouseOver);
	}
}

...

private void ShowImages(List imageList)
{
	int imageListCount = imageList.Count;

	// gui part
	for (int imageCounter = 0; imageCounter < imageListCount; imageCounter++) { 		BorderedImage borderedImage = 			new BorderedImage((string)imageList[imageCounter], 							  (mainScrollviewer.ActualWidth / tiles) - 8); 		mainWrapPanel.Children.Add(borderedImage); 	} 	// parallel part 	Task.Factory.StartNew(() => {
		Parallel.For(0, imageListCount, (imageCounter) => {
			Stream fileStream = File.OpenRead((string)imageList[imageCounter]);
			this.Dispatcher.BeginInvoke(new Action<BitmapImage, int>
				(SetBorderedImageSource), CreateBitmap(fileStream), imageCounter);
		});
	});
}

private BitmapImage CreateBitmap(Stream fileStream)
{
	BitmapImage bitmap = new BitmapImage();
	bitmap.BeginInit();
	bitmap.CacheOption = BitmapCacheOption.OnLoad;
	bitmap.StreamSource = fileStream;
	bitmap.EndInit();
	bitmap.Freeze();

	return bitmap;
}

private void SetBorderedImageSource(BitmapImage bitmap, int imageCounter)
{
	((Image)((BorderedImage)mainWrapPanel.Children[imageCounter]).Child).Source = bitmap;
}

Note 7: Regex to remove prefix which can occurs from 0 to n times

Regex regex = new Regex("^(FBA-)*(.*)$");

foreach (string temp in @"12345
FBA-12345
FBA-FBA-12345
FBA-FBA-FBA-12345
FBA-FBA-FBA-FBA-FBA-FBA-12345
FBA-F-12345
FBA-45678
FBA-FBA-ABC12345
ABCDE".Split(Environment.NewLine.ToCharArray(), StringSplitOptions.RemoveEmptyEntries))
{
	foreach (Match match in regex.Matches(temp))
	{
		Console.WriteLine(match.Groups.Count.ToString() + " - " + match.Groups[match.Groups.Count - 1].Value.ToString());
	}
}

Console.ReadLine();

oder with this Regex can access directly the match “.((?<!FBA-).)*$”.

Note 8 : Event from child class to mother class

internal class Helper
{
    public event EventDelegate MyEvent;
}

public class MainClass
{
    private Helper _helper;

    public event EventDelegate MyEvent
    {
        add { _helper.MyEvent += value; }
        remove { _helper.MyEvent -= value; }
    }
}

Note 9: Load Resource from his name

internal static System.Drawing.Bitmap _011 {
get {
	object obj = ResourceManager.GetObject("_011", resourceCulture);
	return ((System.Drawing.Bitmap)(obj));
}

Note 10: Media key detector

protected override void WndProc(ref Message msg)
{
	if (msg.Msg == 0x319)   // WM_APPCOMMAND message
	{
		// extract cmd from LPARAM (as GET_APPCOMMAND_LPARAM macro does)
		int cmd = (int)((uint)msg.LParam >> 16 & ~0xf000);
		switch (cmd)
		{
			case 13:  // APPCOMMAND_MEDIA_STOP constant
				MessageBox.Show("Stop");
				break;
			case 14:  // APPCOMMAND_MEDIA_PLAY_PAUSE
				MessageBox.Show("Play-Pause");
				break;
			case 11:  // APPCOMMAND_MEDIA_NEXTTRACK
				MessageBox.Show("Next track");
				break;
			case 12:  // APPCOMMAND_MEDIA_PREVIOUSTRACK
				MessageBox.Show("Previous track");
				break;
			default:
				MessageBox.Show("cmd = " + cmd.ToString());
				break;
		}
	}
	base.WndProc(ref msg);
}

Note 11: CLR Assembly with userdefined function in SQL Server
http://msdn.microsoft.com/de-de/library/ms131102.aspx

Note 12: Algorithm Implementation/Strings/Longest common subsequence
http://en.wikibooks.org/wiki/Algorithm_Implementation/Strings/Longest_common_subsequence#C.23

Note 13: Partition (number theory)

private static void Main(string[] args)
{

	foreach (int[] list in Partitions(5, 5, new List()))
	{
		string strTemp = "";
		foreach (int i in list)
			strTemp += " " + i.ToString();
		Console.WriteLine(strTemp);
	}

	Console.ReadLine();
}

private static IEnumerable<int[]> Partitions(int n, int m, List head)
{
	int min = System.Math.Min(n, m);
	for (int i = 1; i <= min; ++i)
	{
		List newHead = new List(head);
		newHead.Add(i);
		if (n == i)
			yield return newHead.ToArray();
		else
			foreach (int[] p in Partitions(n - i, i, newHead))
				yield return p;
	}
}

private static IEnumerable<int[]> Partitions(int n)
{
	return Partitions(n, n, new List());
}

Result:
1 1 1 1 1
2 1 1 1
2 2 1
3 1 1
3 2
4 1
5

Note 14: Generate each class to each dll
1. In a project you add all plugins files
2. Edit the project file to specify which class will generate a plugin library :



	true


	true



3. Add a new target in your project file to generate the plugins library




4. If you want to create the plugins library after each build, add an after build target :



Note 15: How does WCF Asynchron work?
Client -> BeginXXX -> WCF -> Server -> BeginXXX -> Callback (from Client) -> WCF -> Client -> Callback

Note 16: Link to download Sqlite adapter for .Net
http://system.data.sqlite.org/index.html/doc/trunk/www/index.wiki
and provider
http://sourceforge.net/projects/sqlite-dotnet2/files/SQLite%20for%20ADO.NET%202.0/
with configuration




Note 17: Conditions where DataGrid UI Virtualization not work
The WPF DataGrid has UI virtualization feature, but this is undermined by certain circumstances. Virtualization does not work if:
– the DataGrid is inside a ScrollViewer
– grouping is used within the DataGrid
– VirtualizingStackPanel.IsVirtualizing is set to false
– ScrollViewer.CanContentScroll is set to false
– and of course EnableColumnVirtualitation or EnableRowVirtualization stand on false

Note 18: Hide a process from Taskbar

internal class Program
{
	[ComImport,
Guid("56fdf342-fd6d-11d0-958a-006097c9a090"),
InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
	public interface ITaskbarList
	{
		///
		/// Initializes the taskbar list object. This method must be called before any other ITaskbarList methods can be called.
		///
		void HrInit();

		///
		/// Adds an item to the taskbar.
		///
		///A handle to the window to be added to the taskbar.
		void AddTab([In] IntPtr hWnd);

		///
		/// Deletes an item from the taskbar.
		///
		///A handle to the window to be deleted from the taskbar.
		void DeleteTab([In] IntPtr hWnd);

		///
		/// Activates an item on the taskbar. The window is not actually activated; the window's item on the taskbar is merely displayed as active.
		///
		///A handle to the window on the taskbar to be displayed as active.
		void ActivateTab([In] IntPtr hWnd);

		///
		/// Marks a taskbar item as active but does not visually activate it.
		///
		///A handle to the window to be marked as active.
		void SetActiveAlt([In] IntPtr hWnd);
	}

	[ComImport]
	[Guid("56fdf344-fd6d-11d0-958a-006097c9a090")]
	public class CoTaskbarList
	{
	}

	private static void Main(string[] args)
	{
		Process procNotePad = Process.GetProcesses().Where(x => x.ProcessName == "notepad").FirstOrDefault();
		if (procNotePad != null)
		{
			IntPtr windowHandle = procNotePad.MainWindowHandle;
			var taskBarList = (ITaskbarList)new CoTaskbarList();
			taskBarList.HrInit();
			taskBarList.DeleteTab(windowHandle);
		}
		Console.ReadLine();
	}
}

Leave a Reply

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