Developing on Staxmanade

unbound TFS project - how do I get the offline changes checked in?

Our company's code is currently hosted at a third party development shop and once in a while my solution gets marked as "offline". When I right click on the root of the solution node I get an option to "Go Online". If I'm in this state and I go online, it connects to TFS and scans through the entire solution looking for modified files.

So yesterday their internet was down ALL DAY (what a pain, I never realized how dependent I was on source control). So I was trying to edit a file and V.S. kept trying to check it out from TFS before making the edit, which would fail, and leave the file in a read only state. This sucked because I wasn't able make changes to any file.

I did the first thing I knew of on how to get my files in a state that I could work with for the day. I went to File -> Source Control -> Change Source Control and proceeded to "Unbind" each project from tfs. This allowed me to work for the day, make changes, etc without being road blocked by TFS.

Then this morning I came to work and the companies internet was working, and I was able to get to TFS successfully. I re-opened the solution, and unfortuantely in my "Pending Changes" tab there was only a couple files checked out. This was not good because I knew I made many more changes than it thought I had.

This is where the first paragraph above comes into play... I wanted visual studio to figure out all the things I did yesterday because I knew I wasn't going to remember all the files I touched. So I googled about VS's offline/online modes and ran across this blog.

http://blogs.msdn.com/benryan/archive/2007/12/12/when-and-how-does-my-solution-go-offline.aspx

After reading some of the details about how VS works with TFS I decided to try and get my solution "offline" so I could bring it back online and allow it to figure out my changed files...

To accomplish this I opened up regedit. Followed Ben's pointer to

HKEY_CURRENT_USER\Software\Microsoft\VisualStudio\9.0\TeamFoundation\Servers\\

In there I set
AutoReconnect=0
Offline=1


When I re-opened my solution. It opened in offline mode. I was then able to bring the solution online and as expected, it noticed all the changes I made yesterday. (THANK YOU TFS, would have been nice to do this w/out hacking the registry though).


Comments

Staxmanade
If I click on my solution in the "Solution Explorer" the only buttons if have are... "Properties", "Add New Solution Folder", and "Refresh Status" (this is a VisualSVN button)...

is there some sort of option I need to enable to see this command?
justncase
There is a button on the top of the solution explorer for going offline/online. It's awfully convenient.

How can C# variable have an @ sign in front of it?

I remember a year ago I noticed in some code a coworker put together had a variable with an @ sign in front of it. At first I was baffled that it even compiled. I asked my c-worker about it and he said he had no clue as to why it was there and what it was for... so then I spent some time googling and couldn't find anything on the net describing this and why it compiled.

basically what I'm talking about is if you have some code

private void MyMethod(string myparam)
{
    int a = @myparam.Length;
}

Notice the @ sign in front of the myparam variable... That is what I saw in my co-workers code and I couldn't explain how that worked...

now, nearly a year later I was perusing through the SLUnity framework on codeplex [] and saw the @ sign again...

public void UnregisterSubscriber(string publishedEventName, EventHandler subscriber)
{
    PublishedEvent @event = GetEvent(publishedEventName);
    @event.RemoveSubscriber(subscriber);
    RemoveDeadEvents();
}

I did some more googling and still can't find anything, (I'm sure it's out there, just can't put together the right search criteria)...

Then I went back to the code, looked at it for a minute, and it dawned on me that "event" is a keyword in c#... Then I thought, maybe this is what you can do to use a C# keyword in another context than the desired reason to have the keyword.

So I wrote a little test to see if this hypothesis was correct.

private static void MyMethod(string class)
{
    int a = class.Length;
}

this won't compile because of the "class" keyword...

then I put the @ sign in front of class

private static void MyMethod(string @class)
{
    int a = @class.Length;
}

and it not only compiled, but you also get intellisense on the variable...

How cool...

I'm not sure I would do that on a regular basis, seems like it might be a bit of a pain to write... However maybe framework code may need to have this to allow it to be more readable to it's consumers? Anyone know why on this?

Comments

Anonymous
nice one :), had me fooled for a bit too when I found a variable named @@delegate
Justin Chase
That is exactly what it is for, so you can use reserved words for variable names. You'll see this in some of the .NET framework even, with method parameters named @object in some places. I suspect it was added to C# specifically to be compatible with libraries written in other languages so that when it generates methods for you and uses the defined parameter name it won't have a compile error if it happens to be a C# keyword.

WCF Service Proxy inside Silverlight with a generic type

We've implemented a silverlight 2 business application communicating through WCF and I just had to blog about something I found possible in .net in general...

On the server side we have a very simple generic object used to communicate validation issues back to our Silverlight client when a web service method is called. Here's the basic interface.

