Wednesday, July 08, 2009

Exporting GridView or ListView to Excel

A handy and simple way of exporting the content of your GridView og ListView to Excel.

protected void ExportExcelButton_OnClick(object sender, EventArgs e)
{
    Response.Clear();
    Response.Buffer = true;
    Response.AddHeader("content-disposition", "attachment;filename=Contacts.xls");
    Response.ContentType = "application/vnd.ms-excel";
    Response.Charset = "";
    EnableViewState = false;
    var stringWriter = new StringWriter();
    var htmlTextWriter = new HtmlTextWriter(stringWriter);
    userListView.RenderControl(htmlTextWriter);
    Response.Write(stringWriter.ToString());
    Response.End();
}

Thursday, July 02, 2009

Error consuming a WSDL in Visual Studio

Symtons
Adding a WCF “Service Reference” in Visual Studio 2008, pointing at http://localhost/FooMessage?wsdl. All the different files are added in Solution Explorer. But investigation the Reference.cs beneath Service References –> ServiceReference1 –> Reference.svcmap –> Reference.cs (found if “Show All Files” is clicked in Solution Explorer) reveals that no code has been generated. No warnings, no nothing. The app.config doesn’t contain no endpoints or binding either.

Cause
I’ve tried to validate the wsdl with the step by step procedure found here http://webservices20.blogspot.com/2008/10/how-to-validate-your-wsdl.html. But the wsdl is “passed” as a legal wsdl. Using svcutil.exe gives me errors though:

C:\>svcutil http://localhost/FooMessage?wsdl
Microsoft (R) Service Model Metadata Tool
[Microsoft (R) Windows (R) Communication Foundation, Version 3.0.4506.2152]
Copyright (c) Microsoft Corporation.  All rights reserved.

Attempting to download metadata from 'http://localhost/FooMessage?wsdl' using WS-Metadata Exchange or DISCO.
Error: Cannot import wsdl:portType
Detail: An exception was thrown while running a WSDL import extension: System.ServiceModel.Description.DataContractSerializerMessageContractImporter
Error: Object reference not set to an instance of an object.
XPath to Error Source: //wsdl:definitions[@targetNamespace='
http://foo.facade.com/']/wsdl:portType[@name='SendFooMessage']

Error: Cannot import wsdl:binding
Detail: There was an error importing a wsdl:portType that the wsdl:binding is dependent on.
XPath to wsdl:portType: //wsdl:definitions[@targetNamespace='
http://foo.facade.com/']/wsdl:portType[@name='SendFooMessage']
XPath to Error Source: //wsdl:definitions[@targetNamespace='http://foo.facade.com/']/wsdl:binding[@name='SendFooMessagePortBinding']

Error: Cannot import wsdl:port
Detail: There was an error importing a wsdl:binding that the wsdl:port is dependent on.
XPath to wsdl:binding: //wsdl:definitions[@targetNamespace='
http://foo.facade.com/']/wsdl:binding[@name='SendFooMessagePortBinding']
XPath to Error Source: //wsdl:definitions[@targetNamespace='http://foo.facade.com/']/wsdl:service[@name='SendFooMessage']/wsdl:port[@name='SendFooMessagePort']

Generating files...
Warning: No code was generated.
If you were trying to generate a client, this could be because the metadata documents did not contain any valid contracts or services
or because all contracts/services were discovered to exist in /reference assemblies. Verify that you passed all the metadata documents to the tool.

Warning: If you would like to generate data contracts from schemas make sure to use the /dataContractOnly option.

Here follows a days effort in trying to make adjustments to the wsdl. Which by the way isn’t mine. Trying to narrow done the different possibilities.

Workaround
To narrow the story down. It turned out to be the differences between XmlSerializer and XmlFormatter. If you use XmlSerializer (use SvcUtil option /serializer:XmlSerializer), it should work fine. Use a tool, svcutil with a switch, to generate the needed code.
svcutil http://localhost/FooMessage?wsdl /serializer:XmlSerializer
This generates two files for you, the SendFooMessage.cs og output.config.

