Monday, April 26, 2010

Change Selected Text (highlighted text) in Visual Studio 2010

I always optimize my settings when using Remote Desktop, but unfortunately it has a few bad side effects. Although I didn’t have this problem in Visual Studio 2008, with 2010 I find that selected text is almost impossible to see. For some bizarre reason, it is only shows highlighting once I change focus.

Tool –> Options –> Environment –> Fonts and Colors –> Display items: –> Selected Text

image 

Before (I am not making this up!)

image

After (Yay!)

image

Force the browser to scroll to the top using Silverlight

I recently had an master / details scenario where the details popup was much larger than the master control. If I all the way down in the details popup and then returned to the master control, the browser would maintain the scrolling position and the master control would no longer be visible unless I scrolled up. Fortunately Silverlight provides a mechanism for calling JavaScript functions. ;)

Steps:

1.  Add a top anchor tag to the top of the HTML page rendering your Silverlight object.

     <a name=”top” />

2.  Add a JavaScript function to the same page.

     function ScrollToTop { location.href=”#top”; }

3.  Use the following code to call from Silverlight:

     using System.Windows.Browser;
     …
     HtmlPage.Window.Invoke(“ScrollToTop”);

Note: I tried using “windows.scroll(0, 0)” in my JavaScript function to no avail, but using an anchor tag worked just fine.

Friday, April 16, 2010

Change tab order of documents being opened in Visual Studio 2010

At some point between 2003 and 2008, Microsoft changed the default order of where tabs appeared in Visual Studio. In the old version, new document tabs would appear to the right. The new version switched this behavior. I always preferred the old order and now it is an option.

Tools –> Options –> Environment –> Documents

image

Thursday, April 15, 2010

Creating a globally accessible property in a Silverlight application

You have created a Silverlight application and have a property that you want to make globally available. Although you could add it to the Resources collection of your App object, you really want to know every time the property has changed. If you were in a UserControl, you could create dependency properties that allow you to listen for PropertyChanged events, but these would not be global. Handling this at the application level would be best, but because App doesn’t derive from DependencyObject like UserControls, you cannot implement the SetValue and GetValue methods that are required for writing dependency properties.

It turns out that the solution ends up being easier than you think. Essentially you will be encapsulating an object within the App that implements INotifyPropertyChanged. You will then add PropertyChanged events anywhere you want to know where the property changes.

Steps:
1. Create a new Silverlight Application.
2. Add a new class that implements INotifyPropertyChanged. I will call mine “GroupNameObject”. Make sure to add a System.ComponentModel using statement.

using System.ComponentModel;

public class GroupNameObject : INotifyPropertyChanged
{
private string groupName;

public event PropertyChangedEventHandler PropertyChanged;

public GroupNameObject(string value)
{
this.groupName = value;
}

public string GroupName
{
get
{
return groupName;
}
set
{
groupName= value;
OnPropertyChanged("GroupName");
}
}

protected void OnPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
}

3. In your App class add a public property of the type you just created.

public GroupNameObject GroupName = new GroupNameObject("Admin");

4. Now in any UserControl constructor, you can subscribe to the PropertyChanged event and add an event handler.

public MainPage()
{
InitializeComponent();
//Notice how App.Current can be cast to your App instance.
((App)App.Current).GroupName.PropertyChanged +=
new System.ComponentModel.PropertyChangedEventHandler(GroupName_PropertyChanged);
}

void GroupName_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
{
//Disable update button if group is viewer
if(((GroupameObject)sender).GroupName == “Viewer”)
{
updateButton.IsEnabled = false;
}

}

Now any time the property gets changed, you can listen to it and act accordingly. Obviously you would use an object or enum instead of a string here, but I kept it easy for illustration purposes. Also, if you are using MVVM, you should handle this in your ViewModel classes. Happy coding!

Tuesday, April 13, 2010

Create enum based Collection Dependency Properties and set them declaratively in XAML

I was recently updating a Silverlight web part that involved a very complicated form. I came across a scenario where I needed to determine a user’s SharePoint group and then disable or enable a user control according to their permissions. I already had code that passed the user’s credentials and mapped the custom SharePoint groups to an enum. Since there were many databound controls with many different permissions, the main goal was to be able to easily set these permissions declaratively within XAML.

Ultimately, I wanted something that looked like the following. In this example, only a Manager or Supervisor have access to edit the control. The CurrentGroup property is databound and if it returned anything other than Manager or Supervisor, the control would be disabled.

        <localCtrl:MyPermissionTextBox x:Name="permissionCtrl" CurrentGroup="{Binding CurrentGroup}">
<
localCtrl:MyPermissionTextBox.PermissionGroups>
<
localCtrl:PermissionGroupItem Group="Manager" />
<
localCtrl:PermissionGroupItem Group="Supervisor" />
</
localCtrl:MyPermissionTextBox.PermissionGroups>
</
localCtrl:MyPermissionTextBox>


In a nutshell, you will want to do the following steps:



1. Create an item class that encapsulates your enum and stores it as a property.

2. Create a collection class that derives from ObservableCollection<T> (where T is the item class type). Add a read-only property that retrieves your list of enums into a a generic list.


3. Add a UserControl that has two dependency properties: one for the collection class, and one for the current group.


4. In the UserControl’s Loaded event handler, disable or enable the control by checking if the current group is in the list of groups for the control.


5. Add the UserControl to a layout page and set all of the properties in XAML.



Permission UserControl XAML


1. Add a Silverlight UserControl to your project. I named mine “MyPermissionTextBox”.

2. Update the XAML to include a Loaded event handler for the UserControl and a TextBox control with the name “MyControl”.



<UserControl x:Class="MyProject.Controls.MyPermissionTextBox"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="400" Loaded="UserControl_Loaded">
<
Grid x:Name="LayoutRoot" Background="White">
<
TextBox Name="MyControl" Width="150" Height="20" />
</
Grid>
</
UserControl>



Permission UserControl Code Behind



using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Windows;
using System.Windows.Controls;

namespace MyProject.Controls
{
public enum PermissionGroup { Viewer, Member, Manager, SrManager, Supervisor, Admin }

public partial class MyPermissionTextBox : UserControl
{
public static readonly DependencyProperty PermissionGroupsProperty =
DependencyProperty.Register("PermissionGroups", typeof(PermissionGroupItemCollection), typeof(MyPermissionTextBox),
new PropertyMetadata(null, OnPermissionGroupsPropertyChanged));

private static void OnPermissionGroupsPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
MyPermissionTextBox source = (MyPermissionTextBox)d;
source.PermissionGroups = (PermissionGroupItemCollection)e.NewValue;
}

public PermissionGroupItemCollection PermissionGroups
{
get
{
if (GetValue(PermissionGroupsProperty) == null)
{
return new PermissionGroupItemCollection();
}
else
{
return (PermissionGroupItemCollection)GetValue(PermissionGroupsProperty);
}
}
set
{
if (value is PermissionGroupItemCollection)
{
MyControl.IsEnabled = ((PermissionGroupItemCollection)value).Values.Contains(CurrentGroup);
SetValue(PermissionGroupsProperty, value);
}
else
{
MyControl.IsEnabled = false;
}
}
}

public static readonly DependencyProperty CurrentGroupProperty =
DependencyProperty.Register("CurrentGroup", typeof(PermissionGroup), typeof(MyPermissionTextBox),
new PropertyMetadata(PermissionGroup.Viewers, OnCurrentGroupPropertyChanged));

private static void OnCurrentGroupPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
MyPermissionTextBox source = (MyPermissionTextBox)d;
source.CurrentGroup = (PermissionGroup)e.NewValue;
}

public PermissionGroup CurrentGroup
{
get
{
return (PermissionGroup)GetValue(CurrentGroupProperty);
}
set
{
SetValue(CurrentGroupProperty, value);
}
}

public MyPermissionTextBox()
{
InitializeComponent();
PermissionGroups = new PermissionGroupItemCollection();
}

private void UserControl_Loaded(object sender, RoutedEventArgs e)
{
MyControl.IsEnabled = PermissionGroups.Values.Contains(CurrentGroup);
}
}

