Tag | generics Posts

Before I get started on Generic Classes in .Net, I'd like to give credit to CopySourceAsHtml for my new formatting of code blocks in my blog. I made some of my own enhancements, but I'd still be using the boring black on yellow formatting without CSAH. To learn how to get it to work on VS2008, go here (be sure to read the comments if you are running on XP). We've all used generic classes without thinking much about it. I use List<T> extensively (perhaps abusively). I really only discovered ...
One of the best things about LINQ to SQL is that is really does have solid support for stored procedures. However, it's not quite as friendly as dynamic LINQ to SQL with scalar values because you can't take advantage of anonymous types. Instead you must return an actual known type. Furthermore, this can't be a primitive so you can't return string or bool directly. You also can't use a class that doesn't have a default (parameterless) constructor so that also rules out nullable types like Nullable<bool>. ...
It seems that enums might be the neglected step-child when it comes to Generics and Extensions. I've tried defining generics that are constrained to enums. No luck. I faced much frustration trying to get my generic methods to work. I finally came up with a method that meets my need. But, I had to add a little bit of run-time type checking. Instead of repeating Enum.Parse throughout my code, I wanted to create a simple generic extension method that would do it for me. I just discovered that my extension ...
So, I've settled on a pattern that I found somewhere on the web to safely override Equals. I don't remember where I found it, and there are certainly many other good implementations (probably better than mine). Regardless, I found that I do have a repeating pattern. I decided to set out to limit this duplication if I could. Here is what I came up with. 1: public static bool SafeEquals<T>( this T left, object right, Predicate<T> test ) 2: { 3: if( right != null && right.GetType().Equals( ...
The string.Join method can come in handy when you want a comma separated list of strings. However, there's a major limitation. To use it, you must provide a one-dimensional string array. What if you have a collection of objects and you want to "Join" a property on the objects (e.g., a comma separated list of IDs). Well, since I couldn't find anything within the framework that would do this for me, I wrote an extension method that meets my need. Updated from James Curran's suggestion in the comments. ...
The following error can occur when executing the .DataBind() method on a Dundas chart object within an ASP.Net page (.Net 3.0): Series data points do not support values of type "myclass", only values of these types can be used: Double, Decimal, Single, int, long, uint, ulong, String, DateTime, short, ushort. I had set the DataSource property to a generics List of myclass objects (List<myclass>). It turns out that this error is caused by a mismatch between the type of objects within the list ...
At work in order for us to submit code against certain code bases, we go through code reviews. When my code was getting reviewed a fellow developer pointed out how I was raising events compared to how he was raising events. He was using Event handler, and I was going through the events invocation list. Which one is correct? I think it all depends on how you want to control your events. The one issue I thought of, was if I use Event Handler and one of the callers registering for the event throws an ...
*Moved to: Creating a better TFS Sticky Buddy (Core) Over the last week I have been looking at the source for the Family.Show application from Vertigo. I needed to look at methods of presentation of hierarchical information graphically using WPF and I saw this as a good representation of that sort of data. So I se about not only converting it to VB.NET but adding generics to the mix. The first part of the application is the core objects that represent the data and allow interaction in a way that ...
Hello everyone This is my first blog entry at this site and first in a couple of years, but I wanted to share something I created with some help. Since generics came out with VS 2005 I wondered if it were possible to create a completely generic data access layer. I also wanted to take advantage of some cool features like custom attributes, enterprise library, and reflection. One that could get and update objects regardless of the type of object being manipulated. With the help of some great authors ...
since i have already posted basic ContraVariance in delegate, i am not going to go thru the same again, those of you who had missed my earlier post can refer here here is an example of using generics with contravariance namespace ContravarianceWithGenerics { public interface IEquity { string ToString(); string Save(); } //base class abstract class Equity : IEquity { int _price; public Equity(int Price) { _price = Price; } public override string ToString() { return GetType().Name + " : " + _price; ...
Time for another adventure in F#, covering the 101 level basics of the language and why I think it's useful and how it can even help your C# as well. This time, I want to spend a good deal of time on pattern matching and a few other topics. Where We Are Before we begin today, let's catch up to where we are today: Part 1 - Basic functional programming Part 2 - Currying and Tuples Part 3 - Scope, Recursion and Anonymous Functions Part 4 - History of F#, Operators and Lists So, today, like I mentioned ...
Time for another adventure in F#, covering the 101 level basics of the language and why I love it as much as I do. This time we're going to cover some topics such as custom operators, lists and so on. As I want to stress in every installment of this series, the importance of functional programming and its influence on the .NET framework. Don Syme, the creator of F# was instrumental in bringing generics into the .NET framework. With such things as lambdas, object initializers, collection initializers, ...
It seems that I have encountered a scenario where many aspects of C# 2.0+ come into play. I needed to handle conversion from an IDataReader.GetValue() result to a generic type, including Nullable<>. It took me a while to figure it out and with a little help from this snippet, I was quite please with the result. So, I decided to share. 1: private static T NullValue<T>( object testValue, T nullValue ) 2: { 3: T returnValue; 4: if( testValue is DBNull ) 5: { 6: returnValue = nullValue; 7: ...
Covariance and contravariance provide a degree of flexibility when you match method signatures with delegate types. Covariance permits a method to have a more derived return type than what is defined in the delegate. Contravariance permits a method with parameter types that are less derived than in the delegate type. contravariance example: This example demonstrates how delegates can be used with methods that have parameters of a type that are base types of the delegate signature parameter type. ...
Generics is a new feature in .NET 2.0 which allows us to create a data structure without committing to a specific data type. In the early age of .net 2.0 (i.e. .net 1.x), while using custom entity model in our application data architecture, we had to create a separate class regarding the collection for each of custom entity. The custom entity public class SystemUser { public string _Name, _Password; public SystemUser(string name, string password) { _Name = name; _Password = password; } public string ...
In the project I'm working in, we use generics a lot - I mean a LOT! Most of the classes we create are also generic types - it provides some niceties that way. As the classes grew, eventually I got to a point where I want to put in a static function that doesn't deal with the generic type, something like below: public abstract class Container<T> { private T _content; public T Content { get { return _content; } set { _content = value; } } public static void SomeStaticFunctionNotInvolv... ...
One of my colleagues at Tyson Foods arranged to have Jean-Paul S. Boodhoo give a Nothin' But Dot Net Training class. I saw the opportunity to have him present at our use group since the training was the same week as our meeting. Jean-Paul was gracious enough to agree to present on Generics: They're no just for collections. He has also agreed to help me launch a Podcast I have been wanting to start called Let's Talk Code!. Thanks, JP for helping get this started. Generics: They’re not just for collectionsIn ...
Few weeks ago i was training our offshore team on WCF and WSSF. while the guys were doing hands on, they had noticed that the Generic List what they were returning from WCF service was converted to Array and they had no clue why it was happening. Answer : Because web services / WCF Service are platform-agnostic, they need to use the most primitive data types. Scenerio 1 : what would happen if your web service would be consumed by a .NET 1.x application, where no generics are available. Scenerio 2 ...
UPDATE: THIS DEAL HAS EXPIRED IT SEEMS. SORRY. Almost - but really I consider this a giveaway. Amazon is selling the Wrox Box for $30 USD! That is incredible really. There are four books in this box and there are some really good ones that I have on my shelf! These books and content include: Professional ASP.NET 2.0 Professional C# 2005 Professional .NET Framework 2.0 Professional .NET 2.0 Generics CD-ROM with more than 700 pages of bonus chapters from 10 other .NET 2.0 and SQL Server(TM) 2005 Wrox ...
After finishing the mini-lecture circuit and my often viewed dive into Spec#, I decided to see if anyone else was working in the Design By Contract (DBC) arena with C#. Greg Young and I often talk about this subject and various scenarios where it would make sense, and where it wouldn't. Hopefully we'll hear more from the Spec# team shortly about the futures. It turns out there are two other attempts at what Spec# does, and that's what I'm going to dive into today. Back to Basics So, first, let's ...
C# 2.0 introduced a great new feature to the .NET Type system: generics. Generics are really cool in that they allow you to define template classes; I can use a single class definition to provide a strongly typed collection, for example. They enable some other tricks that I would tend to consider something of a "hack" as well; for example, this expression evaluates to true: 1: typeof(IEnumerable<int>) != typeof(IEnumerable<doubl... This expression is nice because there are some odd class ...
Although current BizTalk release does not support .NET generics it does support concept of genericity at the message level. It is possible, of course, through "untyped" messages or messages that don't have specific type attached to their context. Such messages are represented as System.Xml.XmlDocument type in orchestrations. To read more on message typing aspect of BizTalk please refer to this excellent post by Charles Young. I'd like show practical examples of applying generic programming to typical ...
Being an ultra-introvert, it always freaks me out when a comment I make brings me out from under the radar. I posted on the alt.net list to a thread concerning the pro's and cons. Jeremy Miller posted an opinion on my comment, and I followed up with a comment on the post. As a reflection on all that, I'd like to say that I think that in priciple I'm inclined to agree with Jeremy. In practice, I'm stuck with the Framework that led to the post. I believe that my ideas of what a 'Framework' should be ...
RV.NUG was VERY fortunate to recently have Kathleen Dollard as a guest presenter (courtesy of INETA). If you are (or ever have been) a User Group leader, you know that there are times you just keep on keepin on. You're not quite as enthused, not quite as motivated, but you keep on doing it because that's what UG leaders do. And then, something happens and it's all worth while (again - because these moments do repeat). The December RV.NUG meeting was one of those moments. It was "just another meeting" ...
Tonight, the Roanoke Valley .NET User Group (www.rvnug.org) had the incredible privelege of Kathleen Dollard (http://msmvps.com/blogs/ka... speaking. She was, in a word, AMAZING. She had great energy and passion. She is smart and engaging. And she really knows the topic! She spoke on Refactoring with Generics and she covered Linq and some .NET Framework 3.5. Thanks a bunch Kathleen and INETA ...
To save object state for unit tests we use binary serialization. The object state saved to data file and at the start of the test is loaded from the file. It works OK until the object will be changed in a new version. Fortunately There is no problem when a new field is added, but if a field is deleted or removed, it most likely will cause deserialization exception(see Version Tolerant Serialization, Net Serialization FAQ, Solving Binary serialization versioning conflicts articles for details). Also ...
I've been spending a little too much time reading blogs over the last several months and am starting to crave some more in-depth study, so I decided that I am going to be "old-school" and try to spend more time reading books instead. What I'm Reading Now Here are the three books that I have been bouncing back and forth between lately. As you can tell, I am a little ADD as far as books are concerned and rarely read one at a time (probably why I like blogs so much). On the positive side, I stay motivated ...
My oldest child, Katie, is 3. She absolutely loves playing on the computer, and she's starting to learn her ABC's and 123's. My wife and I get her set up on either Disney's, Sprout's or Noggin's (parents with young children know what I'm talking about) websites, but they just don't seem too navigable for kids, especially at Katie's age. She just wants to point and click, without any real context as to what she is doing. I thought I would take her love of computers (and mine too!), and my desire for ...
I stole, errrr, borrowed this from Glen Gordon's blog... :-) "Join geekSpeak on Wednesday, August 29 at noon PT (3 PM ET) for a revisit from one of our favorite geekSpeak guests - Jim Duffy. Jim's an MVP for Visual Basic so he'll be chock full of information this time on the use of Generics in Visual Basic, and how a programming language with such humble roots handles this elegant construct. Jim's always a riot to talk to, so make sure you bring your best questions - serious and not-so-serious." ...
Reference and value types Structs are value types, while classes are reference types Stack What is executing Heap Heap -> pointers to ref types Value Types – · if a field, -> stack, else (part of an object), -> heap: · box value type to reference type In C#, all the "things" declared with the following list of type declarations are Value types (because they are from System.ValueType): bool , byte , char , decimal , double , enum , float , int , etc Reference Types · Heap · Unbox box reference ...
I'm currently supporting an ASP.NET project that has a lot of code like this using the System.Web.UI.Control.FindC... method to get data from child controls - in this example, from DataListItems belonging to a DataList control: foreach (DataListItem item in employeeDataList.Items) { if (item.ItemType == ListItemType.Item || item.ItemType == ListItemType.AlternatingItem) { if (((HtmlInputCheckBox)item.F... { string positionId = ((Label)item.FindControl("P... ...
Visual WebGui is the .net answer for GWT (Google Web Toolkit). But it’s seems more powerful than GWT even though it’s not coming from Microsoft and yet it’s open source. Still I hadn’t got time to put my hands on deeply but you can feel it by just browsing their web site and checking the features and comparing those with GWT. Not like GWT, in Visual WebGui you can use existing windows controls to create your UI. Major advantage of Visual WebGui over GWT is we can deploy Visual WebGui applications ...
The next meeting of the Columbia Enterprise Developers Guild will be held on June 12th, 2007 at 6 PM in the Midlands Tech Northeast Campus Auditorium. The key presentation topic is Generics. The presenter will be Keith Minder of Logical Advantage. We hope to see everyone at the meeting! New Website! All members and prospective members are asked to please visit the new user group website and complete the user registration. This new website will be the central point to reference user group information ...
We have multi-threading application that uses WaitHandle.WaitAll methods. It works fine, when called from ASP.NET, but when it is called from WinForms test harness, it causes the error "WaitAll for multiple handles on an STA thread is not supported.". I've included the workaround and moved code to helper function. However I needed to call the function with different parameters List<ManualResetEvent> and List<WaitHandle> . Even if ManualResetEvent is derived from WaitHandle, there is no ...
It's now Tuesday lunchtime here in Montreal. Day one of DevTeach for me is now done, with the user group summit taking all day. Some really good information was learned by all, and then the keynote this morning confirmed another DevTeach in November, but now on the west coast in Vancouver. It will be nice to have 2 such conferences annually, and not just piggyback on the shoulders of an american tour, But, today's sessions so far... Introduction to WPF Interesting discussion about what it can do ...
The war for which .NET language will reign supreme just got a little dicier folks. For a while now everybody has been slowly moving toward C# as the defacto .NET language of choice. Big names in the .NET world have been showing off coding samples in C# for a long time, books have been filled with C#-only samples...it seemed that we were all moving toward a new future where semi-colons and curly-brackets would reign supreme. That was...until now. The VB.NET team has launched a new weapon in its quest ...
Visual WebGui is.... User-Friendly – Visual WebGui was designed to be the next VB6 for the web. Simple to program, simple to deploy. With a full WinForms API and design time support you can start developing complex AJAX applications in seconds with no web know-how. Secured – Visual WebGui was designed to provide for military grade secured AJAX applications by eliminating client side service consumption and business logic processing using an empty client concept. The browser is used as a looking glass ...
I thought of a really cool use for generic-like syntax for parameterizing variable declaration beyond types. It would be awesome if generics could be used to specify dimensions within a struct. My case, I wanted to implement a Vector struct with a parametric dimension. So if I was using a vector in R2, I could create the struct as Vector<2>. If in R3, new Vector<3>, and so on. If I was able to do that, my struct could have a stack-allocated array of floats. Without this, my array is forced ...
I was surprised to see the syntax of the new Generic Eventhandler... Using the .net 1.1 way we can declare events using the following steps.. STEP 1: declare a delegate public delegate void DivThreeHandler(object ,DivByThreeEventArgs e); The abobe delegate declares the parameters to be sent to the event handlers.Any class that wants to handle this event needs to have a method that mathces this signature. STEP 2: define the EventArgs derived class public class DivByThreeEventArgs:EvetArgs{ ...........code.......} ...
When you want to create custom events, often you need to pass an event argument, and as often you need only to pass in one parameter - your object. So what you used to do is: public event MyCustomEventHandler MyCustomEvent; public delegate void MyCustomEventHandler(MyCust... evt); public class MyObject { public string foo; public int count; public DateTime when; public MyObject() { foo = "hello world"; count = 42; when = DateTime.Now; } public override string ToString() { return string.Format("{0}\t{1}\t{2... ...
I am glad to inform the release of SmartCodeGenerator CTP 2.0 in both .Net1.1 and .Net2.0. As a result Templates can be generated both in VS2003 and VS2005. Please download from Codeplex:http://www.codeple... Notes:1. I am not using the Asp.Net Profile object in the core api to generate user interface, instead introduced a Custom class "TheProperties". Please refer to tutorials at www.smartcodegenerator.com for more details.There are some other changes made to ...
I was challenged recently with a question about generics with constraints. The claim was that it's only a compile flaw that allows your to declare an interface for a generic type with a constraint. Namely that the syntax public interface ISomething <T> where T: SomeClass would pass compilation but would not be useful (runtime) because you can't declare a variable ISomething myVar = new ISomething<SomeClass>(); or something to that extent. I went home feeling a bit uneasy about the discussion, ...
Date:Thursday, October 19, 2006 Topic:Refactoring with Generics Speaker:Kathleen Dollard, Northern Colorado .NET SIG Generics open up new opportunities to increase the robustness of your code, improve its performance, and significantly reduce the total amount of code you write. After a brief introduction to generic syntax, this talk dives into using generics to improve the quality of your code. You'll see how easy it is to shift your current collections to generic collections and learn about new ...
Its wierd, and I cant make head or tail of it. I was writing a webpart today, and I was maintaining a generic stack collection which I wanted to place in the session. What is wierd is that if i were to add object of type Stack <T> to the session, SharePoint says an unrecoverable error has occurred. The moment I changed the stack from a generic to a plain old .NET 1.1 non-generic Stack the error was gone. tags: SharePoint, WebParts, Generics, Session Cross-posted from tariqayad.com ...
Microsoft's Sandcastle was released as a CTP just recently. This is a tool for .NET 2.0 that allows you to create documentation from the XML comments that are found in a DLL. This is a tool that is meant to compete with NDOC which hasn't really had the greatest support for generics found in .NET 2.0. I haven't tried Sandcastle myself yet, but here is the link: http://www.microsoft.com/do... ...
Literally I do mean it..I'm eating my words! In my previous article I had put on some code to show the performance of Generics. Well it was as childish code as my generics knowledge i do agree. Thanks to Alois for such a detailed explanation. I researched and what? I found I was wrong...but that gave me real pleasure :-). I changed Alois code for string and tested it..and I must say amazing result. I'll put the whole code here(Alois...please correct me if I am wrong). using System; using System.Collections.Generic; ...
I posted a new page on my site, demonstrating how to use generics to extract enumerated flag values from an integer value in a generic way. I wrote this utility class, because I wanted a way to execute actions on the server using a URL query parameter sent from the client. Until now, when I wanted to execute an action, I was using a URL like: http://www.galasoft-lb.ch/m... Then I was mapping the value 3 to an enum value, and would execute the corresponding action before rendering ...
We all use DataReader to fill or populate our custom collection. Usually the code is pretty repetetive since we are filling different collections with different objects. In my opinion there should be one Fill<T> method which should fill all the collections provided with the correct parameters. First take a look at the common way of filling a collection: private static void FillCategoryListWithoutHelp... { List<Category> categoryList = new List<Category>(); string connectionString ...
Lately, my ASP.NET 2.0 app has been taking so long to build I have been going crazy. I came across this post at ScottGu's blog that had a possible cause for suddenly long build times. I have about 20 projects, but it's hardly a massive site. I had some problems that I just kind of put up with a while ago where an older version of Iesi.Collections.dll would appear in my /bin folder of my web root and I have been running the NHibernate alpha 9that uses version 1.0.0.2 of Iesi.Collections). Anyways, ...
Just to add to my previous blog abt Generics Overloading the folowing scenarion is also very helpful..... Suppose I have a class public class TestClass<T, U> { public void Foo<I>(T val1, I val2, U val3) { } public void Foo<I>(U val1, T val2, I val3) { } } And I'm calling this as static void Main(string[] args) { TestClass<int, string> ob = new TestClass<int, string>(); ob.Foo<double>(1, 122223, "er"); } it will compile pefectly as the permutations of U,T,and I ...