Tuesday, June 30, 2009

Consuming a Web Service with an error in WSDL

In one of my projects I am consuming a third party Web Services, written in I don’t know what. I have WCF Service References to them.

They launces new versions of their services  quit often, so I was fairly sure something was wrong this time. Updating or even deleting and adding references somehow didn’t work right. I could see the service in the browser, after logging on two times (this is normal). Adding or updating  the reference itself also works fine. I’m happy. Started updating all five references, and cleaned up the mess in app.config. Done this many times before. Building.

Error    4    Custom tool error: Failed to generate code for the service reference 'TheService'.  Please check other error and warning messages for details.    D:\temp\ConsoleApplication2\ConsoleApplication2\Service References\TheService\Reference.svcmap    1    1    ConsoleApplication2

What? Expanding all solution files, to investigate the code behind Service Reference/TheService/Reference.svcmap/Reference.cs. Empty!

Running wsdl.exe and svcutil.exe on the downloaded wsdl to investigate more. Finally something to understand: The complexType SomeClass has a property with a blank space in the name attribute. Not allowed. It looked something like this: 

<xs:element name="statusCode " type="foons:StatusCode "/> 




Luckily the vendor was quick to fix this when told. But I really would like Visual Studio to be more robust, either telling me what the problem is when adding a reference to a none valid WSDL or even maybe just remove the whitespace. Like IE does when watching the WSDL file….

Publishing the code samples in Blogspot

I’ve swapped from writing articles inside blogger.com to try out Live Writer. Mainly cause of the hell will copy and pasting in code samples or xml samples. Dave Haynes’s blogged about it here, and I’ll try it out.

Friday, June 26, 2009

WcfService that acts like a WebService

This article is meant as a tutorial for using a logging tool for a WcfServices that looks to the outside world as an old WebService. (Pardon the namespaces, they have been changed to protect the innocent.)

WcfService that acts like a WebService
What I’ve used to do in the past is just add a WCF Service Library to the solution, and make sure binding="basicHttpBinding" is done. This way other platforms and applications could access the service like add web reference that looks something like http://localhost/WebService/WebService.OrderService.svc?wsdl. Why you want to do this? You want to take advantage of what you get in WCF, but still are able to act like a WebService to others that can’t implement WCF Service Reference. Everything else is like standard WCF, [ServiceContract], [OperationContract], [DataContract] and [DataMember] etc.

WcfService that acts like a WebService, but really is a Web Application
Another way of doing this is add a Web Application, strip out all that you don’t need. Like delete Default.aspx*.But instead of adding a new WCF Service, add an ordinary class, and then rename to whatever.svc. And remove all content, and replace it with these few lines:
<%@ ServiceHost Service="Services.OrderService" %>
This service reference should of course map to a class in your solution, probably the business layer. Make sure you add a reference. The business layer would then need a reference to System.Servicemodel to be able to add the needed attributes:

[ServiceBehavior(Namespace = "http://brembo.name/namespace/workorder")]
public class OrderService : IOrderService

[ServiceContract(Name = "OrderService", Namespace = "http://brembo.name/namespace/workorder")]
public interface IOrderService



The web.config would only need these lines (remove everything else):



<?xml version="1.0"?>
<configuration>
<system.serviceModel>
<services>
<service name="Services.OrderService" behaviorConfiguration="DebuggingBehaviour">
<endpoint address="" binding="basicHttpBinding" bindingNamespace="http://schema.brembo.name/" contract="Services.IOrderService"/>
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior name="DebuggingBehaviour">
<serviceMetadata httpGetEnabled="true"/>
<serviceDebug includeExceptionDetailInFaults="true"/>
</behavior>
</serviceBehaviors>
</behaviors>
</system.serviceModel>
<appSettings/>
<connectionStrings/>
</configuration>



The Web Application contains by default many no longer needed references. These are the only one needed: System, System.Core, System.Data, System.Runtime.Serialization, System.ServiceModel. Also add your business layer.




