Posts archived in .NET

This is the first in (hopefully) a series of quick things I’ve picked up whilst tackling the previously mentioned project

So, I have a table something like this:

CREATE TABLE [dbo].[Product](
 
[ProductID] [int] IDENTITY(1,1) NOT NULL,
 
[Name] [nvarchar](100) NOT NULL,
   [Price] [int] NOT NULL,
    [LastSaveTimestamp] [datetime] NOT NULL CONSTRAINT [DF_Product_SaveTimestampDEFAULT (getutcdate())
) ON [PRIMARY]

The key here is the default value on the column: LastSaveTimestamp.

If I then try to, say insert a new column into this table, for example using this code:

  DatabaseContext dc = new DatabaseContext();
  Product product = new Product();
  product.Name = “test product”;
  product.Price = 50;
  dc.Products.InsertOnSubmit(product);
  dc.SubmitChanges(System.Data.Linq.ConflictMode.FailOnFirstConflict);

Then I’d get an exception like:

System.Data.SqlTypes.SqlTypeException: SqlDateTime overflow. Must be between 1/1/1753 12:00:00 AM and 12/31/9999 11:59:59 PM..

The fix is actually really simple – In the table designer / DBML, you need to tell it that the column is auto-generated. Unfortunately this doesn’t seem to be automatically detected. It’s one of a few ‘just plain weird’ situations. 

AzamSharp has the fix details, with a handy-dandy screenshot over on his blog.

0 comments

Two WCF Stumbles

Here’s two things that caused me a bit of pain when working with WCF. Hopefully these pointers should help you get back to more productive things.

No Output when returning Serialized / Serialised objects.

I had been working on adding a significant number of methods and properties to a series of classes, and when I went to test the service I got literally no output.

Debug points indicated that all properties were there, and valid – but still WCF wasn’t returning anything. There was no exceptions  being returned to the client.

The best tool for debugging these sorts of solutions is to first of all enable Tracing and MessageLogging.  This is done via the WCF Service Configuration Editor, on the Diagnostics tab. 

Once you’ve done that, and re-run the projects – you can open up Service Trace Viewer.  For me under Visual Studio 2008, this was under Microsoft Windows SDK v6.0A > Tools.

image

This tool then lets you open up the trace log generated in your solution directory, and see all the activity that’s been happening.

debugging-wcf-services

From here, it was just a matter of scrolling down to the activity entry that had the yellow hilighting (indicating a warning), selecting it – then clicking on the Errors.

For me, the first time this happened to me, it was because I had stuffed up the DataMember Name values. It has also occurred for other reasons, such as a property not being populated, when I had specified that it was both required, and also that it could not emit a default value.

Can’t get mex to work

No, this isn’t a misguided racial slur. I was having issues setting up the mexHttpBinding on an ASP.NET AJAX WCF Service.

The solutions all point towards the same thing, that you need to set up an endpoint, and set the contract to IMetaDataExchange, then set the behaviour to have <serviceMetadata />. Except that it just wouldn’t let me add that property to my endpoint behaviour, and whenever I changed it to a service behaviour it would then not allow me  to set the other properties I needed for that.

Well, perhaps I’m particularly slow – but hopefully this pointer will help someone else.

1: Create a NEW service behaviour:

<serviceBehaviors>
  <behavior name="MyServiceBehavior">
    <serviceMetadata
      httpGetEnabled="true"/>
    <serviceDebug
     includeExceptionDetailInFaults="true"
     />
  </behavior></serviceBehaviors>

2: Add a new endpoint to your  existing service

<endpoint
   address="mex"
   binding="mexHttpBinding"
   bindingConfiguration=""
   contract="IMetadataExchange" />

3: Add the behaviorConfiguration you added in Step 1 to the Service (NOT the endpoint).

<service
  behaviorConfiguration="MyServiceBehavior"
  name="MyProject.MyService">

I kept trying to add it to the endpoint, and failing miserably. So much time spent back-and-forth on this!

 

That’s it for this instalment of “WCF is great, but I wish the config was a bit easier to understand”. Stay tuned for more exciting episodes!

Today I spent about half an hour banging my head against this problem:
Whenever I would try and return a business object, I’d simply get no response from my WCF Service. Litterally nothing.

The problem turned out to be that I had accidentally specified the DataMember Name of a property in a sub object twice.

So, I had my broken class set up like:


[DataContract(Name = "MyClass", Namespace = "Example")]
public partial class MyClass
{
[DataMember(Name = "property1")] public int Property1 { get; set; }
[DataMember(Name = "property1")] public string Property2{ get; set; }
}

An instance of this class was used as a property in another object, which was being returned from WCF.

.NET didn’t throw any sort of error unless I tried to return just “MyClass”.

Sure, it was my fault, but if you have a complex data structure, this could get awefully difficult to find without some sort of message from WCF.

Yes, this is part of that ultra nifty WCF JSON .NET 3.5 Flex project at work. :)