public interface IValidatedResult<T>
{
  T Result { get; set; }
  List<string> ValidationIssues { get; set; }
}

Now if you had a method that exposed this generic result object through your web service...

public ValidatedResult<long> StringLength(string param1)
{
  return new ValidatedResult<long>(param1.Length);
}

Now if you to to the silverlight project tell Visual Studio to generate a proxy for you (against the service you just created) it will give you a proxy with an object that is not generic. You end up with some autogenerated code that looks more like...

public partial class ValidatedResultOflong : object, System.ComponentModel.INotifyPropertyChanged
{

  private long ResultField;

  private System.Collections.ObjectModel.ObservableCollection<string> ValidationIssuesField;

  [System.Runtime.Serialization.DataMemberAttribute()]
  public long Result
  {
    get
    {
      return this.ResultField;
    }
    set
    {
      if ((this.ResultField.Equals(value) != true))
      {
        this.ResultField = value;
        this.RaisePropertyChanged("Result");
      }
    }
  }

  [System.Runtime.Serialization.DataMemberAttribute()]
  public System.Collections.ObjectModel.ObservableCollection<string> ValidationIssues
  {
    get
    {
      return this.ValidationIssuesField;
    }
    set
    {
      if ((object.ReferenceEquals(this.ValidationIssuesField, value) != true))
      {
        this.ValidationIssuesField = value;
        this.RaisePropertyChanged("ValidationIssues");
      }
    }
  }

  // stripped out the INotifyPropertyChanged goo
}

Notice the non generic type ValidatedResultOflong that was generated? This non generic object is great and all except when you want to do some generic processing on these objects. For things like error handling, validation handling... if we had to create different handling methods for all of these different objects, that could prove to be laborious...

Say I wanted to write an extension method to do some generic processing on all objects that are a ValidatedResult of T... Unfortunately there is no common signature we can key off of to write this method with the proxy code generated by V.S.

Then I thought I would try something... Can you have a partial class in one area which contains a common property, in this case each contains a "Result" and a "ValidationIssues" property and another partial class in a different location that declares it implements an interface which defines that "Result" and "ValidationIssues" property... and would that compile?

So I wrote my first test...

Here is our auto generated partial class simulated...

public partial class Foo
{
  public bool Result { get; set; }
}

I then wrote a generic result of T to define the object has a Result property.

public interface IResult<T>
{
  T Result { get; set; }
}

And now the specific implementation with a long Result type.

public partial class Foo : IResult<long> {}

After putting those three structures together I hit Build in VS and to my surprise (at first, but now it makes total sense) it compiled... This was great news. This meant I could create a generic processor for my wcf objects in silverlight... I'll show how on the silverlight side below...

I defined the validated result contract as follows...

public interface IResultProperty<T>
{
  T Result { get; }
}

public interface IValidatedResult<T> : IResultProperty<T>
{
  List<string> ValidationIssues { get; set; }
}

This meant I could quickly create partial class stubs for each of the wcf generated objects that looked like... ValidatedResultOf{object} and would define to the compiler that all these objects truly implemented the ValidationIssues and Result property.

Here's an example of the partial class for the ValidatedResultOflong

public partial class ValidatedResultOflong : IValidatedResult<long> { }

With that in place, this meant I could create some generic handling methods for all of my objects that now implement IValidatedResult<T>...

public static bool HasValidationIssues<T>(this T validatedResult)
where T : IValidatedResult<T>
{
  if (validatedResult != null &amp;&amp;
  validatedResult.ValidationIssues != null &amp;&amp;
  validatedResult.ValidationIssues.Count > 0)
  return true;
  else
  return false;
}

Don't know if i've very heard anyone talk about one partial class containing some property or common method and being able to create another partial class that defines the interface contract for that... Pretty cool...

Comments

Jason.Jarrett
Interesting observation. Thanks for sharing.

I haven't pushed it very far (bool, string, MyCustomObject, etc)

Boris Modylevsky
Thanks for the post. It's really exciting to receive a proxy of Generic class. It really works smoothly with "simple" classes. But more complex ones result with random names in Silverlight proxy. For example, my `_SimpleTree_` became _SimpleTreeNodeOfItemErNMAaNV_
Jason.Jarrett
Ok, I quickly threw an example together. I didn't comment much, but the code's there and "works on my box..."
Let me know if you have any troubles either understanding it, or getting it working.