public class PermissionGroupItem
{
public PermissionGroup Group { get; set; }
}

public class PermissionGroupItemCollection : ObservableCollection<PermissionGroupItem>
{
public List<PermissionGroup> Values
{
get
{
return (from n in this.Items select n.Group).ToList();
}
}
}
}



Test UserControl XAML



Note: You will need to handle the Binding for CurrentGroup. In this example I have simply hard-coded. In this case the control would be disabled as the Viewer is not in the list of Permissions.




<UserControl x:Class="MyProject.Controls.Test"

xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"

xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"

xmlns:local="clr-namespace:MyProject"

xmlns:localCtrl="clr-namespace:MyProject.Controls" Height="300"Width="300">

<
Grid x:Name="LayoutRoot"Background="White"HorizontalAlignment="Stretch">

<
localCtrl:MyPermissionTextBox x:Name="permissionCtrl"CurrentGroup="Viewer">

<
localCtrl:MyPermissionTextBox.PermissionGroups>

<
localCtrl:PermissionGroupItem Group="Manager" />

<
localCtrl:PermissionGroupItem Group="Supervisor" />

</
localCtrl:MyPermissionTextBox.PermissionGroups>

</
localCtrl:MyPermissionTextBox>

<
TextBlock FontSize="10">

<
TextBlock.Style>