(A note to readers: This is all pure geek/coder content – Please skip this if nothing in the subject line makes sense)

I started on a new project at work for a client a bit over a week ago, by virtue of the requirements, we decided to investigate the use of new version of Microsoft’s  .NET Framework, Version 3.5, for all of the server-side services.

Microsoft have been quite strongly pushing the benefits of the new features of .NET 3.5. There’s been a few key features which are particularly interesting, and if all goes according to the marketing hype, should end up saving a huge amount of time and effort, whilst ensuring that we use well known and standardised interfaces.

What features?

Windows Communications Foundation (WCF) is particularly interesting because it promises to let you (mostly) remove the whole ‘how’ and ‘where’ portion of communications between tiers, and let you focus on the ‘what’ and ‘when’.

In essence, WCF should let me state that I want to create (say) a Web Service, that accepts information in format X, and outputs responses in some other format. It doesn’t have to be a Web Service either, it could be a Peer to Peer network speaking in straight binary streams.

For this project the client-functionality is all in Flex, so we need to ensure that the Flex guys can quickly decode all the responses and turn them into Action Script objects. Through a bit of experimenting and application prior experience – Web Services speaking JSON appeared to be the easiest and most light weight method of doing this.

Language Integrated Queries (LINQ) is another particularly interesting technology, particularly because it lets me focus on what I want to do with the data I have, rather than spending time transforming it from the Database tables, rows, and procedures, into .NET objects and methods.

There are a number of implementations of LINQ, which enables you to query a variety of sources – the one that I’m most likely to use is LINQ to SQL (talking to SQL Server). Regardless of what I’m accessing however, the syntax is identical – again, removing the need to modify my code if I need to query an XML file, Oracle or MySQL Database, or even native .NET objects.

You can probably see a common theme here – WCF lets me focus on communication with the outside world without needing to write that interface or conversion functionality, and LINQ lets me access and manipulate data, without needing to write that interface either.

So, it’s all plug and play?

Well, that depends entirely on what you’re doing with your data. If you’ve got something like a CRM application where the client is responsible for managing (most of) the data, then yes it can quite possibly be almost plug and play if you’re going with a “CRUD” interface.

If your data structure is more complex, then you need to determine exactly where the split is. In this specific project, I’m presenting an abstracted view of the data that the client needs, and doing all of the business logic to manage data management in the SQL and Web Services Layer.

So far, the whole WCF and LINQ combination looks good. I’m hoping to post some more detailed posts later on.

Further Reading

I highly recommend Scott Guthrie’s LINQ to SQL series of posts. Start with Part 1: Introduction to LINQ to SQL

These resources have also been of a great help in getting my head around the whole LINQ thing:

I’m currently working away on improving Smitter R3, and part of that is improving the way proxies are handled.

Currently, there’s four situations it supports quite fine:

- No Proxy
- Proxy, without Authentication
- Proxy, with BASIC Authentication (using specified username/password)
- Proxy, with NTLM Authentication using your current Windows Account (aka Windows Integrated Authentication).