I've never used this file host service, but giving it a try... I've placed the project here [ http://www.filesavr.com/validatedresultsample](http://www.filesavr.com/validatedresultsample)

Also the only concepts to really look at here are the `ValidatedResult<T>`` and the notion of the partial classes used along side the VS service reference code to get the extension methods to work... This by no means follows best practices with some of this stuff.

Good luck!</div>
greg
... very much appreciated!!
Jason.Jarrett
Greg,
I will try to put together an example and post it here soon.</div>
greg
... too many snippets for me to get the big picture... It looks promising, though. Do you have a simple working example you could post? I am interested in the generic proxy concept whether used within Silverlight or otherwise. Thanks in advance.

UnitDriven's UI Gets a Minor Makeover

I had some time to play around with and learn WPF within Silverlight. It's a modest start, but I just had to blog about it...

We've started a project at my current job using Silverlight. Researching different framework options I ran across the UnitDriven project on codeplex. After downloading and checking out the silverlight testing UI...











I decided this was a place I could take a stab at learning some silverlight UI. ok... So it's getting late and it's certainly not perfect, but here's where I am now.












The only really tricky piece was... The original UI used nested ListBox controls which threw me down a path of thinking the program was broken... basically with a ListBox inside of a ListBox you have to select the first item, then the sub item, and in this application, only then, can you select the "Run" button to execute the unit test... I spent time looking through code trying to figure out if there was a bug in the testing contexts.

The solution to this was to convert the ListBox to an ItemsControl. Which allowed me to select multiple buttons without having to first select the ListBox sub item...

I then had to wrap everything inside of a ScrollViewer because the ItemsControl doesn't create one automatically like the ListBox does.
[EDIT]
Unfortunately wrapping everything in the ScrollViewer removed a feature the older version had, namely, at the top of the control is a display of the # succeeded/# Total. Wrapping everything in the ScrollViewer removed the ability to scroll through tests while that value was being updated during tests...

So I updated the main grid in the XAML, and shifted a few things around to allow this old feature to be seen in the new UI.
[/EDIT]

after that was done, it was basically playing around with different styling elements to end up with the UI above.

It was a good simple exploratoin into some of the Silverlight's WPF capabilities.

Comments

Nermin
Your work on this patch is trully appreciated. That listbox issue was trully annoying one.
Justin Chase
Thanks for the patch, I applied it today.

How best to expose a value that could throw an error?

If you have a class that needs to expose some value (either by a Property, or a "getter" function) and there is a chance that getting this value could cause an exception. How do you best expose that value?

I originally had a Property that exposed some value where, if in a certain state, would throw an exception.

Microsoft FxCop recommends.

Do not explicitly raise exceptions from unexpected locations. There are some methods, such as Equals and GetHashCode, which users do not expect to raise exceptions. Therefore calls to these methods are not commonly wrapped in try catch blocks.

So if FxCop recommends not raising an exception from a Property's getter, we'll just throw it in a function. Come to find out now FxCop says...

Properties should be used instead of Get/Set methods in most situations. Methods are preferable to properties in the following situations: the operation is a conversion, is expensive or has an observable side-effect; the order of execution is important; calling the member twice in succession creates different results; a member is static but returns a mutable value; or the member returns an array.

So, which is the best method?

I went back to the Property method because it really is mimicking the usage of a property...

Any suggestions out there?

BinarySearchOrDefault()

When you need to use BinarySearch on a large List<T>, you need to declare a long to hold the return index value of the search. When the item in the list is not found the value returned from the binary search is negative and depending on it's value can mean different things. However most of the time I use this search method I don't care about these other options. Either give me the value I am searching for or give me the default value of <T>.

I wrote a little helper extension that will return the found object or if the item could not be fount it returns default(T).


public static T BinarySearchOrDefault<T>(this
List<T> list,
T item,
IComparer<T> comparer)
{
int returnIndex = list.BinarySearch(item, comparer);

if (returnIndex >= 0)
return list[returnIndex];
else
return default(T);
}

Timing Debug Code Using Lambda's

In applications that require responsiveness it's sometimes hard, while in the middle of development to test what implementation of some code is faster.

Below I've created an example of an easy way to time some action or group of actions within a method to quickly determine how long it would take to do it one way or another.



public void SomeMethodIAmWorkingOn()
{
TimeAction(
() =>
{
for (int i = 0; i < 100; i++)
SomeMethodIAmTiming();
SomeNextStep();
},
"Timing method SomeMethodIAmTiming 100 times...");
}

public static long TimeAction(
System.Action action,
string
debugNote)
{
long time = TimeAction(action);

System.Diagnostics.Debug.WriteLine(
string.Format(
"TimeAction:{0}ms, NOTE: {1},",
time,
debugNote)
);

return time;
}

public static long TimeAction(
System.Action action)
{
Stopwatch watch = Stopwatch.StartNew();
action();
watch.Stop();
return watch.ElapsedMilliseconds;
}

Comments

Jason.Jarrett
whoops - Thanks for the suggested update...
Anonymous
Lambda, not lamda. ;)