Archive

Archive for September, 2009

WCF RESTFul and webHttpBinding configs

September 27, 2009 Leave a comment

There are few things to notice to config the webHttpBinding if you want to build a RESTFul WCF

1. Add [WebGet(UriTemplate=”countries”)] to existing Interfaces

2. App.config

add a new endpoint

<endpoint address="" binding="webHttpBinding" behaviorConfiguration="webBehavior" contract="GeoService.Data.Services.IGeoService" />

which bind to an endpointBehavior

<endpointBehaviors>
        <behavior name="webBehavior">
          <webHttp/>
        </behavior>
</endpointBehaviors>

 

3. in the hosting site Add Factory to the <%@ erviceHost … %>

Factory="System.ServiceModel.Activation.WebScriptServiceHostFactory"

 

However seems it’s an optional, works for me without the Factory

Another thing to notice that webHttpBinding don’t work with wcftestclient.exe

so you have to test it in the web browser.

Categories: Uncategorized

NO IEnumerable in WCF!

September 26, 2009 Leave a comment

I’ve experiencing this WCF bug which turns out a known WCF bUgGGG

https://connect.microsoft.com/wcf/feedback/ViewFeedBack.aspx?FeedbackID=336696

basically it won’t work 100% if the returning type if IEnumerable<T> in WCF.

Its all working in my localhost, but when I deploy the WCF service to a server it stopped working

I guess a better return type would be IList<T>

Categories: .NET

WCF HOWTOS

September 25, 2009 Leave a comment
 
Here’s how I did to get WCF host/client working.
 
This link is quite helpful to start with http://msdn.microsoft.com/en-us/netframework/dd939784.aspx (Beginner’s guide to WCF)
 

1. Create a new WCF Service Library project

 

New Project –> WCF –> WCF Service Library

 
It has on one simple contract – GetCountries() for demo purpose
 

namespace GeoService.Data.Services
{
    [ServiceContract]
    public interface IGeoService
    {
        [OperationContract]
        IEnumerable<Models.Country> GetCountries();
    }
}

namespace GeoService.Data.Models
{
    [DataContract]
    public class Country
    {
        [DataMember]
        public int CountryId { get; set; }

        [DataMember]
        public string CountryCode { get; set; }
    }
}

I’ve also put in linq dbml to retrieve countries form the database.

Check the endpoints

By default there are 2 endpoints mexHttpBinding and wsHttpBinding, I added one more basicHttpBinding

Contract should be set to the interfact – GeoService.Data.Services.IGeoService

2. Create a WCF Host website

New Website –> WCF Service

add a project reference to the GeoService.Data

open Service.svc and modify the top line to

<%@ ServiceHost Language="C#" Debug="true" Service="GeoService.Data.Services.GeoService" %>

right click web.config –> Edit WCF Configuration make sure there are 3 endpoints there.

 

3. Host it in IIS 7

 

To register WCF host extension (.svc) in IIS 7

 

There were more errors related to local machine below these errors.I looked up the net and after some digging figured out the solution to the problem:

  1. Run Visual Studio 2008 Command Prompt as “Administrator”.
  2. Navigate to C:WindowsMicrosoft.NETFrameworkv3.0Windows Communication Foundation.
  3. Run this command servicemodelreg –i.

The servicemodelreg is a command line tool which provides the ability to manage the registration on ServiceModel on a machine. You can get more info on the tool at MSDN here.

up till this point, you should be able to open it in browser.

http://localhost/GeoService/Service.svc

4 To consume WCF in your client application

 

In your project’s data layer add service referent to this http://localhost/GeoService/Service.svc and name it “GeoServiceReference”

It generates all the config settings in app.config inside <system.serviceModel> section

Now you can use this WCF service

depending on which endpoint you want to use