The problem comes you’re in this fifth situation:
- Proxy, with NTLM Authentication using a specified username, password and domain.

Initially, I was using code like:

WebClient client = new WebClient(url);
client.Proxy = new WebProxy(proxyurl, true);
// if proxy-auth required:
client.Proxy.Credentials = new NetworkCredential(proxyusername, proxypassword, domain);
// ...etc

But, this fails with “407 Proxy Authentication Required”
The crazy part is that it actually is doing NTLM authentication, but it appears to be attached in the headers for twitter.com (!?).

So, I tried using WebRequest, and also HttpWebRequest and specifying proxy-keep-alive.
I also tried setting the .NET Default proxy to my specified proxy or just adding authentication credentials.
But, still nothing appears to be working.

Almost all the solutions online are using the DefaultCredentialCache – but that really doesn’t help (I tried), because I’m not logged in as the user that I want to authenticate as. Cretaing a new CredentialCache and adding the details to that – still no help.

All in all, very frustrated!

If you want to have a crack at solving it – download the SmitterR2 source and check out Smitter.Core.TwitterService.GetStatuses (in SmitterClasses\SmitterCore.cs).

There’s currently a line like:
using (WebClient client = BuildWebClient())
Ignore/remove it and create your own WebClient/WebRequest/etc to test on. That’s the first (network) function called when Smitter starts up, and is pretty quick to return a result one way or another.

Just make sure you’re using a proxy which requires NTLM / Kerberos Auth, and isn’t on the same domain as your current account. Any other situation seems to work A-OK.

If you can solve this, I’d be much in your debt.

4 comments

Smitter R2

Smitter, Release 2  is out now.

Changes

  • Better error handling (please report any bugs)
  • Proxy Support
    (NB: ClickOnce deployment may not work with Proxies requiring authentication!)
  • More efficient posting (no refresh necessary)

Requirements

  • Microsoft .NET Framework 2.0

Installation

ClickOnce Notes (updated!)

  • By Default, only works with Internet Explorer 6 and above, with the .NET Framework 2.0 installed
  • Does not work correctly if you have Internet Explorer configured to use a proxy requiring Authentication (eg: Corporate Firewalls)
  • Firefox users can run ClickOnce applications by installing the FFClickOnce addon, and then going to the normal installation page.

Upgrades

Source Code:

Application and Source Code Licence

 Creative Commons License
This work is licensed under a Creative Commons Attribution-Share Alike 2.5 Australia License

Please give your feedback in the comments, or add me on Twitter.

Features Confirmed for R3 (updated)

  • Minimise to Notification Icon (“System Tray”)
  • smitterPopupBalloon Notifications (optional)
    If Smitter is minimised or not visible, and your @Username is mentioned in a new tweet. 
     
    Note:  To deploy the above two features, I need an icon for Smitter.  On the screen-shot above, I am using an icon borrowed from Iconfactory’s Twitterific client icon in the   Litho Extras Volume 5 collection.   Due to licensing rules, I can’t distribute this icon, so it’ll remain for internal testing at the moment
  • Minor bug fixing (removal of the “Loading” messages if it errors, and fixing of the hammer-prevention so that it allows you to refresh)
  • More?
6 comments

Smitter R1 Released

Smitter R2 is out, go to the announcement.

image What is Smitter?
It’s a Small Twitter client, for Windows.  It’s also an excuse/reason for me to start writing software in C#, since I’m used to writing in VB.NET. (Boo, hiss, etc).

What’s with the “Battleship Grey”?
I’m not a designer, and fiddling with Windows Presentation Framework / etc wasn’t in my list of things I needed to learn right at the moment. 

What’s cool about it?
Nothing particularly, it’s pretty much all functional. But it’s the only windows twitter client I know of that shows you the source of messages.

How do I install it?
If you’re using Internet Explorer, just click here, and then click Install.
This is the recommended method as it will enable automatic updating when I release a new version. 

Alternatively, You can download the zip file. Just extract all the files to a new directory, and run Smitter.exe