If you like to remove the App_Data folder which isn’t needed, unload project, edit project file and remove these lines:



<itemgroup>
<folder include="App_Data\">
</itemgroup>



This should now run as a wcf service, reachable from ordinary WebService clients.

Monday, June 22, 2009

Project References and Copy Local

In our new project we use both NHibernate. The solution consists of the normal layers; data, business, presentation and common.

The data tier has references to NHibernate, and in hibernate.cfg.xml a need for NHibernate.ByteCode.LinFu is configured. The reference to NHibernate is set to copy local, and NHibernate doesn't exist in the GAC. Which otherways could interfere with the copy local. Ok, everything fine so far. Also a need for a reference to NHibernate.ByteCode.LinFu with copy local is needed, since this assembly is needed run-time. Added a reference with copy local, to get this assembly in the runtime folder. I'm not to happy with this reference, but I can leave with it. What I'd really like is NHibernate self to handle this, and get hold of its needed assemblies. But there is a dynamic reference here.

Fine by now, everything ends up in the datalayer\bin\debug folder. Ahh, but then. I add a project reference in the business layer to the data layer. And from the web application there is added a project reference to the business layer. In the Web\bin folder there are missing some dll's after compiling. Everything that NHibernate needs are there (and all other assembly include their needed assemblies), except for NHibernate.ByteCode.LinFu, LinFu.DynamicProxy and hibernate.cfg.xml.

I don't want the client to know about all the different needs my data access has. So linking in files the client itself doesn't need is not a good option for me. Adding references to assembly not needed by the client the same.

So for now I uses post build events on my data project. Copies explicit the needed files to a temporary bin folder.
mkdir "$(SolutionDir)Bin"
xcopy "$(TargetDir)*LinFu*" "$(SolutionDir)Bin" /y
xcopy "$(TargetDir)hibernate.cfg.xml" "$(SolutionDir)Bin" /y

The client copies all files from this directory in the pre build event to the web\bin folder like this:




xcopy "$(SolutionDir)Bin" "$(TargetDir)*.*" /y

This way all the missing files are copied back and forth, ending up where they are needed.

Saturday, June 20, 2009

Toyota Way House

At the Norwegian Developers Conference 2009 I went to the track with Craig Larman, "Toyota Way House".

The Toyota Way 2001 was educational, and explained to me why some of our project had worked and some had not at all... As a developer by heart, I really enjoyed the bit about a manager should be a teacher and technical specialist in the craftmanship. I had to nod my head, wishfully...

http://en.wikipedia.org/wiki/The_Toyota_Way

Monday, June 01, 2009

My customization of blogger.com

Note to myself when I change template, or if others sees the need, this is my few customizations.

Favicon
Just belove the <head> add theese lines:
<link href='http://logica.com/favicon.ico' rel='shortcut icon'/>
<link href='http://logica.com/favicon.ico' rel='icon'/>

To remove the blogspot header, add this line just above the body tag:
#navbar-iframe { display: none !important;}

Thursday, January 01, 2009

SelfHosting.cs

public class SelfHosting : IDisposable
{
private static ServiceHost serviceHost;
private ApplicationController controller;

///
/// Starts this instance. From Test Projects only.
///

public void Start()
{
Debug.WriteLine("Entering SelfHosting Start");
if (serviceHost != null)
throw new AddressAlreadyInUseException("Selfhosting already started");
serviceHost = new ServiceHost(typeof(OrderService));
serviceHost.Open();
ApplicationStart();
}

///
/// Stops this instance.
///

public void Stop()
{
Debug.WriteLine("Entering SelfHosting Stop");
if (serviceHost != null)
serviceHost.Close();
serviceHost = null;
}

private void ApplicationStart()
{
Debug.WriteLine("Entering SelfHosting ApplicationStart");
try
{
controller = new ApplicationController();
controller.Initialize(Environment.CurrentDirectory);
}
catch (ApplicationInitializationException exception)
{
LoggerFactory.New().Fatal(exception);
throw;
}
}



#region Implementation of IDisposable

private bool disposed;
///
/// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
/// Implements to avoid when starting a
/// test after another one has failed leave a none clean state.
///

public void Dispose()
{
Debug.WriteLine("Entering SelfHosting Dispose");
if (!disposed)
{
Dispose(true);
GC.SuppressFinalize(this);
disposed = true;
}
}

///
/// Releases unmanaged and - optionally - managed resources
/// Set large fields to null
/// Free managed resources
///

/// true to release both managed and unmanaged resources; false to release only unmanaged resources.
private void Dispose(bool disposing)
{
if (disposing)
{
controller.Dispose();
if (serviceHost != null)
serviceHost.Close();
serviceHost = null;
}
}

///
/// Releases unmanaged resources and performs other cleanup operations before the
/// is reclaimed by garbage collection.
///

~SelfHosting()
{
Dispose(false);
}

#endregion
}

