Deborah Kurata's thoughts about turning visions into reality with .Net.
Welcome to the blogsphere, Deborah! Can't wait to read what you got. I also love how you picked up my tag line for the signoff for your posts....
"Enjoy!" ;-)
Oh and one more thing... HAVE FUN!!
-B
One of my favorite features in VB 9 (Visual Studio 2008) is XML Literals. This example demonstrates how
Looping through a list to append strings is often more challenging than it should be. For example… In
The other problem here is that the aggregation of the strings is cool, but the string + string approach involves creation of a lot of strings for the GC to clear. You should be usng a StringBuilder. This is very inefficient on a large number of strings:
string final = "";
for (var x = 0; x < 10; ++x)
{
final += x.ToString();
}
This simple code (like your aggregation) will create about 30 strings that aren't used. Being mindful of the immutability of strings is important.
Like what I see so far, subscribed!
I prefer using string.join to accomplish these kinds of things -- the only downside is that it needs a string[]. Luckily, LINQ includes ToArray() to turn the IEnumerable<string> that comes out of Select into a string[].
string email = string.join("; ",custList.Select(c => c.EmailAddress).ToArray());
It's easier to visualy inspect and verify that the for loop exmple works than the lambda based one.
I'm glad to see you blogging. I am trying to subscribed to the Rss for post feed but my reader (Omea) epps giving me a 'cookie header' error. You may want to check on this.
Hey Shawn -
Thanks for stopping by my blog.
Yes, just because you can do something does not necessarily mean that you should. Have you seen the scuba diving cat? :-)
www.youtube.com/watch
As developers, we always have to evaluate techniques for "fitness of purpose". We have to decide whether a specific technique is appropriate for what our application needs to achieve.
This technique may be fine for an application that will have 1 to 5 email addresses. But it would not work well for a spamming app sending to hundreds of email addresses.
Thanks for your thoughts!
Hi Jonathan -
Thanks for your suggestion.
It appears that Join is smarter and does not create the excess strings that the Aggregate method creates.
Cool! Thanks again!
This entry describes the MasterMind class from this example in further detail: Public Class MasterMind
This entry describes the Peg class from this example in further detail: Public Class MasterMind End Class
Thank you!
I'm working through this months examples as we speak... sort of..
One of the common ways to access data in a .NET application is to use the drag and drop TableAdapter
This post provides an implementation of a method that retrieves a DataTable from a SQL Server database
Deborah, could you do a post on creating/maintaining SPs, including when one should lean toward a SP versus a dotnet query?
TIA,
jack
I LOVE that movie!!! Braaaazzzziiiiillllll. I suppose you wouldn't like Woody Allen's "Sleeper" either then. Another great comedy about the future. ;-)
Hi Jack -
I just posted this:
msmvps.com/.../dal-using-stored-procedures.aspx
Hope it provides the information you are looking for.
Hey Beth -
Someone told me that I just didn't *get* the British humor in this movie. But I am a big Dr. Who, Torchwood, Graham Norton, and Top Gear fan, and used to watch Monty Python. So that can't be it. :-)
This movie was written by some of the same people that wrote Monty Python and some of the same actors were in this movie.
In a prior post here , I created an XML file using VB 9 (Visual Basic 2008/.NET Framework 3.5). This
Deborah, that was great! Exactly what I needed.
You have a talent for putting descriptions into UNDERSTANDABLE language.
Much appreciated.
This post provides an implementation of a method that accesses a DataReader using a stored procedure
This post provides an implementation of a method that accesses a DataReader from a SQL Server database
Thanks Deborah!
I took the Co/ContraVariance example from Lucian's blog. Glad I could explain it in "human"-ish terms ;-)
blogs.msdn.com/.../co-and-contra-variance-how-do-i-convert-a-list-of-apple-into-a-list-of-fruit.aspx
Enjoy!
Most business applications have business objects such as customer, order, or invoice. Often, the data
Great !
How using this in a multi-language context?
I wrote about this same solution over a year ago - with a slight difference in that my solution is using a generic extension method to get the description attribute value.
Daily tech links for .net and related technologies - July 9-13, 2009 Web Development Using Custom T4
Hi Moggoly -
Thank you for your post. My extension method just extended [Enum]. It would be interesting to see how you did it with a generic extension method. Would you be willing to post some of your code?
Thanks again!
You forgot to close the reader.
CommandBehavior.CloseConnection means that underlying connection will be closed during the closing of the reader.
So using statement or simple call for reader.Close(); should do the trick
using (SqlDataReader reader = Dac.ExecuteDataReader("CustomerRetrieveAll", null))
while (reader.Read())
// Do something with the data
If not doing so you connection pool will reach it's limir very quickly, especially in a web application.
Nisus -
Yes, you are correct! I had a Close statement in my sample code but neglected to copy it to my post. But a using statement is event better.
I'll edit my example per your suggestion.
Thanks!
My prior post demonstrated how to bind to a list of month names. Once the user picks the desired month
Don't have one to post but wanted to say this is a great topic. Also want to say thanks for all your recent articles, especially for posting C# and VB code each time, very nice.
Hi Deborah,
Thanks, this was just what I needed!
However, instead of using a dictionary as you did, I used LINQ with an anonymous type.
Dim enums = [Enum].GetValues(_type)
result = _
( _
From e As Object In enums _
Select e = New With _
{ _
.ID = CInt(e) _
, .Name = CType(e, [Enum]).GetDescription _
} _
Order By _
e.Name _
).ToList
I had already created an extension method "ToWords" for the string type (which I didn't show here for simplicity), but I needed to have "Week 1/2", "Week 3/4" which of course I couldn't have as enum members.
So your code helped me out enormously!
Thanks,
Yann
Very cool, Yann.
I was directed here by you to look at this, does this work on .net framework 2.0 with visual studo 2005?
Hi Miller -
No. As it states at the top of the post, this is for Visual Studio 2008, .NET Framework 3.5.
(Guess I should have asked that before linking you to this page.)
There are often times that you need to write out text files containing data managed by your application
Hi Paul -
If you have to support multiple languages in your UI, you should not have any strings that you plan to display to the user hard-coded in the code.
So you won't be able to leverage this technique.
Typical MS tightly coupled approach. You're going to be writing a TON of data access for each object. Use NHibernate and you can have state AND persistence solved out of the box.
And if the ActiveRecord pattern is really what you want, there's persistence frameworks for that too.
Even in the .Net world, we are so far beyond ever having to write all this code manually. This is solving a problem that has already been solved.
Hi mendicant -
Thanks for coming by the blog. The purpose of putting this into a base class is so you never have to write it again.
And I have additional methods (not shown here) that automatically populate my business objects and update the database based on the business object properties. So I don't write any data access for any objects.
I only need the stored procedures, and I have written a code generator to do that for me. :-)
... and with Spring.Net, AOP, etc.
I used to try to this in VB. The overhead was just not worth the effort. At most, implement the property change listeners and use a service oriented architecture.
Your base class provides:
public abstract Boolean SaveItem();
Which means every item needs to override it. Now I've got to write code in every single class that implements it. Do your automatic methods exist on each item?
As for the stored procs, I'm not ready to even begin down that road again.
Thanks for taking my first comment so nicely, I wasn't very rational when I wrote it.
Great post. Can you provide specifics for comment " I have found some things that I much prefer doing in C#".
I'm a vb.net programmer (history in Access rather than VB) and besides more code/examples on the net being C# I struggle to find where/why C# is preferable. I had to write about 30 lines of C# the other day and found it a giant pain in the butt. All those curly braces and semi colons just seem totally ridiculous.
Deborah, You will still need "Data access" code even with Stored Procs. Do you mean that is common code?
I am with mendicant on SPs. I'll try not to get started on them too. :)
+1 to mendicant for acknowledging the harsh tone in the comment
+1 to Deborah for trying so hard to come up with this even people say the problem has been solved. So what, next time when you actually need to use NHibernate you are that much wiser than those who didn't try
-1 to me for not providing any value in this comment ....
Get the following errors from the code:
Error 1 The best overloaded method match for 'System.Web.UI.WebControls.TreeNodeCollection.Add(System.Web.UI.WebControls.TreeNode)' has some invalid arguments C:\web_projects\AM\MasterPage.master.cs 29 29 C:\web_projects\AM\
Error 2 Argument '1': cannot convert from 'string' to 'System.Web.UI.WebControls.TreeNode' C:\web_projects\AM\MasterPage.master.cs 29 52 C:\web_projects\AM\
Error 3 'System.Xml.Linq.Extensions.Nodes<T>(System.Collections.Generic.IEnumerable<T>)' is a 'method', which is not valid in the given context C:\web_projects\AM\MasterPage.master.cs 32 43 C:\web_projects\AM\
Hi Tim -
Thank you for coming by the blog.
These are a few right off the top of my head...
VB: Dim tb As TextBox = DirectCast(sender, TextBox)
C#: TextBox tb = (TextBox)sender;
VB: Dim sampleString As String
C#: string sampleString;
VB: AddHandler SampleUserControl1.ValueChanged, _
AddressOf SampleUserControl1_ValueChanged
C#: sampleUserControl1.ValueChanged +=
sampleUserControl1_ValueChanged;
VB:
Private _FirstName As String
Public Property FirstName() As String
Get
Return _FirstName
End Get
Set(ByVal value As String)
_FirstName = value
End Set
End Property
C#: public string LastName { get; set; }
[VB will be getting automatically implemented properties in VS 2010]
Hi Star79 -
Thank you for stopping by the blog. It looks like from your errors you are using a WebForms TreeView?
This code is for a WinForms TreeView as per the first line of the post.
You can use the same general concept for accessing the XML, but you would need to change the code to add nodes to the WebForms TreeView to the correct ASP.NET syntax.
In the simple sample code I have posted on my Web site, I do indeed have the SaveItem code manually written into each business object. (But in my sample code, there is only one business object so not a big deal.)
In my *real* applications, I have some code in my base class (not shown here) that automatically populates the stored procedure parameters. So the SaveItem method in each business object only needs to define the appropriate stored procedure and reset the entity state.
I have also worked with some very basic Linq to SQL with POCO. I plan to do a post on that soon.
Hi Thanks for pointing that out...Iam totally new to LINQ can you pls guide me on this..
appreciate your blog.
Thanks for the reply. Personally I see only the last 2 items as a benefit although as you said VS 2010 will remove the last benefit.
No doubt often the VB version is more verbose but I find more often than not the verboseness (if there is such a word) is easier to read and more natural.
As you said it comes down to choice and where your roots in development started. As I started with dBase I'm use to languages of the 4GL nature as opposed to C# being 3GL.
I really appreciate reading a blog that has VB & C# code. Keep up the good work.
Awesome. Whatever we can do to keep you rolling please do...You're kicking this stuff out at an unbelievable rate and it's all uber cool. Thanks!
Hi Deborah
Your real application version base class sounds interesting could you show an example.
Julian
Interesting Finds: July 24, 2009
Very informative and simple program that was a big help for something I've needed to learn. Thank you.
I worked for Prime Computer and helped design these computers that Tom Baker and assistant made an ad for in the late early 80's:
www.facebook.com/.../share.php
One word for Dr. Who... BRILLIANT!
Now that is my kind of vacation. I love Dr. Who!
業務でツールが出力したデータを分析して結果をExcelに出力するアプリを作っています。 本当、このアプリ開発にはいろいろあり悩まされてきたけど、ようやく終わりが見えてきたところで困ったのがExcelの終了処理
I question both the character and caliber of any developer who DOESN'T love Dr Who.
I'd LOVE to go there. That would be so awesome...
Hi Dave -
Oh ... those are so funny! Thanks for sharing!
Debora, your articles hit that sweet spot for those looking at "how to do stuff" with .NET. Straight to the point, easy to understand. Having examples in both VB and C# is also a rarity and greatly appreciated.
The C# code example in this article could be improved, though. If you're using GetType() and typeof, there's no need to then do a .Name to do the comparison. You can use the == operator to do a direct comparison between the two type objects.
With that said, I personally would probably use the is or as operator in C# for the check unless I only wanted TextBox objects. Those operators will match a TextBox or anything that derives from TextBox. The comparison with GetType and typeof will only match a TextBox object.
Lastly, if the code is intended to work with any type of "textbox" (ex. TextBox, MaskedTextBox) in the processing, keying off of the TextBoxBase class would allow that.
Thank you for taking the time to put this beautiful article. Im newbie in C# and this is just what I was looking for, exactly something like this.
After one day of trying without any success, I found I made two slight omissions, that the article not mention about these.
1. You need to use the control user designer to hook up the SampleUserControl_TextChanged.
2. The event handling method that consume the event must be.
private void sampleUserControl1_ValueChanged(object sender, NamespaceName.ValueChangedEventArgs e)
Cheers from Bolivia.
Hi James -
Thank you for your kind comments about the blog and for your tips. I will remove the .Name property as per your suggestion. Thanks again!
And the coalesce operator can be concatenated, as follows:
currentUser = _currentUser ??
GetWebUserFromSession() ??
GetWebUserFromTrackingCookie() ??
CreateNewWebUser();
Some developers consider this to confusing and difficult to maintain, but I think that over time, people will get used to it and it will become common.
As always, very simple and helpful examples that remind us that there is a better way to do things.
Keep it up.
This was a great tip. I tried to do this in a web form and it was a really ugly solution with tons of if statements (Controls were in a master page) This is much cleaner and nicer
I love your blog!!
Deborah,
your solution is lacking of a sort (orderby) metod. Check my ListKeyValuePairEx which you can change for Dictionaries as well:
To use:
<combobox>.BindEnumKeyValue(typeof(<enum>));
or
<combobox>.BindEnumDescriptionValue(typeof(<enum>));
public static class ComboBoxEx
public static void BindEnumKeyValue(this ComboBox obj, Type enumType)
obj.DataSource = enumType.EnumToList();
obj.DisplayMember = "Key";
obj.ValueMember = "Value";
public static void BindEnumDescriptionValue(this ComboBox obj, Type enumType)
obj.DataSource = enumType.EnumDescriptionToList();
public static class EnumEx
public static IList EnumToList(this Type enumType)
List<KeyValuePair<string, int>> list = new List<KeyValuePair<string, int>>();
foreach (Enum key in Enum.GetValues(enumType))
int value = (int)Enum.Parse(enumType, key.ToString());
list.AddUnique(new KeyValuePair<string, int>(key.ToString(), value));
return list.SortByKey();
public static IList EnumDescriptionToList(this Type enumType)
list.AddUnique(new KeyValuePair<string, int>(key.GetEnumDescription(), value));
public static string GetEnumDescription(this Enum value)
return GetEnumAttribute(value, typeof(DescriptionAttribute));
public static string GetEnumCategory(this Enum value)
return GetEnumAttribute(value, typeof(CategoryAttribute));
public static string GetEnumAttribute(this Enum value, Type attribute)
Type type = value.GetType();
if (value == null)
throw new ArgumentException("Value must be of type Enum", "Value");
System.Reflection.MemberInfo[] memberInfo = type.GetMember(value.ToString());
if (memberInfo != null && memberInfo.Length > 0)
object[] attrs = memberInfo[0].GetCustomAttributes(attribute, false);
if (attrs != null && attrs.Length > 0)
return ((DescriptionAttribute)attrs[0]).Description;
return value.ToString();
public static class ListKeyValuePairEx
public static List<KeyValuePair<K, V>> AddUnique<K, V>(this List<KeyValuePair<K, V>> list, KeyValuePair<K, V> kv)
if (!list.Contains(kv))
list.Add(kv);
return list;
public static List<KeyValuePair<K, V>> SortByKey<K, V>(this List<KeyValuePair<K, V>> list)
List<KeyValuePair<K, V>> sorted = new List<KeyValuePair<K, V>>();
foreach (KeyValuePair<K, V> item in list.OrderBy(key => key.Key))
sorted.Add(new KeyValuePair<K, V>(item.Key, item.Value));
return sorted;
public static List<KeyValuePair<K, V>> SortByValue<K, V>(this List<KeyValuePair<K, V>> list)
foreach (KeyValuePair<K, V> item in list.OrderBy(key => key.Value))
Hi,
Thank you very much for your nice code samples. And a Thank You to you husband who ask about LINQ and DataTable.
I am trying to LINQ my DataTable and return it to my DataGridView. The problem with DataView is that I cannot use distinct and select my fields.
I like to LINQ my DataTable with distinct and select only one (1) field from my DataTable and return it to my DataGridview...any suggestion?
Thank you,
Rune
Rune Brattas @ videotron dot ca
I've been looking for this code for days. You are my new hero! You saved me hours of effort in making this work.
I love it. I one great post.
Thanks
This all sounds pretty close to an old incarnation of CSLA.NET (We're talking .NET 1.1 days)---I'm wondering if Rocky has moved beyond defining a base class, and then having to hand-code state management into property setters of derived classes?
We considered this approach in the project that we are working on but have moved onto a more flexible (but considerably more advanced) means of managing all that plumbing code that you've baked into your base class, viz., using AOP.
At the end of the day, developers should be concentrating on solving business problems, not writing plumbing and although your base class does take alot of that away, it does mean that you're not stuck deriving from it. Also, you still need to hand-code that state management and notification stuff into your derived classes---why not just use an AOP framework to bolt that on at runtime?
It does amaze me that after so many years of object orientation and applying MVC goodness, we still haven't got to a place where this is all automagically dealt with by the underlying framework.
I guess POCO based approach using NHIbernate is way better than implementing any business logic in your BO's even if it is only SaveItem...
If you have a big project with hundreds of entities you will quickly noticed how unmaintainable it gets
It's a great post!! However, I just don't understand the reason of having 2 different languages where the underlying technology (IL) of both is not VERY different. I would agree if it was pre-.NET era where Object-Oriented C++ was more powerful than Object-Based VB. The expectations from both of those languages were quite different. C++ was used for more complex tasks using powerful data structures (linklists, trees, graphs etc.) and on the other hand VB was opted for rapid application development. But, where are we now where almost all of the features are available in both C# and VB.NET with some exceptions. Is it very difficult to implement those exceptions where they are absent?? Is it really impossible to implement XML Literals in C# and Statement Lambda in VB.NET?? if not then I honestly see only one language in future (C# very likely :))
Hi Irfan -
Thank you for visiting my blog.
To reply to your question, VB10 (VS 2010) will have statement lambdas.
So there is no distinguishing between the user entering '0' and the user entering 'A'??
Ken Getz also has a nice article that includes generating a collection of random numbers using LINQ:
<msdn.microsoft.com/.../cc700332.aspx>
sorry... the trailing ">" on the url breaks it... I thought <> would prevent url wrapping.
msdn.microsoft.com/.../cc700332.aspx
Thank you for visiting my blog!
Ken's code randomly orders a set of numbers, where my code randomly selects a subset of numbers. Both techniques are useful, depending on your requirements.
NOTE: If you have difficulty using the link in Jack's post, try this: msdn.microsoft.com/.../cc700332.aspx
Hi CB -
You are right in the num will be 0 in both cases. However, if the user enters '0' the If statement will be true. If the user enters 'A', the If statement will be false.
Hope this helps.
Debora,
Only thing is for ASP.Net replace the HasChildren with HasControls(), in the above Process.... function, there you have it for ASP.Net application environment as well.
I have one such recursive function where in I had to set the checkboxes within a HtmlTable control on a aspx page. So to this function I pass the list of checkbox values and the HtmlTable control. I then check if the current control is a HtmlInputCheckbox and if so, set the checkbox state (checked) if the value of it is one among the list that I have passed as input. Here is the code
/// <summary> /// Recursive function to set the Checkbox controls within the container control. /// </summary> /// <param name="listArray"></param> /// <param name="ctrlContainer"></param> /// <param name="listIndex"></param> public static void ProcessCheckboxControls(string[] listArray, Control ctrlContainer, int listIndex) { HtmlInputCheckBox checkBox = null; foreach (Control ctrl in ctrlContainer.Controls) { if (ctrl.GetType() == typeof(HtmlInputCheckBox)) { //First initialize the checkbox ((HtmlInputCheckBox)ctrl).Checked = false;
//Now set the checked status from the list (if applicable) SetCheckboxFromList(listArray, (HtmlInputCheckBox)ctrl); listIndex++; return; }
if (ctrl.HasControls()) ProcessCheckboxControls(listArray, ctrl, listIndex); }
/// <summary> /// Set checkbox from List. /// </summary> /// <param name="listArray"></param> /// <param name="checkBox"></param> public static void SetCheckboxFromList(string[] listArray, HtmlInputCheckBox checkBox) { int i = 0; for (i = 0; i < listArray.Length; i++) { //Check to see if the checkbox value matches with any of the listArray items if (checkBox.Value == listArray) { checkBox.Checked = true; break; } } }
Hi LotusShiv -
Thank you for your comment and associated code for use with ASP.NET. Great example!
NOTE: I removed some of the excess blank space between the lines for space reasons. I did not reformat any wrapped lines, however.
I actually don't agree with "Do NOT use inferred typing for variables of intrinsic types (like in the above integer and string examples)".
I use this a lot:
dim title = "This is my title"
I see no point in having to use:
dim title as string = "This is my title"
Am I missing some obscure reasoning here?
PS - I think you need to change "Questions? Contact Susan at Susan-at-msmvps.com" that's at the bottom of the page, lol.
Good for beginners, Thanks
You should seed you random numbers; otherwise you'll end up with the same random numbers for every execution of the code. The common used technique is to seed it with the number of milliseconds from the epoch:
Random rand = new Random(DateTime.Now.Ticks);
How are parameters passed in? Can you give me an example?
I prefer implementing TryParse using what in DDD is called a Value Object. I have an example here: blog.torresdal.net/.../RefactoringTryParseIntoAValueObject.aspx
Hi Yann,
Thank you for visiting my blog and for bringing up this topic.
The main reason not to use inferred typing in this case is readability. Read more about this here:
srtsolutions.com/.../on-var-and-c.aspx
And regarding your PS, Susan's name at the bottom is correct. She is the one that manages this blogging site for all of the mvps.
Hi Chris -
Thank you for visiting my blog and for your suggestion.
However, if you don't specify a seed, the Random method will define one for you so that you don't have the problem you defined. This is a quote from the documentation:
"Initializes a new instance of the Random class, using a time-dependent default seed value."
Here is the link:
msdn.microsoft.com/.../h343ddh9.aspx
Thank you for bringing up this topic!
Hi JP -
I added an example demonstrating how to pass parameters to the ExecuteDataTable method.
Thanks for your suggestion!
Hi Jon -
Thanks for the link!
Very cool. Multiple params go in as a comma separated list:
Dim dt As DataTable = Dac.ExecuteDataTable("CustomerRetrieveById", _
new SqlParameter("@CustomerID", custId), new SqlParameter("@UserID", userId), )
Thanks :)
On a side note, how are multiple connections handled? Lets say a build a data grid, and on item databound I make another database call.
The Using statement ensures that the connection is closed after every call to this function. SQL Server's connection pooling prevents performance issues.
I've written an extension method with the help of the generic code here: theengineroom.provoke.co.nz/.../generic-tryparse-type-conversion.aspx
The idea is that you can implement TryParse on any value type by extending the string type, returning a nullable value type, so you can test if the parse was successful. I hope this code shows up in the comments!
public static class Parsing{ public static Nullable<T> Parse<T>(this string tryVal) where T : struct { Nullable<T> result = null; try { int iNumberOfMethods = typeof(T).GetMethods().Length; MethodInfo mTryParse = null; for (int iCounter = 0; iCounter <= iNumberOfMethods; iCounter++) { MethodInfo mCurrent = (MethodInfo)typeof(T).GetMethods().GetValue(iCounter); if (mCurrent.Name.Equals("TryParse")) { mTryParse = mCurrent; break; } } if (mTryParse != null) { T passIn = default(T); object[] args = { tryVal, passIn }; bool success = (bool)mTryParse.Invoke(null, args); if (success) result = new Nullable<T>((T)args[1]); else result = new Nullable<T>(); } } catch { }
return result; }}
And this is how you would use it:
[Test]public void Testing_Parse_Helper(){ string ok = "123"; string notOk = "hello"; int? try1 = ok.Parse<int>(); double? try2 = notOk.Parse<double>(); Assert.IsNotNull(try1); Assert.AreEqual(try1, 123); Assert.IsNull(try2);}
please ,how can you give a customer a unique number which consist at least 10 chars?
Hi Notken -
Thank you for visiting my blog and for your post. The code originally lost all of the formatting, so I had to reformat it. Let me know if I introduced any errors.
Awesome. You are soooo very much appreciated. Thanks again.
This post provides an implementation of a method that saves data to a SQL Server database using a stored
Hi Moses -
I would not recommend using this random number technique to define unique keys for your customers.
Rather, you should consider either using an autonumber column on your database table or use GUIDS to produce unique Ids.
Here is a link:
msdn.microsoft.com/.../system.guid.aspx
Thank you for submitting this cool story - Trackback from DotNetShoutout
I'm working with data collected over eons (e.g. 20-30 yrs... mainframe, to DOS DB, to Win DB...). Names have been converted to UpperCase and I would like to make them "normal" - however, I don't want to end up like many bulk mailing printouts - which fail to put proper casing to names like O' Neil, or Mc Murrey, or de la Roma --- and the end up looking like: O'neil, or Mcmurrey, or De la roma
I suspect this would take a huge name database to match against or to just have a huge typefest where names are corrected via "data entry".
Know any automated way?
TryParse in java?
Nice! Thanks for posting this.
I think you've just saved me hours of future hair-pulling-out... :)
Don't overlook the OfType method as an alternative to Cast. The Cast method will throw if the conversion is not allowed, whereas OfType will simply filter non-matching objects out of the sequence. So the OfType method is a bit like the 'as' keyword.
Hi John -
One option for handling more complex names is to use the techniques described in this post and build in a set of rules to correct the most common occurrences, such as O'Neil and McMurrey. You could then have the code print to a log for any cases it questioned (like having multiple words in the last name). Then people would only need to look at these exceptions and not every single last name in the database.
Thanks for your suggestion, Daniel.
Is My.Settings a WinForms thing? Im assuming its the same as <add key="key" value="value"/> in the web.config?
Similar to my prior post here that details how to use anonymous types to display word counts, this post
Fantastic Post. I'm assuming you've tested with office 2007.
In the Microsoft Data Access Block, there is a parameter cache. It can automatically fill parameter values for you. So your method can be
public static int ExecuteNonQuery(string storedProcedureName,
params object[] arrParam)
It hides the access details behind your method. Users only need to feed values in correct order.
Or simply:
foreach (var g in Regex.Matches(sampleText.ToLower(),@"\w+")
.Cast<Match>()
.GroupBy(m => m.Value))
Debug.WriteLine(g.Key + ": " + g.Count());
Sorry, no VB.NET.
Hi Robert -
Yes, I tested with Office 2007.
Thanks for visiting my blog!
JQuery and web development Limit Number of Characters in a TextArea using jQuery Find out which Key was
thanks for your efforts
Public Class DotNetUtility Public Shared Function ConvertingTextCase(ByVal str As String, ByVal stringcase As TextCase) As String If str Is Nothing Then Return String.Empty End If
Dim ci As System.Globalization.TextInfo = Application.CurrentCulture.TextInfo
Select Case stringcase
Case TextCase.LowerCase str = ci.ToLower(str) Exit Select
Case TextCase.None str = str Exit Select
Case TextCase.TitleCase str = ci.ToTitleCase(str) Exit Select
Case TextCase.UpperCase str = ci.ToUpper(str) Exit Select
End Select Return str End Function
Public Shared Function IsRightToLeft(ByVal str As String) As Boolean If str Is Nothing Then Exit Function End If
Dim ci As System.Globalization.TextInfo = Application.CurrentCulture.TextInfo Dim rtl As Boolean
If ci.IsRightToLeft = True Then rtl = True Else rtl = False End If
Return rtl End Function
Public Enum TextCase None = 0 LowerCase = 1 TitleCase = 2 UpperCase = 3
End Enum
End Class
Hi Omar -
Thank you for sharing your code.
NOTE: I removed some of the excess line spacing that was inserted by the editor here.
The "useful scope" of the anonymous type is pretty much what you can see on screen, right? It seems that there is little you can do with the query result unless you know exactly what the
'select new {...}' statement looked like.
Or is that somehow discoverable?
These are very useful posts, thanks for putting them uip.
I’ve been keeping an eye on Deborah’s MSMVPS blog and am amazed. Deborah is posting some awesome code
Interesting Finds: August 20, 2009
I don't get it. Why strip the file objects down to just the four properties? If you were going to pass the anonymous type out to other routines then I could see having security reasons to do something like that but anonymous types need to stay within the routine. Wouldn't you rather just use the file types you already pulled with .GetFiles?
Yes, the useful scope of an anonymous type is primarily restricted to the routine in which it was defined.
If it had a more significant scope, a named type (basically a class) should be used instead.
Hi Bob -
Thanks for visiting my blog.
There are lots of properties on the file objects. If you had lots of code where I have "Do whatever ..." and that code only used the four properties, it might be helpful to only have the four properties showing up in Intellisense.
In *real* projects where I have used this, we have also defined properties that modified the built-in properties such as defining the .FileName property without an extension or removing the "." from the extension.
Completely forgotten about the coalesce operator. Thanks for the reminder. Great blog by the way.
Interesting Finds: August 21, 2009
Thanks Deborah for your recurring contribution. You are priceless to Visual Basic community.
Hello Deobrah,
Don't you agree that importing Schema would simplify the LINQ query to avoid mistyping errors?
Thanks again for your lovely post
One small typo, this feature was available with Visual Studio 2008 which shipped with .NET 3.5 which includes C# 3.0 and VB 9.0.
For Visual Studio 2010 and .NET 4.0 there is going to be C# 4.0 and VB 10.0.
Hi Cliff -
You are correct.
I have been working on VS 2010 articles and typed "2010" here when it is "2008". I correct the text.
This post provides an implementation of a method that saves data to a SQL Server database using a SQL
The phrase in the sample string comes from the movie "Flowers for Algernon".
One of my favorite features in .Net 3.5 is the ability to extend a class using extension methods. Earlier
There are many different types of text files that you may need to process in your applications. Some
No mention of JSON?
There may be times that you need to read delimited comma files into your application. For example, you
Hi Eric -
Thanks for the suggestion. See the update at the end of my blog. I added the OrderBy and the associated VB code.
Hi Joacim -
You are correct!
This seems like more work than using TextFieldParser directly. You're giving up a lot of error checking, and adding extra overhead loading the odbc + ado.net drivers. Why not just use msdn.microsoft.com/.../microsoft.visualbasic.fileio.textfieldparser.aspx ?
There may be times that you need to read fixed length files into your application. For example, you obtain
Hi Neil -
Thank you for stopping by my blog.
I was focused on describing enough about text files to then write the next two posts, which involve reading text files using OleDb.
You would not use OleDb to read in JSON files. But for completeness, I'm glad you mentioned it here.
Hi Reed -
Thank you for visiting my blog and thanks for the link!
There are benefits of reading the data into a DataTable, such as the ability to then bind to controls such as a DataGridView.
Using the technique you suggested is another choice if the application just needs to process the file line by line.
There may be times that you need to read comma separated value (CSV) files into your application. For
In my prior post, I covered how to read a comma delimited file into an in-memory DataTable. You could
In my prior post, I covered how to read a fixed length file into an in-memory DataTable. You could then
I just added posts for using TextFieldParser to access a comma delimited value (CSV) file and a fixed length file. Thanks for the suggestion!
Thanks Deborah for this post.
Is there a chance to see a post related to interacting with Excel from VB? I'm not talking about VSTO but using automation.
Regards
Despite the fact that there is a free version of SQL Server called SQL Server Express , there are still
Hi Walleed -
I have done several Excel examples:
msmvps.com/.../default.aspx
Interesting Finds: August 28, 2009
Thanks Deborah for these very helpful tips and code sections.
Also, this is one of the few expert blogs where VB programmers are not ignored!
Focusing on making text proper case, if the incoming text is all uppercase then .ToLower method is needed.
using the following
<Runtime.CompilerServices.Extension()> _ Public Function ProperCase(ByVal value As String) As String Dim TI As System.Globalization.TextInfo = New System.Globalization.CultureInfo("en-US", False).TextInfo Return TI.ToTitleCase(value.ToLower) End Function
with this data
Dim Mary = (From name In New String() _ {"MARY JONE'S", "mary jone's", "Mary jone'S"} _ Select name.ProperCase).ToList Mary.ForEach(AddressOf Console.WriteLine)
Outputs
MARY JONE'sMary Jone'sMary Jone'sMARY JONE'sMary Jone'sMary Jone's
Now add .ToLower
We get proper casing correct
Mary Jone'sMary Jone'sMary Jone'sMary Jone'sMary Jone'sMary Jone's
Thanks a lot..you saved me..:)
I'm trying the C# solution and I keep getting an error that the Microsoft Jet Engine cannot open the file ''. That only thing different that I'm doing is instead of a OleDbConnection, I have a string in it's place. Does the directory name for the data source need to have a \ at the end?
Can you post this question along with a code snippet here:
social.msdn.microsoft.com/.../threads
I monitor this C# forum and here it will be easier to look at your code and have a "conversation".
Thanks Deborah for this lovely article with simple non-complex overview that we all adore in your distinguishable articles.
Why didn't you add a simple blank methods and properties to demonstrate how real world objects can be casted to VB Code?
Also we hope that the following article would talk a bit about pillars of OOP like encapsulation and inheritance in your way that charms all VB fans -what is your secret? :-)
Have a lovely day
Reducing the number of lines of code and improving code documentation are focused on in our code reviews.
Hi Waleed -
Thank you for visiting my blog and for the kind words.
These are all upcoming topics. Did not want to make any one topic too long. :-)
Today’s world of software design and development is all about managing complexity. Computer-savvy users
Interesting Finds: September 1, 2009
In object-oriented (OO) terms, inheritance defines an “is a” relationship between two or more classes
When talking about OO, the term “interface” has nothing to do with your user interface. An interface
The four basic elements of an object-oriented system are abstraction , encapsulation , inheritance ,
Hey, one question regarding this code:
What about UTF-8 text file and the special characters?
I have tested it and this code doesn't read multibyte character - so isteed one 2byte character you will get two 1 byte characters. Oh and Byte Order Mask at the begining is also visible :)
Interesting Finds: September 2, 2009
Hi Radarek -
Thanks for stopping by the blog. Yes, this technology is a little limited. There is an OEM mode (instead of the ANSI mode), but I did not try it. If you give it a try, report back and let us know if it worked for you.
Awesome! Please don't stop now. ;-)
All the best,
Mark Wisecarver
Thanks for the interesting article. I had never tried using Application Events because my app doesn't start from a form, which is required. Finally (duh) I realized that a tiny dummy form that hands off to my Sub Main would do the trick. Your article gave me the push.
what timers ?? what class ? there are three timers class !!!
Hi es -
It does not really matter to the code which timer you use. Rather, it will depend on your application.
I used the System.Windows.Forms.Timer because my example was executed from a WinForm. You may want to pick one of the others, depending on how you use this class.
I have tried this thing before. I wanted to catch StackOverflowException. But this thing is not working for StackOverflowException. For all other exceptions, this mechanism is perfect.
Thank you for the above code. Works very well, except for one small error in the c# code. You set an integer rowHeaderWidth which will be 0 if row headers are NOT visible, but then you do not use it when setting the rectangle bounds, so the rectangle is offset.
I think rowHeaderswidth in the VB example should be rowHeaderwidth, but have not tested it.
Thank you for catching that! I corrected the code in the post.
Thanks again -
You still impress me with your magical way in your posts. However, I blame using lambda expression since it makes me lose focus on the feature you try to explain. I've noticed that you fell in love with the anonymous function as you used it intensively in your last posts.
Thanks again and stay brilliant as you are :-)
This is a very important feature to perform dummy repetition of the same data over and over and a strong replacement of the traditional loop since it is an inline function.
Thanks Deborah. This post is beyond amazing
I remember studying the nullable types when I was preparing for the .NET Framework 2.0 exam as it was in the very beginning of the Microsoft self paced kit.
The good thing is you used "ternary operator" which would do the job correctly.Developers may mix it up with "the immediate IF (IIF)" which would sometimes causes a logical bug that is hard to be found since many are not aware that it evaluates both true and false parts if they were functions.
Thanks Deborah. You touched a vivid topic.
Мегареспектос! Прочитал с интересом от начала и до конца.
What a great class, thank you very much!!
If you don't like to use lambda expression you can just as well use a regular LINQ query and let the compiler create the lambda for you.
' Initialize an array with letters
' This one does A, B, ... J
Dim letters() As String = (From i In Enumerable.Range(0, 10) _
Select (Chr(Asc("A") + i).ToString())).ToArray()
A spin off of the python range method?
Are there some pieces of code that you find yourself writing over and over and over again? Do you ever
Before going through the details of how to use object binding, it is important to understand exactly
As stated here , you use object binding in a WinForms application by following these steps: 1. Build
Interesting Finds: September 9, 2009
Love the code; it works great with my code to pull XML data from a website into a dataset. One question though. If I want to leave the Excel file open so I can do further work on it, how do I do so with out leaving garbage out there?
Thanks Deborah for submitting this article. But what about creating custom code snippets using snippet editor. I usually code the snippet in the XML editor, however, I hope you can highlight the usage of the code snippet editor as I believe it would be much easier to work with.
Trying this on a fixed width file, but it doesn't work unless I have an end of line character. The file I am working with is just one long stream of characters. Thanks anyway!
Very straight forward and it helped a lot.– thanks for posting it!
.NET Comparing Two Images in C# Application running in localhost and debugging mode - HttpContext.Current
.NETComparingTwoImagesinC#Applicationrunninginlocalhostanddebuggingmode-HttpCo...
I just wanted to thank you for this post too. I was just starting to do Linq to Word for a project and this posting came riding to the rescue.
Cheers;
Dave
Can you post a soltion file with all code in the related Data Access examples.
Hi Jim -
There are examples here:
www.insteptech.com/.../samplecode.htm
After my post on Using Code Snippets , several people have asked about the Code Snippet Editor. As stated
Very well-written article and very understandable. Also helped me with a problem I've had for some time, thanks!
Hello, this is a good approach for wrapping up the database access, but I just wanted to note few things here: this solution is no flexible for usage with different SQL providers and it still returns ADO.NET's standard objects like DataTables etc., meaning the developer who uses this code would still need to map the data fields into her C# objects manually, which is tedious and time-consuming. Just as a suggestion, you could read my post: <b><a href="seesharpgears.blogspot.com/.../csharpgears-framework-database-access.html" title="Database Wrapper Classes" >Database Wrapper Classes</a></b> which utilizes a framework for designing a wrapping the whole access to the database to four operations Select(), Update(), Delete() and Insert() and is capable of directly mapping the SQL columns to C# attributes, meaning that a SQL table Product corresponds to a C# class Product and the Select() query would return List<Product> directly, which makes it easier for OOP manipulation. Please read my approach and tell me what do you think. All comments are appreciated.
There are often times in most applications where you need to work with lists. You may have lists of customer
Though this is not necessarily a common requirement, this post demonstrates the following techniques
yourList.OrderBy(x=>Guid.NewGuid()).Take(numberOfItems);
hi deborah,
just want to ask if you have a sample n-tier architecture, 5-tiers which includes entities, DAL, proxy, UI and data source-
im trying to make a system using this 5 tiers for the winforms application...
hope you can help me with this. a sample program could help. with add, delete, update and edit using stored procs.
many thanks. God bless.
This works great as long as you are calling a form that resides inside the assembly. I need to be able to display a form that resides in another assembly. I have tried many samples on the internet and find that they do not work and either give me a null reference exception as soon as I try frm.Show or when I try to invoke the Show method as (obj.GetMethod("Show").Invoke(inst, Nothing)) it gives an ambiguous name exception. How can I perform this?
I use Excel 2008 on Mac. It does not enable the use of macros. I am not familiar with Applescript or C#.
My question is pretty similar and I wonder if it can be solved without the use of macros. I have several columns of data (heading is constant, length of columns could differ), which has to be transformed to fit to a statistical software so that each cell in the column produces as many cells beneath in the same column as the value of the cell (not negative integer). The value of the newly generated cells are the sequential number of the original cell in the column (except for the heading).
Eg:
XY
0
1
3
4
8
This column should produce altogether 16 cells in the same column (or new spreadsheet) 1 with the value "3", 3 with the value "4", 4 with the value "5" and 8 with the value "6" (the sequential number could be read out form an other parallel column as well).
I would very much appreciate if you could help solving ths frustrating problem.
M.
Hi Gamena -
The sample application I have is here:
Hi Marton -
My blog primarily focuses on .NET development. You may want to try posting your question to an Excel forum.
Good luck!
Whether it be SQL Server, Access, Oracle, or mySql, most applications write to one kind of database.
Hello Deborah,
Welcome to the metrics world. You have just demonstrated that the functionality, what is useful to the user, is not the programming language but what is hiding behind the language (i.e. the IDE and the OS) and how the language is used by the programmer.
I bet that, had you measured the functionality with COSMIC (www.cosmicon.com) you would have found the same number for VB6 as for .NET. This is because COSMIC measures the functionality and not the lines of code.
This being said I like your code, I'll try it.
Best regards,
Bernard Londeix
Telmaco Ltd (www.telmaco.com)
Please explain:
// Process the directory and all subdirectories
in the C# program,
it seems to me that only the subdirectories are processed.
If *.cs programs are in the top directory, they will not be added.
I can't believe that MS would have made it so trivial to code for multiple database types.
In Java, we will have to use an elaborate DAO pattern using one of Sun's blueprint, like this one:
java.sun.com/.../DataAccessObject.html
Or use DAO facility by one of the leading frameworks, Spring's DAO comes to mind.
Or use an ORM like Hibernate.
Anyway, is this provider method widely used in MS. I mean is it widely used if you are not using ORM (like nHibernate) or other open source frameworks like Spring.NET?
very nice post.
thats my always problem with different dbms
thanks
;)
What do we do with exceptions? Are the exceptions raised provider-specific?
Won't the use of SqlParameter... ParamArray arrParam() As SqlParameter... still bind this approach to Sql Server provider?
Hi HoyaBaptiste -
Oops! I did not correctly handle the parameters in this code. I will edit the post to correct it.
Hi Conrad -
This is from the msdn documentation:
"The DbException class is the base class for all exceptions thrown on behalf of a data source. You can use it in your exception handling code to handle exceptions thrown by different providers without having to reference a specific exception class."
msdn.microsoft.com/.../9hy8csk1.aspx
In my agency all .NET WinForm solutions have global unhandled exception handlers using this technique. Besides logging information to an XML log file developers have the option to send exceptions to a specially setup mailbox. The mailbox has rules setup to send known applications exceptions to sub folders which are monitored. The advantage here is that many times a developer will see a message; fix the issue before a user calls in the problem which in turn equates back to the customer as good customer service on our end. All our unhandled exception handling is housed in a separate DLL (includes a custom dialog which morphs between user and technician interface) which makes it easy for a developer to plug in this functionality Susan is talking about. Sometime in the near future I will be releasing the source code including demonstration projects used to test this code which has made several jumps in Frameworks with no changes other than improvements. Location will be under code.msdn.microsoft.com/kevininstructor
Also, there are some tools built into Visual Studio 2008 that will give you this (and much more information):
blogs.msdn.com/.../new-for-visual-studio-2008-code-metrics.aspx
Of course, this will only work for .NET projects.
Hey Rich!
Good to hear from you. Thanks for pointing to this link. There are some really nice tools there.
One note on the tool you mentioned .... I believe that it is only available in Visual Studio Team Editions.
Great way to manage snippets. There are more at www.snippetgood.com
looking forward
Thanks for a great little post. Well written and very clear :-)
Please tell me what is this "missing" field ??
Here is a 2 liner for it
wc.exe *.cs
wc.exe *.vb
This is on many platforms unix, linux, win32...
WC(1) User Commands WC(1)
NAME
wc - print the number of newlines, words, and bytes in files
SYNOPSIS
wc [OPTION]... [FILE]...
DESCRIPTION
Print newline, word, and byte counts for each FILE, and a total line if
more than one FILE is specified. With no FILE, or when FILE is -, read
standard input.
-c, --bytes
print the byte counts
-m, --chars
print the character counts
-l, --lines
print the newline counts
-L, --max-line-length
print the length of the longest line
-w, --words
print the word counts
--help display this help and exit
--version
output version information and exit
Hi Manu -
Thank you for stopping by the blog. Missing.Value is needed in C# because C# 3.0 does not support optional parameters.
Here is a link to the msdn documentation on Missing.Value:
msdn.microsoft.com/.../system.reflection.missing.value.aspx
I created code similar to this in 2005 when the data factory came out. I created a class that I can drop into any project and used shared functions that I call. I account for returned datatables, return an object for ExecuteScalar functions, and I also have an execute nonquerySQL that returns nothing. The class has a parameter object with typed parameters, and so far has been tested successfully with SQL Server, Oracle, text files, Excel, and ODBC against a mainframe. It will even account for the oracle refCursor returns as well for returning cursors from oracle.
In addition, I created a slick little application that goes against any SQL Server database on the network, lists all the stored procedures, and generates the calling code for me, complete with all return types, and typed parameters. Cut my programming time down by 80% and eliminated quite a bit of debugging since the code has been tested and is quite effective. I think the best thing .NET 2.0 put in was the data factory.
John
riley_wright@hotmail.com
This looks very simple. Is this an aspect of LINQ or just part of VB.NET itself now?
ALSO, how would one add an attribute to the Customer element such that it read like this:
<Customer id="12345"> in the resulting XML
try to use the code as it but i get an undeline error on "Customers" name "Customers" is not declared
Hi Jerry -
Thank you for coming by the blog. XML Literals are a feature of VB.NET only.
To add an attribute, the code would look something like this:
Dim customerXml As XElement = _
<customers>
<%= From c In custList _
Select <customer id=<%= c.CustomerId %>>
<LastName><%= c.LastName %></LastName>
<FirstName><%= c.FirstName %></FirstName>
</customer> %>
</customers>
Hi Noel -
Are you referring to this line?
Dim dt As Data.DataTable = Customers.RetrieveAsDataTable
As I mentioned in the description following the code, you can use any DataTable. In my example, the DataTable came from my Customers class. You will have to change the right side of this equation to reference your table from whereever it is.
I was in your class lamda expression. really liked it. May I get the slides?
melinda_x@yahoo.com
Thank you
- Melinda
My presentation at our local Code Camp was fun. I covered a lot of material and had a GREAT audience
In this prior post , I detailed how to build lists of things using a generic List<T>. Once you
This post covers the syntax for lambda expressions. It uses the customer list defined in this prior post
Interesting Finds: October 12, 2009
exceptionFunction looks like it's some function that handles Exceptions :p
The same several questions often come up in the forums regarding the basics of building a user control
Good one!
You forgot to mention Extender controls, a control that extends another by providing new properties and behavior. The classic example is the ToolTip control which, as soon as you've put on on a form, will extend all other controls with a ToolTip property.
Maybe you should read up on it a little. This film was extremely important at the time, portraying serious social issues with black humour. Dismissing a film because it is "a little odd" is a little closed minded when it comes to film review.
let me first thank you for your work, esp. your "Doing objects..." books. Really good intro for OOP in VB(.net)!
Unfortunatly I've got to put some salt in the generic approach to data access:
1) MS-DBProvider approach doesn't support Oracle-return parameters, that do return a cursor, which is THE way for Oracle-SPROCs to return resultsets. The DBType enumeration doesn't contain a DBType.Cursor or something similar. So, one has to implement something more special inside the DAL...
2) The Oracle Parameter-Format (at least in Ora 9.2) isn't neccessarily the name with : before! Doing ad hoc queries like "SELECT * FROM table WHERE field = :Value" this works, but not with SPROCs! (The ad hoc-query approch counters the generic approch, since it implies NOT to write provider specific SQL-code!)
So that sadly reduces the DBFactory to a semi-generic issue, esp. when using a SPROC approach.
IMHO MS should finish it's work in those areas instead of walking hundreds of new paths, only to realize those are dead ends...
Best wishes and take care
Volker from Germany
Hi Alex -
Thank you for dropping by my blog.
Yes, I assumed it was a very important movie at the time considering its Oscar nomination and interesting social statements. But it was not for me.
And as you may guess, I am a software developer by trade, not a movie reviewer. Just wanted to share my opinion and thoughts.
Thanks for sharing yours as well!
Could you give us an example for the method :
Retrieve a populated business object using a DataContext
I wish bind a business object on data and I wish my methods return some List<mybusinnessobject>
To Deborah Kurata
Thanks a lot... I really appreciate your effort..
this blog was really helpful..
WB.SaveAs(filename, Microsoft.Office.Interop.Excel.XlFileFormat.xlWorkbookNormal, null, null, false, false, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlShared, false, false, null, null, null);
this code also works.. :: )
I liked the simplicity of your articles. I had a task to read a tab delimited text file into dataset and was using this code. But my limitation is that I can't create any file on the server i.e. schema.ini. Is there a way to use oledb to readt tab delimited file without using schema.ini file?
Hi Sri -
Did you see this blog post?
msmvps.com/.../reading-comma-delimited-files-textfieldparser.aspx
Great post. This is probably a matter of personal taste but if I were coding this I would define the Customer ID as 8 and the Last Name as 20, I prefer to deal with trailing spaces I've always felt leading spaces are more problematic to deal with when processing data.
Lambda expressions can be assigned to a delegate variable. The lambda expression is then executed when
Interesting Finds: October 17, 2009
I create this function to return a List<mybusinnessobject>
public static List<T> ExecuteAndBindToObject<T>(Param pParam) { // Create the return list of T List<T> lList = new List<T>(); // Get the type T and the properties Type tType = typeof(T); PropertyInfo[] piProperties = tType.GetProperties(); // Execute the stored procedure DataTable dtTable = ExecuteDataTable(pParam); // If we found some records if(dtTable != null && dtTable.Rows.Count > 1) { // For each record for(int iRow = 0; iRow < dtTable.Rows.Count; iRow++) { // Create an object of type T T oCurrentObject = (T)Activator.CreateInstance(tType);
// For each property of T foreach(PropertyInfo piProperty in piProperties) { // Get the binding info attribute object[] oAttributes = piProperty.GetCustomAttributes(typeof(BindingInfo), true); if(oAttributes.Length != 0) { BindingInfo biInfo = (BindingInfo)oAttributes[0]; // Get the value in the datasource object oValue = dtTable.Rows[iRow][biInfo.SourceFieldName]; // Set the property value of the current object piProperty.SetValue(oCurrentObject, oValue.GetType() == typeof(DBNull) ? null : oValue, null); } } // Add the current object lList.Add(oCurrentObject); } } // Return the list return lList; }
[AttributeUsage(AttributeTargets.Property, AllowMultiple=false)] public class BindingInfo:System.Attribute { private string sSourceFieldName; public BindingInfo(string sSourceFieldName) { this.sSourceFieldName = sSourceFieldName; } public string SourceFieldName { get { return sSourceFieldName; } } }
NOTE: I reformatted the code - DJK
Thanks Deborah, I read the suggested post and found that it would be easier to use Schema.ini file. So now I got access to temporarly create schema.ini file and export the tab delimited file to dataset.
This was working great with test data but when I tried with production data. It failed because of datatype issue. Some of the rows have numeric data and some has text in one of the column. So I modified the Schama.ini file to add "Col3=C Text Width 100" but unfortunately I am still getting the same datatype error. I am not sure if Schema.ini is bein read or not? Appreciate your suggestions.
Good! But the code could not get me to convert my Heading to either lower or upper. Any suggestions?
The last several posts have provided examples of using anonymous types. This post backs up a little and
Thank You so much !! i was lookin 4 it since more than 1 month.. i just found the solution :)
Hi Melinda -
Thank you for visiting my blog. Glad you liked the talk.
The information from the slides starts here:
msmvps.com/.../lambda-expressions-an-introduction.aspx
If you have Visual Studio 2008 or later and have the Professional Edition or better (NOT the Express
Hi Deborah!
This post help me a lot.
Visual Studio 2008 (Professional Edition and above) provides a really nice set of tools for development
Deborah, if you only wanted to populate the California portion of the XML tree how would you do this? I am assuming that you have to take out the first For/Next stmt with <State>.
stateNode = ?
For Each region As XElement In state...<Region>
regionNode = stateNode.Nodes.Add(region.@name)
For Each area As XElement In region...<Area>
regionNode.Nodes.Add(area.@name)
Next
EM
Hi there,
Isn't it bad practice to use the autogenerated unit tests. I heard somewhere that it is.
I heard that its best to write the unit test from scratch.
VB.NET APPLICATION DEMO WITH SOURCE HAVING BO, DAL, AND UI.
Interesting Finds: October 26, 2009
Hi Anon -
Visual Studio is not really generating your unit test ... only a template for your unit test. You still have to write all of the code to perform the test.
So in my opinion, there is no downside. Think of this generated code as your unit test snippet: you still need to fill in all of the important details.
Hope this helps clarify.
Hi Shivaji -
I have an example here:
Hi EM -
I assume this thread is answering your question:
social.msdn.microsoft.com/.../6a9507c8-7c37-4850-abd2-c43252a53c33
I have VS 2008 Professional, but I don't see Code Coverage in LocalTestRun.testrunconfig (also I don't have Controller And Agent and Web Test options). Do I need test certain projects or install something additional?
Hi Patryk -
My mistake. The Professional Edition has the tools for building, executing, and debugging unit tests. However, the code coverage tools are only in the Team System Edition.
I corrected the post.
Thank you *very* much for pointing this out so I could correct this error.
Wow! Unless the computer's date/time was tweaked forward, this article was created just a couple of days ago - usually the dates shown are months if not years in the past.
Anyway, my question is: Can random values be sent to these tests, such as in the case of testing last names, could it be sent a bunch of different strings, such as:
Twain
12345
Clemens
`1!@#
O'Malley
McClintock
l'Raisson
a;fasdkl;jsdfa;jklsdfa
etc.?
I don't know if I will pass this way again, so if you really want me to see a reply, please email it to bcshanno@jcpenney.com
Hi B. Clay -
I don't know where you are reading an odd date, but I see 2009-10-25 everywhere (last Sunday). The 15:25:40 is the time (hour, minutes, seconds) Where are you seeing a date in years past?
Regarding your question, yes. The next article in this series will cover how to test properties in further detail.
Thanks for coming by the blog.
Thank you for taking your time to investigate this.
Terrific Mate..
I found a couple of code posting on a nullable tryparse method. The code the I came up with is here johndauphine.blogspot.com/.../nullable-tryparse-function-in-c.html.
BTW, here is how I call a the function
NullableParser<double>.TryParse(dataToLoad["foobar"].ToString(), out _fooBar );
Where datatoload is a DataRow
Way back when we were using Visual Studio 2005, there was a Clipboard Ring tab in the Toolbox. I loved
Is there something -- the [TestMethod()] attribute, perhaps -- that restricts PrivateObject's use?
Or can it be used anywhere?
Thank you for visiting the blog.
The PrivateObject is in the following namespace:
Microsoft.VisualStudio.TestTools.UnitTesting
And the description of the class is "Allows test code to call methods and properties on the code under test that would be inaccessible because they are not public. "
I don't think it was meant to be used anywhere else.
And maybe that is a good thing? If a class has private members, it seems that they should *not* be accessed by external code? (Testing being the only exception)?
The only thing I miss here is a reason why I should call private members directly. If a private property or method cannot be tested by calling other public members or I have a need to test it independantly then the private member should be refactored out to a dedicated class. Otherwise, the Single Responsibility Principle is likely to be violated.
Thanks for your post. It was very useful. Just would like to share that, I could also create parameter from DbProviderFactory.CreateParameter() and it created param specific to my provider. This way, I could avoid below switch case...
switch (df.GetType().Name)
case "SqlClientFactory":
...........
Thanks a bunch Deborah, this will help a lot of developers.
This is a nice example of automating Excel via .NET, which I would like to see more of, but this method will be painfully slow for large amounts of data. Anyone else have "bulk" methods for sending the data in one shot?
I know this can be done with an array, but you must first get from the datatable to the array. Using a StreamWriter to go to .csv is also fast, but this file must then be opened in Excel. It would be nice to have a fast direct method.
Hi Shiv,
the switch/case statement in the DAL-snippet is mainly due to the different naming conventions for DBParameters. The DBFactory.CreateParameter() method won't supply the Parametername with the '@', '?' or (sometimes, not always) ':'.
For that reason a DAL needs to make a difference, here done by switch/case. Another attempt could be to read the DB's Schema, where'll find 'ParameterMarkerFormat'...
Best wishes
Volker
This post was mentioned on Twitter by brada: Great post on RIA Services with VB.. http://bit.ly/1eplar
I am CEO of a software development company in Australia and I have to say that this is without doubt the single most informative, thorough and extensive .NET blog on the entire Internet. It is so good I feel almost guilty about getting this for free. Deborah, you are amazing.
Thank you for the kind words.
They really encourage me to keep going!
Urs, the access to private methods/properties/fields is required if one does not want to change the public signature of the tested class but still wants to mock/stub the internal dependencies on other objects.
Example: you want to test SomeClass that loads some data from the database using DataClass. You don't want it to actually touch the database so you mock the DataClass to return a certain value say "3". Since SomeClass does not expose DataClass in it's public signature, the only way to cut the dependency on DataClass is to manipulate the internal variable holding the reference to DataClass and replace it with mock/stub object created outside of it.
Thanks so much for this post!!
It really helped me with a quick prototype I had to whip up.
Kathy
This post details first how to build a list containing the data to display in a WinForms TreeView control
Very helpful tip, Deborah. It's a pity the same thing doesn't work for auto-complete fields on the browser.
(I was once completing a UserName and Password dialog and didn't hit Tab properly between the fields, so my password got typed in in plain text alongside the username. The next time I was logging on - in a demo - up came the suggestions drop-down complete with the UserName+Password combination, for all to read!)
There may be times when you want RIA Services to ignore a property in your business object. This may
So I have read in dozens of places that you can easily share a source code file between your business
I mentioned in this prior post that RIA Services did not know how to handle properties that have an Enum
I just stopped by to check out your site.
I think it's crazy to attempt using something as complex as RIA Services without reading the RIA Services Overview document in its entirety. That document is at great pains, even in the very first quick walkthrough, to point out that a file must be correctly named.
It IS possible to link a Silverlight project to a non web project although it's a bit painful to do this at the moment because the GUI doesn't help you - you have to manually edit the csproj file. You can find more information on this in Dave Hill's blog entry here: blogs.msdn.com/.../prism-and-net-ria-services.aspx
I have to say that this is without doubt the single most informative, thorough and extensive .NET blog on the entire Internet. It is so good I feel almost guilty about getting this for free.
me richtexbox dont working gidme one example
for vb6 U.U please.
This is what i was looking for :D,
Thankyou!!
If you need help with VB 6, you may want to post your question here:
http://www.vbforums.com/
I was tired of seeing all the examples with Entity Framework , this example is clean , clear and provide an excellent way to understand the basic concepts,
I am trying to use your example with the ViewModel , will update my progress later. Thanks
Hi Sat -
Thanks! Glad this was helpful.
Keep us posted on how you are doing!
Nice post on gradients--we have been using those in our Foothill WPF class but I was mystified how to achieve certain directions until I read your article.
For the second image in this post--showing the Address form--what type of Panel did you use to lay that out? Canvas or Grid? The Nathan book says never to use Canvas, so I'm assuming you did so here just for demo purpose.
...and, in order for PNG transparency to work, the PNG must be 24 bits/pixel. Like you, I found out the hard way.
Thanks for your Help.
Thanks for the tip, BEM!
I used Canvas in all of these examples. I am not familiar with the Nathan book. Is there a reason one should never use a Canvas?
In one of the applications I am working on, I display a set of "bubbles" representing entities that are sized according to one of the entity properties. I lay these out across the control. I can't image trying to do this with a Grid.
Thanks for your comments!
- Assume that Microsoft tools do not support anything other than the most plain image format (open it in paint and also preview it via file explorer just to check). MS largely lags behind in supporting image, audio and video formats.
- Use a decent image editing program (photoshop, gimp, etc.) so that your images match the image format standard
- Use more widely supported sub-format like 4:2:2 in Jpeg instead of 4:1:1
- Consider optimizing the image using optipng or jpegtrans
- Assume that Silverlight/MS apps will very poorly resize or dither your image.
This post was mentioned on Twitter by BethMassi: RT @msftwise Deborah's Developer MindScape-XAML: Gradients: http://bit.ly/2sG6AJ : BTW Beta2 makes this easy w/ eyedrop+gradient colorpicker
I mis-spoke; Nathan says Canvas is "too primitive a panel for creating flexible user interfaces" but also to "keep in mind for maximum performance when you really do need precise control over the placement of elements."
If you have a fixed size window where the elements need to be placed at an exact size/position, or relative position, canvas is fine.
If you want the UI elements to expand/contract as you resize the window, then I think you have to use one of the other panels like Grid, DockPanel, StackPanel, etc.
Thank you for submitting this cool story - Trackback from progg.ru
Exactly what I am looking for!
Merci beaucoup pour ce post
I must admit I'm getting disillusioned with the unit test features in VS2008. It's way more complex than JUnit, and seems buggy. Try debugging from a test -- often you can't step into the code called. It may be OK on a brand-new project, but when converting a mass of VB6 and adding tests, it just fails.
Well, try running debug on some of these generated tests. You can't step into the code under test!
the oracle database gives back a RefCursor.. how to populate dataset with RefCursor
my text file adds and subtracts the text in my application but it doesnt show the text inside.
could you please let me know why is that so?
I have a *very large* solution that originally was converted from VB6. In general, I am able to debug from the tests with no problem.
However, if I have been debugging from within the tests for a significant amount of time (like all afternoon), I then find that I have difficulty. Often just existing Visual Studio and reopening the solution solves the issues and allows me to continue.
I have a *very large* solution and I am able to debug from the tests with no problem.
Hi vishal -
Thank you for stopping by my blog. Please post your question here:
social.msdn.microsoft.com/.../categories
The forums provide a much easier place for asking questions that require reviewing code and submitting follow up questions.
I monitor the forums often, and there are many experts there that can help you with any issues you are having.
As WinForms and WebForms developers, we are used to building user interfaces (UIs) that look like this
Once again...Awesome!
Thanks a bunch ;-)
http://twitter.com/msftwise
Nice one
I have this situation:
<Root>
<Date Value="20091118">
<MM Title="MyTitle" Note="MyTitle1" />
</Date>
<Date Value="20091119">
<MM Title="Title2"Note="Title2" />
<MM Title="Title3" Note="Titl3" />
<Date Value="2009113">
<MM Title="Tit4" Note="Tit4" />
</Root>
When in child nodes i have only one child everything goes well when i read it, but if there are more then one note my query read only the first child.
This is my query:
Dim query = From st In inXLM...<Date> _
Select New With { _
.Data = st.Attribute("Value").Value, _
.MM = st.<MM>.@Title, _
.Note = st.<MM>.@Note}
Can you help me plese.
Thanks in advance,
Ilber
Please keep in mind that persons 40 years and older will have difficulty with:
- Gradients
- Too many colors
- Similar colors on top of each other (light brown text on brown background).
- Too many rounded corners
- Too many lines
- Fixed font size
- Color scheme is low contrast
-
I used the excel API and it was extremely slow. Then I found this article
theengineroom.provoke.co.nz/.../how-to-bulk-insert-data-into-an-excel-worksheet-using-c-and-office-12.aspx
Highlights:
1) Get your datatable
2) delcare object array
3) fill object array with data
4) get an excel range object of exact size of column with and number of rows
5) excelRng.Value2 = object array
Your data is 'pasted' into your worksheet and you don't have to use the clipboard object
HTH
Thanks for the tip, rngGuy!
Thanks for your suggestions, Greg.
As someone on the "better" side of 40, I find that gradients are softer on the eyes. But I agree on the other points. The easy font size adjustment is one of my favorite things in Win7.
Thanks again.
Thanks for the tips, Ted.
You have no example with getting line I will go with Charlieit123's solution! E for Effort!
This tip is very cool!
Thank you to share with us.
This is up to your usual standard - a potentially complex topic made simple and crystal clear. I have followed your guidance since VB5 days with your book "Doing Objects" and met you the last time at the San Diego .net users group. Thanks again I will be building upon this for my work.
Happy Thanks Giving to you and your family!
Hi Geoff -
Thank you for the kind words and Happy Thanksgiving to you and your family as well!
Daily tech links for .net and related technologies - November 18-20, 2009 Web Development SharePoint
Thank you again for posting such a wonderful blog. Now i have to point out your ability to write simple, precise and very clear explanation in terms of concepts that you explain.
Also almost all the times, the code that you post is tested and workable, and i had no problems with it.
Your blogs are more ever becoming a complete reference for us, where you not only explain the fundamental concepts, but also how to solve the real world problems that we face a lot of times, when we do coding.
Thanks again,
Sidd
We can also bind an image tag's Image Source proprety to and ImageSource tag in the codebehind. That works too :)
Here is a simple test I use when reviewing our developed applications/web sites.
- Take a screen shapshot of the application
- Open in Gimp/photoshop
- Convert to grayscale
- Find edges in the application
- Thicken the edges by 1 or 2 pixels
- Review that with the development team to show the noise in the GUI
Open other helpful GUI tip for those over 40 and more so for those 60 or older is to minimize or remove the animated icons/click hit bitmaps. This is especially distracting and counter productive for older users.
Every application has some type of codes: customer types, reason codes, states, and so on. Sometimes
When building line of business (LOB) applications, a common feature is create, review, update, and delete
Building a DataForm is quick and easy and is detailed in this prior post . Even customizing it is a breeze
I am just starting to work with Silverlight and I have found your website VERY helpful. Thanks for the efforts you are making.
As a developer of business apps., I frequently have the situation where data input through a form requires complex validation, with inter-relationships among the fields on the form. Normally, I would put this logic in the middle tier of my application and validate the resulting object before saving it to the database. If there is a problem with the validation, I would send the appropriate information to the view, perhaps by raising an exception.
Do you have any thoughts about how this would be handled in a Silverlight app.? I guess that I could share the validation logic between my middle tier and the Silverlight app., but is there another / better way?
let me add another curiosity (and example of sleazy app-development) with images, but this time WPF:
Struggling around with XAML and WPF one'll find out that using Blend and VS side by side will be highly recommended. OK that far. Now, let you (or even worse your stylish designer) open your .net-project in Blend. First you arange some window-properties. Among others the Icon-Prop. Blend gives you the file-open dialog and let you choose (as you did that thousends of times with winforms before) an ico-file. And now you hit F5 to run the project, but the only thing you'll get is the well known "app encountered a problem; report this to MS or not". To me as a winforms developer the near to most feared and hated message. But no further explanation. Hmmm.
So let's try it in VS. There you'll get an error, to, but this time a FileFormatException, giving you the hint, that you should probably try png instead of ico and e`voila, it works!
1) Why is the ico-format supported by the file-open dialog, when it's usage creates an error? Bad, because a good app should let the user make mistakes...
2) Why not giving a qualified error message?
Both aspects make THIS implementation really is lousy and not appropriate to designers (you know, the guys wearing stylish glasses and love to use their fruity-comps and hate to use that boring business stuff instead ;-)).
Seems as if MS has to do much more homework to launch new technologies in a way that doesn' make it's critics laugh...
Greetings from rainy & stormy germany
Great post... but I have one question.
I'm experimenting a little bit with this RIA thing and came across the following situation:
The query to retrieve the combobox items is a paremeterized query, so I added a query parameter to my DomainDataSource, but, unfortunately the query parameter is not bindable, the only way to pass a value is harcoding it... The value for this parameter is given from the selected item in my dataform...
do you know how could I overcome this problem?
bye,
Sebastián.
Great Post Deborah! I have been fighting this for awhile. I have a custom combobox that I created that loads on demand but it has a few quirks. This is so much cleaner. I am looking forward to your follow up post once you solve the next piece of the puzzle.
Also another variable to throw at it once you have it working are some validation attributes. I have a required attribute on mine (one of the quirks) and the dataform can correctly identify that has changed and needs to save but the box does not get a red border or tooltip.
The Data Annotations showed up after I aligned them on one line, otherwise when I just pasted the Data Annotations, the Data Form was ignoring them.