I’m behind a proxy - it doesn’t work for me.
I’m adding proxy support shortly, but I wanted to get this out there as a first release.

This broke my system, who do I sue?
This application is provided on an ‘as-is’ basis, and at your own risk. Do not use this on “production” or important PCs if you’re particularly nervous.

Can I look at the Source Code?
Yep, that’s available too.  Download the source code here.

 Creative Commons License
This work is licensed under a Creative Commons Attribution-Share Alike 2.5 Australia License.

Can you add feature x?
Maybe – Add a comment here, or send an email. Alternatively, if you’re good with C# – you can have a crack at it yourself.

You do realise you did {giant, list, of, things} wrong, and the structure is crap?
The structure is crap because I went with the Twitteroo .NET API at first, but that doesn’t support certain functionality (like for example seeing if a message is private, what the source was, and being able to specify a proxy server). 

There are probably a whole number of violations of best coding practices here too. Again, this was primarily created so that I can learn the C# syntax and slightly different event modeling, etc. When I start off with a proper project spec, and don’t shift around on your a whole bunch, things work out a lot nicer.

Credits, Mentions, etc

FAMFAMFAM  – For the Silk Icons used within the GUI. (Creative Commons License)

Karsten Januszewski for this great pointer on how to generate classes from well-formed XML using XSD.   (nb: On Step 2, you need to use the ‘/classes’ switch.)

Paul Jenkins, for making me feel guilty for not actually knowing C# when he asks for advice/pointers about .NET stuff.

The Gold Coast has put on some great weather – nice and cool at night, warm and sunny during the day.
I’ve taken a bunch of photos during Tech.Ed, I’ll upload them soon. In the mean time – Nick Hodge has heaps of photos on his photo stream.

I’ve attended a bunch of interesting sessions – but there’s a heap of information on offer, so it’s easy to overload.

Next year I think MSFT needs to organise a few more social-networking things around the events. For example, get attendees to put ‘teched07au’ tags on photos on Flickr, and blog posts, etc. Use SMS-broadcasts (possibly through twitter) to inform people of session changes and things like that (link it back to their commnet subcription).
I’ll probably think of a bunch of other small improvements as time goes on.

Overall, it’s been good fun the last few days, and I have learnt things which are relevant to my job, and which will help a little further on too.

I’ve also successfully avoided the vendors who want to steal my information so they can sell me stuff.


Updates – LOLCode.NET, Movieworld, Bye-Bye Developer Guy

_MG_6791 Nick gave his LOLCode presentation, to much incredulity by some people who attended.

Yes, LOLCode is a proper Turing complete language. And LOLCode.NET compiles into MSIL as well.

_MG_6936 Movie world was… interesting. About 3,000 people were packed into busses and trundled up to movie world for dinner and some rides.   There was the BatWing, Superman and a few others – we didn’t have access to the full park, but there was a large area open.

_MG_6823

_MG_6827

_MG_6830 

_MG_6834

_MG_6842

_MG_6856 

_MG_6875

_MG_6901

_MG_6912 

_MG_6917 

_MG_6934 

 _MG_6961 Homeward Bound

 _MG_6969

 _MG_6971

_MG_6990Frank’s “Catch Up with Frank” talk was interrupted so he could be serenaded to a version of Don McLean’s “American Pie” called “Developer Guy”.

So, I spent a little while today going through the huge number of sessions on at Tech.Ed at the Gold Coast this year (160 or so) and picking out a rough guide for what I’m thinking of going to.

If anyone else is going and wants to meet up for a chat – drop me a line :)

Tuesday, August 7, 2007
09:10AM – 10:20AM
     DJ903 – Newcastle to Brisbane.

11:30AM (est) – Check In @ Crowne Plaza

6:30PM
    Welcome Party     

Wednesday, August 8, 2007
8:15AM
    Opening Keynote     

(9:00AM to 9:30AM is the tentative timeslot for Nick’s LOLCODE ‘ChalkTalk’. The Keynote runs until 9:45AM though.)