GeoServiceReference.GeoServiceClient geo = new GeoServiceReference.GeoServiceClient("BasicHttpBinding_IGeoService");
or
GeoServiceReference.GeoServiceClient geo = new GeoServiceReference.GeoServiceClient("WSHttpBinding_IGeoService”);

var x = geo.GetCountries();

5. Run the website, Failed, why?

 

Took me a while to find out that I have to copy the whole app.config settings to the website’s web.config! (the system.serviceModel)

that means everytime you change app.config wcf settngs, make sure you copy the change back into web.config. otherwise it the website

won’t be able to know the endpoint at run time!

It’s actually very same as Linq’s dbml settings, you have to have the sql settings in the web.config too.

Categories: .NET

Apply CSS to Html.ActionLink()

September 25, 2009 Leave a comment
wow didn’t realize to apply css to ActionLink is this tricky.
 
the working version for me is
 
<%= Html.ActionLink(" ", "ConditionsOfEntry", "Home", new { }, new { @class = "btn_form_sprite btn_cdt_entry" })%>
 
( it won’t work without the first new { } !!!)
 
it’s almost like a bug in mvc 1.0
 

 

 
Categories: .NET

2 buttons in the same MVC Form

September 24, 2009 Leave a comment
There are several ways to handle multiple submit buttons in MVC form.
 
<input type="submit" name="Cancel" value="Cancel" />
<input type="submit" name="Create" value="Create" />
 

the easiest no brainer way.

        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Create(string create, string cancel)
        {
                if (create != null) //meaning create got clicked
                if (cancel != null) //meaning cancel got clicked
        }

Another way (it’s not post any data, only to trigger the Cancel() action method

 
<input type="button" name="Cancel" value="Cancel" onclick="$(‘#cancelForm’).submit()" />
<input type="submit" name="Create" value="Create" />
<% using (Html.BeginForm("Cancel", "Product", FormMethod.Post, new { id = "cancelForm" })) { } %>
 
 [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Cancel(string productName, string country, string cancel)
        {
            return View();
        }
 
 

Another way (to use javascript to do the form post)


$
('#button1').click( function() {
          $
(form).attr( 'action', '<% Url.Action( "action1" ) %>' )
                 
.submit();
         
return false; // prevent default submission
     
});
Categories: .NET

MVC and DropDownList

September 23, 2009 Leave a comment

View

 
Page Interits="System.Web.Mvc.ViewPage<MVC1.Controllers.ProductFormViewModel>"
 
<% using (Html.BeginForm()) { %>
      Country: <%= Html.DropDownList("Country", Model.Countries) %>
<% } %>
 

Model

 

public class ProductFormViewModel
    {
        public Model.Product Product { get; private set; }
        public SelectList Countries { get; private set; }

        public ProductFormViewModel(Model.Product product)
        {
            Product = product;

            IList<SelectListItem> allCountries = new List<SelectListItem>();
            allCountries.Add(new SelectListItem { Text = "AUS", Value = "AUS" });
            allCountries.Add(new SelectListItem { Text = "USA", Value = "USA" });

            Countries = new SelectList(allCountries, "Value", "Text", "USA");
        }
    }

 

Controller

 

public ActionResult Create()
        {
            Model.Product product = new Model.Product();
            return View(new ProductFormViewModel(product));
        }

 

[AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Create(string productName, string country)
        {
            if (ValidateProduct(productName, country))
            {
                //if validated, proceed to create new product
                bool success = false;

                if (success)
                {
                    return RedirectToAction("Index", "Home");
                }
                else
                {
                    ModelState.AddModelError("_FORM", "Exception during creating a new product");
                }
            }

            return View(new ProductFormViewModel(new Model.Product()));
        }

Categories: .NET

To Access Subversion repository hosted inside the VM

September 21, 2009 Leave a comment
Install the Subversion in one of the VM. the URL noramlly looks like
 
To access it from Host machine – my Windows 7 box (x64 bit)
 
you can either.
 
 
2. edit IIS host file add an entry (C:WindowsSystem32driversetc)
 
192.168.1.104       SVNCC.Home.local
and then you can use Https://SVNCC.Home.local/svn directly from the host machine.
 
Categories: .NET

Microsoft FxCop 1.36 Beta 2 and Visual Stduio 2008 integration

September 21, 2009 Leave a comment
1. Brand new install of FxCop 1.36 beta 2
2. Add Target… (to add in the assemblies you’d like to FxCop with)
3. Save the FxCop project into the same directory of your VS solution file.
    ie. if your solution is called MySolution.sln, then name your FxCopy to "MySolution.sln.FxCop"
 
4. Done, now you can run FxCop from it’s UI
 

Now you want to integrate FxCop into VS 2008 ehhh??

 

1.

In Visual Studio select Tools->External Tools…  You should see the External Tools dialog box.

You must fill following fields:

Title: FxCop
Command: C:Program FilesMicrosoft FxCop 1.36FxCopCmd.exe
Arguments: /c /p:"$(SolutionDir)$(SolutionFileName).fxcop" /cXsl:"C:Program FilesMicrosoft FxCop 1.36XmlVSConsoleOutput.xsl"
Initial Directory: C:Program FilesMicrosoft FxCop 1.36
Use output window

Must be checked

 

2. Tools -> FxCop to run it!
    The result should appear in VS output window.
 
 

Now you want to chuck FxCop into your Build Process eh??

 
I’ve got it working based on Microsoft FxCop 1.36 Beta 2 and Cruise Control 1.4.3.4023
 
Firstly please use this FxCopReport.xsl instead of the the comes with Cruise Control.net installer (took me half day to fig it out!)
 
 
Apart from this FxCopReport.xml rest are relatively straightforward.
 
1. Install FxCop on build server.
2. Modify Nant script to add in
<target name="fxcop" depends="compileDebug">
  <exec program="C:Program FilesMicrosoft FxCop 1.36FxCopCmd.exe" failonerror="false">
   <arg value="/f:${website.root.path}/bin/Pulse.*.dll" />
   <arg value="/o:c:fxcop-result.xml" />
   <arg value="/forceoutput" />
  </exec>
 </target>
 
3. Back to the ccnet.config file add in Merge section
 
  <tasks>
       <nant>
         <executable>C:Program Filesnant-0.85binNant.exe</executable>
   <baseDirectory>C:SVNScriptsSony.Pulse</baseDirectory>
   <buildFile>sony.pulse.full.ci.build</buildFile>
       </nant>
   
   <merge>
    <files>
     <file>c:fxcop-result.xml</file>
    </files>
   </merge>
   
     </tasks>
 
4. edit dashboard.config in (c:programs files…etc)
 
add in <xslReportBuildPlugin description="FxCop Report" actionName="FxCopBuildReport" xslFileName="xslFxCopReport.xsl" /> (if it’s not there)
and maybe <xslFile>xslfxcop-summary.xsl</xslFile>
     <xslFile>xslFxCopReport.xsl</xslFile>
 
5. Copy the custom FxCopReport.xsl to C:Program FilesCruiseControl.NETwebdashboardxsl
 
I think that’s about it!!
 
 
 
 
Categories: .NET

BuildLibrary.bat

September 19, 2009 Leave a comment
This is the script comes with MS Enterprise Library. run to build the whole solution
 
@echo off
@REM  —————————————————————————-
@REM  BuildLibrary.bat file
@REM
@REM  This batch file builds the Enterprise Library application blocks and tools.
@REM  By default, it builds a Debug build.
@REM 
@REM  Optional arguments for this batch file:
@REM    1 – Build type. Defaults to Debug
@REM  —————————————————————————-
echo.
echo =========================================================
echo   BuildLibrary                                          
echo      Builds Enterprise Library                          
echo =========================================================
echo.
set msBuildDir=%WINDIR%Microsoft.NETFrameworkv3.5
set solutionDir="..Blocks"
set buildType=Debug
set returnErrorCode=true
set pause=true
if "%1"=="/?" goto HELP
if not Exist %solutionDir%EnterpriseLibrary.sln goto HELP
@REM  —————————————————-
@REM  If the first parameter is /q, do not pause
@REM  at the end of execution.
@REM  —————————————————-
if /i "%1"=="/q" (
 set pause=false
 SHIFT
)
@REM  —————————————————-
@REM  If the first or second parameter is /i, do not
@REM  return an error code on failure.
@REM  —————————————————-
if /i "%1"=="/i" (
 set returnErrorCode=false
 SHIFT
)
@REM  —————————————————-
@REM  User can override default build type by specifiying
@REM  a parameter to batch file (e.g. BuildLibrary Debug).
@REM  —————————————————-
if not "%1"=="" set buildType=%1
@REM  ————————————————
@REM  Shorten the command prompt for making the output
@REM  easier to read.
@REM  ————————————————
set savedPrompt=%prompt%
set prompt=*$g
@ECHO —————————————-
@ECHO BuildLibrary.bat Started
@ECHO —————————————-
@ECHO.
@REM ——————————————————-
@REM Change to the directory where the solution file resides
@REM ——————————————————-
pushd %solutionDir%
@REM ——————————————————-
@REM Change to the directory where the solution file resides
@REM ——————————————————-
if "%DevEnvDir%"=="" (
 @ECHO ——————————————
 @ECHO Setting build environment
 @ECHO ——————————————
 @CALL "%VS90COMNTOOLS%vsvars32.bat" > NUL
 @REM Remove LIB env var to work around known VS 2008 bug
 @SET Lib=
)
@ECHO.
@ECHO ——————————————-
@ECHO Building the Enterprise Library assemblies
@ECHO ——————————————-
call %msBuildDir%msbuild EnterpriseLibrary.sln /t:Rebuild /p:Configuration=%buildType%
@if errorlevel 1 goto :error
@ECHO.
@ECHO —————————————-
@ECHO BuildLibrary.bat Completed
@ECHO —————————————-
@ECHO.
@REM  —————————————-
@REM  Restore the command prompt and exit
@REM  —————————————-
@goto :exit
@REM  ——————————————-
@REM  Handle errors
@REM
@REM  Use the following after any call to exit
@REM  and return an error code when errors occur
@REM
@REM  if errorlevel 1 goto :error 
@REM  ——————————————-
:error
if %returnErrorCode%==false goto exit
@ECHO An error occured in BuildLibrary.bat – %errorLevel%
if %pause%==true PAUSE
@exit errorLevel
:HELP
echo Usage: BuildLibrary [/q] [/i] [build type]
echo.
echo BuildLibrary is to be executed in the directory where EnterpriseLibrary.sln resides
echo The default build type is Debug.
echo.
echo Examples:
echo.
echo    "BuildLibrary" – builds a Debug build     
echo    "BuildLibrary Release" – builds a Release build
echo.
@REM  —————————————-
@REM  The exit label
@REM  —————————————-
:exit
if %pause%==true PAUSE
popd
set pause=
set solutionDir=
set buildType=
set returnErrorCode=
set prompt=%savedPrompt%
set savedPrompt=
echo on
 
 

Here’s some addition script for DB creation

 
@ECHO.
@ECHO —————————————————————–
@ECHO Logging
@ECHO —————————————————————–
@ECHO.
cd ..BlocksLoggingSrcDatabaseTraceListenerScripts
if Exist CreateLoggingDb.cmd Call CreateLoggingDb.cmd
@if errorlevel 1 goto :error
 
CreateLoggingDb.cmd
 

osql -S (local)SQLEXPRESS -E -i LoggingDatabase.sql

LoggingDatabase.sql

USE [master]
GO

IF EXISTS (SELECT name FROM master.dbo.sysdatabases WHERE name = N’Logging’)
 DROP DATABASE [Logging]
GO

CREATE DATABASE [Logging]
 COLLATE SQL_Latin1_General_CP1_CI_AS
GO

Othere DB scripts

SET NOCOUNT ON
GO

USE master
GO
if exists (select * from sysdatabases where name=’Northwind’)
  drop database Northwind
go

DECLARE @device_directory NVARCHAR(520)
SELECT @device_directory = SUBSTRING(filename, 1, CHARINDEX(N’master.mdf’, LOWER(filename)) – 1)
FROM master.dbo.sysaltfiles WHERE dbid = 1 AND fileid = 1

EXECUTE (N’CREATE DATABASE Northwind
  ON PRIMARY (NAME = N”Northwind”, FILENAME = N”’ + @device_directory + N’northwnd.mdf”)
  LOG ON (NAME = N”Northwind_log”,  FILENAME = N”’ + @device_directory + N’northwnd.ldf”)’)
go

exec sp_dboption ‘Northwind’,’trunc. log on chkpt.’,’true’
exec sp_dboption ‘Northwind’,’select into/bulkcopy’,’true’
GO

 
 
Categories: .NET

Windows Powershell

September 18, 2009 Leave a comment
When you run a powershell script you’ll most likely run into
File C:scriptstest.ps1 cannot be loaded because the execution of scripts is disabled on this system. Please see "get-
help about_signing" for more details.
At line:1 char:19
+ c:scriptstest.ps1 <<<<
It is because  By default, PowerShell’s execution policy is set to Restricted; that means that scripts – including those you write yourself – won’t run. Period.
Now, admittedly, this might seem a bit severe. After all, what’s the point of having a scripting environment if you can’t even run scripts with it? But that’s OK. If you don’t like the default execution policy (and you probably won’t) then just go ahead and change it. For example, suppose you want to configure PowerShell to run – without question – any scripts that you write yourself, but to run scripts downloaded from the Internet only if those scripts have been signed by a trusted publisher. In that case, use this command to set your execution policy to RemoteSigned:
Set-ExecutionPolicy RemoteSigned
Alternatively, you can set the execution policy to AllSigned (all scripts, including those you write yourself, must be signed by a trusted publisher) or Unrestricted (all scripts will run, regardless of where they come from and whether or not they’ve been signed). 
 
For now I 'll use 

Set-ExecutionPolicy RemoteSigned

to be able to my my local scripts
 
 
 
 
Categories: .NET