WCF RESTFul and webHttpBinding configs
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.
NO IEnumerable in WCF!
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>
WCF HOWTOS
1. Create a new WCF Service Library project
New Project –> WCF –> WCF Service Library
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:
- Run Visual Studio 2008 Command Prompt as “Administrator”.
- Navigate to C:WindowsMicrosoft.NETFrameworkv3.0Windows Communication Foundation.
- 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.
Apply CSS to Html.ActionLink()
2 buttons in the same MVC Form
<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="submit" name="Create" value="Create" />
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
});
MVC and DropDownList
View
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()));
}
To Access Subversion repository hosted inside the VM
Microsoft FxCop 1.36 Beta 2 and Visual Stduio 2008 integration
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
|
Now you want to chuck FxCop into your Build Process eh??
<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>
<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>
<xslFile>xslFxCopReport.xsl</xslFile>
BuildLibrary.bat
@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 BuildLibrary
echo Builds Enterprise Library
echo =========================================================
echo.
set solutionDir="..Blocks"
set buildType=Debug
set returnErrorCode=true
set pause=true
@REM If the first parameter is /q, do not pause
@REM at the end of execution.
@REM —————————————————-
set pause=false
SHIFT
)
@REM If the first or second parameter is /i, do not
@REM return an error code on failure.
@REM —————————————————-
set returnErrorCode=false
SHIFT
)
@REM User can override default build type by specifiying
@REM a parameter to batch file (e.g. BuildLibrary Debug).
@REM —————————————————-
@REM Shorten the command prompt for making the output
@REM easier to read.
@REM ————————————————
set savedPrompt=%prompt%
set prompt=*$g
@ECHO BuildLibrary.bat Started
@ECHO —————————————-
@ECHO.
@REM Change to the directory where the solution file resides
@REM ——————————————————-
@REM Change to the directory where the solution file resides
@REM ——————————————————-
@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 Building the Enterprise Library assemblies
@ECHO ——————————————-
@if errorlevel 1 goto :error
@ECHO —————————————-
@ECHO BuildLibrary.bat Completed
@ECHO —————————————-
@ECHO.
@REM Restore the command prompt and exit
@REM —————————————-
@goto :exit
@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
if %pause%==true PAUSE
@exit errorLevel
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 The exit label
@REM —————————————-
:exit
if %pause%==true PAUSE
set pause=
set solutionDir=
set buildType=
set returnErrorCode=
set prompt=%savedPrompt%
set savedPrompt=
Here’s some addition script for DB creation
@ECHO —————————————————————–
@ECHO Logging
@ECHO —————————————————————–
@ECHO.
cd ..BlocksLoggingSrcDatabaseTraceListenerScripts
if Exist CreateLoggingDb.cmd Call CreateLoggingDb.cmd
@if errorlevel 1 goto :error
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
Windows Powershell
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