<
Style>

<
SetterProperty="FontSize"Value="10" />

</
Style>

</
TextBlock.Style>

</
TextBlock>

</
Grid>

</
UserControl>



Note: All code done in Visual Studio 2010 RTM.


Friday, February 19, 2010

Create a sample text generator system tray tool with C#

There are a ton of great websites that allow you to generate sample text, but I’ve always wanted one that I can access quickly and easily, especially when I am doing some testing. Here is one that can be easily created and runs in your system tray. The code is simple enough that you can add more options like DBCS text generator.

image

Steps
1. Open Visual Studio and create a Windows Forms Application.
2. Add a new or existing Icon File to be shown in your system tray.
3. Add a ContextMenuStrip control the the form and rename it “contextMenuStrip”.
4. Add a NotifyIcon control to your form and rename it “notifyIcon”.
i. Change the Text to “TextGenerator”.
ii. Change the Icon to the one you added in Step 2.
iii. Change the ContextMenuStrip to the one in Step 3.
5. Add the following code to the Form code behind. (Alternatively you can use the designer to some of this code, but I find it more scalable if I do it in code.)

using System;
using System.Diagnostics;
using System.Windows.Forms;

namespace TextGenerator
{
public partial class Form1 : Form
{
public bool ShowTooltips { get; set; }
public int DefaultCharLength { get; set; }
public string SampleText = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec consequat " +
"dolor auctor tortor tincidunt tristique sit amet et arcu. Vivamus dui risus, hendrerit quis rhoncus" +
"vel, consequat ut augue. Quisque congue nisi id enim lobortis vitae pellentesque nulla euismod." +
"Aenean ante risus, feugiat vel facilisis non, iaculis ac augue. Phasellus in mollis est. Suspendisse" +
"potenti. Vestibulum gravida sem enim. Vestibulum vel dui id odio vulputate fringilla. Curabitur " +
"bibendum lorem a nisi posuere sit amet tincidunt diam condimentum. Fusce in tellus urna. Suspendisse" +
"condimentum tortor et mi luctus facilisis. Fusce tincidunt augue vitae odio luctus posuere. Phasellus" +
"ac turpis metus, pharetra tempor lectus. Sed eget massa sit amet lacus faucibus blandit in a risus." +
"Phasellus dui dolor, pulvinar vitae cursus pharetra, porttitor in augue. Donec tristique dignissim " +
"diam in sollicitudin. Integer luctus elit a orci tristique sit amet pulvinar erat tempor. Maecenas " +
"sit amet aliquam libero. Sed tincidunt justo at velit sollicitudin vel vehicula turpis ultrices. " +
"Etiam erat nulla, vehicula non viverra non, porta eu elit. Proin commodo adipiscing nisl nec pretium." +
"Nam lacinia posuere varius. Cras mollis rutrum felis, venenatis lobortis mi imperdiet non. Lorem ipsum" +
"dolor sit amet, consectetur adipiscing elit. Nam id nisi lorem, non pulvinar erat. Donec sit amet velit" +
"eu velit varius imperdiet sit amet vitae leo. Nulla malesuada, dolor sit amet tincidunt fermentum, " +
"mauris nisl posuere nisi, a consequat leo risus ut nibh. In a sapien eu lectus lobortis lacinia. " +
"Pellentesque sit amet lacus sem, non molestie sapien. Duis at enim magna. Integer vitae mi purus, id " +
"rutrum neque. Mauris vitae sem nulla, at accumsan odio. Quisque pulvinar, urna ut aliquam tristique, " +
"magna magna ornare tortor, ut adipiscing nunc nisi et ipsum. Nam porttitor sodales porta. Cras " +
"ullamcorper libero ut sem dapibus ac dapibus tellus scelerisque. Mauris a nisi nec odio varius " +
"iaculis. Integer vel massa eget nunco volutpati.";
public Form1()
{
InitializeComponent();
this.WindowState = FormWindowState.Minimized;
}

private void Form1_Load(object sender, EventArgs e)
{
ShowTooltips = false;
DefaultCharLength = 100;
this.Visible = false;
this.WindowState = FormWindowState.Minimized;

if (Process.GetProcessesByName(Process.GetCurrentProcess().ProcessName).Length > 1)
{
MessageBox.Show("An instance of TextGenerator is already running.\r\nCheck your system tray.");
System.Threading.Thread.Sleep(3000);
this.Close();
}

ToolStripMenuItem defaultText = new ToolStripMenuItem("Default Character Length");
ToolStripMenuItem defaultText50 = new ToolStripMenuItem("50");
defaultText50.Click += new EventHandler(defaultText_Click);
ToolStripMenuItem defaultText100 = new ToolStripMenuItem("100");
defaultText100.Checked = true;
defaultText100.Click += new EventHandler(defaultText_Click);
ToolStripMenuItem defaultText250 = new ToolStripMenuItem("250");
defaultText250.Click += new EventHandler(defaultText_Click);
ToolStripMenuItem defaultText500 = new ToolStripMenuItem("500");
defaultText500.Click += new EventHandler(defaultText_Click);
ToolStripMenuItem defaultText1000 = new ToolStripMenuItem("1000");
defaultText1000.Click += new EventHandler(defaultText_Click);
ToolStripMenuItem defaultText2000 = new ToolStripMenuItem("2000");
defaultText2000.Click += new EventHandler(defaultText_Click);
defaultText.DropDownItems.Add(defaultText50);
defaultText.DropDownItems.Add(defaultText100);
defaultText.DropDownItems.Add(defaultText250);
defaultText.DropDownItems.Add(defaultText500);
defaultText.DropDownItems.Add(defaultText1000);
defaultText.DropDownItems.Add(defaultText2000);

ToolStripMenuItem copy50 = new ToolStripMenuItem("Copy 50") { Tag = 50 };
copy50.Click += new EventHandler(copy_Click);
ToolStripMenuItem copy100 = new ToolStripMenuItem("Copy 100") { Tag = 100 };
copy100.Click += new EventHandler(copy_Click);
ToolStripMenuItem copy250 = new ToolStripMenuItem("Copy 250") { Tag = 250 };
copy250.Click += new EventHandler(copy_Click);
ToolStripMenuItem copy500 = new ToolStripMenuItem("Copy 500") { Tag = 500 };
copy500.Click += new EventHandler(copy_Click);
ToolStripMenuItem copy1000 = new ToolStripMenuItem("Copy 1000") { Tag = 1000 };
copy1000.Click += new EventHandler(copy_Click);
ToolStripMenuItem copy2000 = new ToolStripMenuItem("Copy 2000") { Tag = 2000 };
copy2000.Click += new EventHandler(copy_Click);

ToolStripMenuItem exit = new ToolStripMenuItem("Exit");
exit.Click += new EventHandler(exit_Click);

ToolStripMenuItem options = new ToolStripMenuItem("Options");
ToolStripMenuItem showToolTipItem = new ToolStripMenuItem("Show Tooltips");
showToolTipItem.Click += new EventHandler(showToolTipItem_Click);
options.DropDownItems.Add(showToolTipItem);

contextMenuStrip.Items.Add(defaultText);
contextMenuStrip.Items.Add(copy50);
contextMenuStrip.Items.Add(copy100);
contextMenuStrip.Items.Add(copy250);
contextMenuStrip.Items.Add(copy500);
contextMenuStrip.Items.Add(copy1000);
contextMenuStrip.Items.Add(copy2000);

contextMenuStrip.Items.Add(new ToolStripSeparator());

contextMenuStrip.Items.Add(options);
contextMenuStrip.Items.Add(exit);
}

void showToolTipItem_Click(object sender, EventArgs e)
{
ToolStripMenuItem showToolTipItem = sender as ToolStripMenuItem;
ShowTooltips = !showToolTipItem.Checked;
showToolTipItem.Checked = !showToolTipItem.Checked;
}


void exit_Click(object sender, EventArgs e)
{
this.Close();
}

void defaultText_Click(object sender, EventArgs e)
{
foreach (ToolStripMenuItem childItem in ((ToolStripMenuItem)((ToolStripMenuItem)sender).OwnerItem).DropDownItems)
{
childItem.Checked = false;
}
((ToolStripMenuItem)sender).Checked = true;
DefaultCharLength = Convert.ToInt32(((ToolStripMenuItem)sender).Text);
CopyToClipboard(DefaultCharLength);
}

void copy_Click(object sender, EventArgs e)
{
CopyToClipboard(Convert.ToInt32(((ToolStripMenuItem)sender).Tag));
}

private void notifyIcon_MouseClick(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
CopyToClipboard(DefaultCharLength);
}
}

private void CopyToClipboard(int characters)
{
try
{
Clipboard.SetText(SampleText.Substring(0, characters));
if (ShowTooltips)
{
notifyIcon.ShowBalloonTip(50, "TextGenerator", "Copied " + characters.ToString() + " characters to the clipboard.", ToolTipIcon.Info);
}
}
catch (Exception ex)
{
notifyIcon.ShowBalloonTip(10, "TextGenerator", "Unknown Error: " + ex.ToString(), ToolTipIcon.Error);
}
}
}
}
6. Hit F5 and run!