9:45AM
    CON204 – Introduction to Microsoft Windows CardSpace; OR     
    DEV231 A Lap around Microsoft Visual Studio 2008     

11:00AM Morning Tea     

11:30AM
    CON205 Programming Microsoft Windows Communication Foundation: A Developer’s Primer; OR
    DAT302 – Database Schema Versioning: How to Use Microsoft Visual Studio Team System for Database Professionals and Team Foundation Server to Version and Deploy Your Databases

12:45PM
    Lunch          

1:45PM
    ARC303 Principles and Patterns of Security; OR
    DEV301 “IronPython” and Dynamic Languages on .NET; OR
    WEB305 IIS7 for Developers     

3:00PM Afternoon Tea

3:30PM
    DEV305 Building Microsoft Windows Communication Foundation and Windows Workflow Foundation Applications with Microsoft Visual Studio 2008; OR
    WEB314 – Web 2.0 Programming

5:00PM
    ARC305 Architecting for Web Scale; OR
    DAT306 – Things You Need to Know for a Painless Upgrade to Microsoft SQL Server 2005     

6:15PM
    Ask the Experts     

Thursday, August 9, 2007
8:15AM
    DAT307 – Database Maintenance in Microsoft SQL Server 2005; OR     
    DEV308 A Lap around Microsoft Windows Presentation Foundation     

9:45AM
    DAT308 Microsoft SQL Server 2005 Security Best Practices; OR
    DEV317 – Microsoft Visual Basic: Tips and Tricks for the Microsoft Visual Studio 2008 IDE

11:00 AM Morning Tea

11:30AM
    DEV311 NET Framework 3.0 End-to-End: Putting the Pieces Together     

12:45PM
    Lunch     

1:45PM
    DEV312 Building a Complete Web Application Using ASP.NET Microsoft Visual Studio Codename 2008 (Part 1 of 2)     

3:00PMAfternoon Tea

3:30PM
    ARC311 – Windows Client .NET: Introducing the “Acropolis” Client Application Framework; OR     
    DEV347 Unit Testing and Test Driven Development     

5:00PM
    ARC310 Learning to live with the Static-typing Fascist and the Dynamic-typing Fanboy in your Enterprise… ; OR
    SEC304 – The fortified data center in your future: build it and they will come.     

6:15PM
    Final Party     

Friday, August 10, 2007
8:15AM
    DEV319 LINQ and XML for the Microsoft Visual Basic Developer; OR
    CON312 – Rules Engine Use and Extensibility in Microsoft Windows Workflow Foundation     

9:45AM
    DAT309 Implementing Scale-Out Solutions with Microsoft SQL Server 2005; OR:     
    DEV309 Best Practices for Team-Based Software Development     

11:00AM Morning Tea

11:30AM
    DEV315 Building a Complete Web Application Using ASP.NET “Orcas” and Microsoft Visual Studio Codename 2008 (Part 2 of 2); OR
    SEC313 – How Did They Find THAT?: Implementing the New Microsoft Fundamental Computer Investigation Guide for Windows     

12:45PM
    Lunch     

1:45PM
    SEC303 Securing Your Friends and Family; OR
    WEB301 – MS DLR for OSS developers     

3:10PM
    Closing Locknote     

Saturday, August 11, 2007

11:00AM
     Check out of Hotel

4:30PM-5:45PM
     DJ903 Brisbane to Newcastle

If you’re like me, and have registered for Tech.Ed 2007 at the Gold Coast, you will probably have recieved two emails in the past few days with your details to login to CommNet.

I’m not sure about anyone else – but the emails I got didn’t actually include the URL for CommNet. A quick Google search leads me to the TechEd Orlando CommNet site. All well and good, except it doesn’t accept my details.

The correct site for Aussies (and I assume Kiwi’s too) is actually https://aunz.msteched.com. Hopefully me posting this will let some other confused souls figure out how to access all the session planning tools. :)

Edit, Monday afternoon Just got an email with the appropriate CommNet URL in it.