Tuesday, January 16, 2007

How to build a project containing Reporting Service project

Follow this link to msdn forum: http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=304374&SiteID=1

Solution file warning MSB4122: Scanning project dependencies for project "TestProject\TestProject.rptproj" failed. The default XML namespace of the project must be the MSBuild XML namespace. If the project is authored in the MSBuild 2003 format, please add xmlns="http://schemas.microsoft.com/developer/msbuild/2003" to the element. If the project has been authored in the old 1.0 or 1.2 format, please convert it to MSBuild 2003 format.
This error message appears while trying to build a team build on TFS.
In order to perform Code Analysis on managed binaries, MSBuild needs to launch FxCop. MSBuild is unable to locate the FxCop binaries. Make sure Visual Studio Team Edition for Software Developers or Visual Studio Team Suite is installed and run MSBuild from within the "Visual Studio Command Prompt" or specify the path to FxCop by setting the FXCOPDIR environment variable.

This means you have to install some version of VSTS on the Build Server. Licensing of Team Test, Team Dev, Team Architect and Team Suite are per-user, not per machine. You are free to install another copy on the build machine as long as everyone who uses it is licensed to use the tools.
F-Secure and VSTS doesnt work!!!

After weeks and months of problems with the Team Foundation Server Workgroup Edition and Visual Studio Team System Suite 180 days trial. I finally got my hands the real deal. I thought. Installing TFS for the sevent time on the server, and VSTS developer edition on my laptop. Read to go. But NO! Creating new team site failes! Still! God ¤#¤##%. Nothing to work with. devenv.exe just drops dead. Would you like to send the error message. Yes, but no solution is suggested.

My colleague got a fresh mashine, installs VSTS developer edition. But the same thing happens. Lucky for him, he has something to work with. Shreds of evidens in the event log.

Devenv.exe (VS) has a problem with an F-Secure dll. Shutting down all five or six F-Secure processes EVERYTHING WORKS FINE!!

Could I please send the bill to F-Secure which is more of a virus, then an anti-virus?

Wednesday, October 18, 2006

Sandcastle
Documentation compilers for managed class libraries

I've tested this documention tool which is i September CTP now. Added this as a pre-compile event, and my CHM-dokumentation is always up to date.

This tool: SandcastleGUI - http://www.inchl.nl/SandcastleGUI/, I've found very usefull.

If you open a test results file in VSTS and go to view code coverage results, and get the message “Code coverage is not enabled for this test run“. Here what to do:
  1. In your Visual Studio solution, you should have a Solution Items folder. In this folder, you should see a file named localtestrun.testrunconfig. Open it.
  2. On the left, click the Code Coverage option.
  3. Under Artifacts to instrument, select your code assembly and its corresponding test assembly.
  4. Click Apply then click Close.

See more at loudcarrot.

Tuesday, October 03, 2006

Finally I got my self to install the next big thing on my home computer. Office 2007 b2tr. It seems to be working fine. Except that sending mail didnt work no longer. No biggi thoug. The imported account setting seemed fine, but I had to delete it and manually add it again. By manually configure settings, whats the deal with Auto Account Setup? Will that ever work for my accounts?

Tuesday, June 26, 2001