Instructions
1. Left-Click to copy default characters.
2. Right-click to copy a different amount of characters or set the default character link.
References
Sample text taken from LoremIpsum.

Tuesday, February 16, 2010

Download SharePoint List Attachments – Code Sample

Here is a simple code sample for downloading SharePoint List Item attachments. When the code is run all attachments are downloaded. Subfolders are created based on the List Item ID.

Code Sample

using System.IO;
using Microsoft.SharePoint; //Located: C:\Program Files\Common Files\microsoft shared\web server extensions\12\ISAPI
...
static void Main(string[] args)
{
try
{
DownloadListAttachments(@"http://portalname/webname/", "listname", @"c:\Temp\Attachments\");
}
catch (Exception ex)
{
//TODO: Handle exception
}
}


public void DownloadListAttachments(string siteUrl, string listName, 
string downloadLocation)
{
string downloadItemLocation = string.Empty;
using (SPSite site = new SPSite(siteUrl))
{
using (SPWeb web = site.OpenWeb())
{
foreach (SPFolder folder in
web.Folders["Lists"].SubFolders[listName].SubFolders["Attachments"].SubFolders)
{
foreach (SPFile file in folder.Files)
{
byte[] binFile = file.OpenBinary();
downloadItemLocation = downloadLocation + "\\" + folder.Name + "\\";
if (!Directory.Exists(downloadItemLocation))
{
Directory.CreateDirectory(downloadItemLocation);
}
System.IO.FileStream fstream =
System.IO.File.Create(downloadItemLocation + file.Name);
fstream.Write(binFile, 0, binFile.Length);
}
}
}
}
}


Screenshots
image


image 



image



image





References 
How to programmatically download attachments from list items in Windows SharePoint Services