Friday 7 October 2011

Postbuild events for Sharepoint projects in Visual Studio 2010

This is really helpful:
"C:\Program Files (x86)\Microsoft SDKs\Windows\v7.0A\Bin\gacutil.exe" -u $(TargetName)
"C:\Program Files (x86)\Microsoft SDKs\Windows\v7.0A\Bin\gacutil.exe" -i "$(TargetPath)"
%windir%\system32\inetsrv\AppCmd recycle APPPOOL "SharePoint - 80"

It automatically adds dll to GAC and recycles application pool.

Friday 27 May 2011

Creating folder in a document library and creating file inside that folder

In order to create programmatically folder inside library and then create file inside that folder you can use following code:

using (SPWeb web = properties.Web.Site.OpenWeb("/web"))
{
 list = web.Lists["My list"];

 SPFolderCollection collection = list.RootFolder.SubFolders;
 //Create new folder
 SPFolder folder = collection.Add("Automatically created at " + DateTime.Now.ToString().Replace(":", "-"));
 item = folder.Item;
 item[SPBuiltInFieldId.Comments] = "Automatically created";

 this.EventFiringEnabled = false;
 try
 {
  item.Update();
 }
 finally
 {
  this.EventFiringEnabled = true;
 }
}
//insert attachment to folder
if (item.Folder != null)
{
 SPFolder folder = item.Folder;
 if (properties.ListItem.Attachments.Count > 0)
 {
  SPFile file = item.Web.Site.RootWeb.GetFile(properties.ListItem.Attachments.UrlPrefix + properties.ListItem.Attachments[0]);
  byte[] imageData = file.OpenBinary();
  SPListItem contractItem = folder.Files.Add(properties.ListItem.Attachments[0], imageData).Item;
  contractItem.Update();
 }
}

Thursday 26 May 2011

Creating a generic list of an anonymous type ?!?

Yesterday I was wondering how to create a generic list of an anonymous type, something like this:
var employee = new { FirstName = "Jan", LastName = "Kowalski" };
var employeeList = new List();
At the beginning I though this was impossible, but the resolution is closer than it appears:

var employee = new { FirstName = "Jan", LastName = "Kowalski" };
var employeeList = (new[] {employee}).ToList();
employeeList.Clear();

We can extend it to create factory creating those lists:
public static List<T> CreateList<T>(T itemOftype)
{
   List<T> newList = new List<T>();
   return newList;
}

Tuesday 5 April 2011

WCF tutorial part 03 - setting endpoints inside app.config file

In this part I'm going to show you how to set endpoints inside app.config file instead of heaving them in code. This way we can easily change them in the future without need to recompile our application.

Host
From Program.cs file remove line with baseAddress definition, also change ServiceHost construction to following
ServiceHost serviceHost = new ServiceHost(typeof(MyService.Service));
our Program.cs file Main method will start with
ServiceHost serviceHost = new ServiceHost(typeof(MyService.Service));
try
{    
 serviceHost.Open();
 Console.WriteLine("The service is ready.");
 Console.WriteLine("Press <ENTER> to terminate service.");
 Console.ReadLine();

 serviceHost.Close();
}
...catches etc.
Add App.config file to WCFHost project
Put this into this file:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <system.serviceModel>
        <behaviors>
            <serviceBehaviors>
              <behavior name="Metadata">
                <serviceMetadata httpGetEnabled="true" httpGetUrl="http://localhost:8000/meta" />
              </behavior>
            </serviceBehaviors>
        </behaviors>
        <services>
            <service behaviorConfiguration="Metadata" name="MyService.Service">
                <endpoint address="net.tcp://localhost:9000/tcp" binding="netTcpBinding"
                    contract="MyService.IService" listenUriMode="Explicit" />
            </service>
        </services>
    </system.serviceModel>
</configuration>
First I'm adding Metadata behavior, it's almost equal to putting this in code:
ServiceMetadataBehavior smb = new ServiceMetadataBehavior();
smb.HttpGetEnabled = true;
serviceHost.Description.Behaviors.Add(smb);
I'm also specifying where will be metadata available (http://localhost:8000/meta)
Then I'm creating new tcp endpoint at address net.tcp://localhost:9000/tcp.

Client
Now we need to recofigure our client. Service reference cannot be updated since metadata location has changed. First, start your host project (remember setting startup project mode to current selection). If the host is up, right click on ServiceReference and choose Configure Service Reference...


If you receive error similiar to this one:
remove your service reference completely and add new service reference.
In both cases as new address enter http://localhost:8000/meta . Service should have been discovered (click Go):
 If it's discovered correct Namespace to ServiceReference and click OK.
Start you're client - it should connect to the host without any further changes needed.
You can download source code from here:
http://sites.google.com/site/terespl/files/WCFTutorialpart03.zip

Thursday 31 March 2011

Interesting online programming course (in polish only)

If you are interested in online programming course covering ASP.NET MVC 3 programming you must definitely visit this address http://codingtv.pl/ . The authors: Łukasz Gąsior and Andrzej Kowal are also speaking about tools which are used for creating project.
In polish only.

Wednesday 30 March 2011

Endpoints using 'UriTemplate' cannot be used with 'System.ServiceModel.Description.WebScriptEnablingBehavior'.

I was getting this exception (Endpoints using 'UriTemplate' cannot be used with 'System.ServiceModel.Description.WebScriptEnablingBehavior'.) all the time, after I specified my service contract (I was using WebScriptEnablingBehavior):
public interface ICourseService
{
 [WebGet(UriTemplate = "GetCourseList", ResponseFormat = WebMessageFormat.Json)]
 [OperationContract]
 List GetCourseList();
}
Well... it turns out, this parameter combination is forbidden, instead use this:
public interface ICourseService
{
 [WebGet(ResponseFormat = WebMessageFormat.Json)]
 [OperationContract]
 List GetCourseList();
}
notice, there's no UriTemplate. Eventhough you can still navigate to: http://localhost:60377/TestSite/test.svc/GetMyList and it will retrieve JSON file.

Sunday 27 March 2011

WCF tutorial part 02 - separating service from host

In this tutorial we're going to separate service from host. In my opinion it's a good pattern to have service separated from host.
Let's add a new project to solution and call it MyService
After this, drag IService.cs and Service.cs files from WCFHost to MyService project. Remove them from original WCFHost project.
Change namespace in those files to MyService.
Make interface and class publicly accessible by adding public modifier to their definitions.

Add reference in WCFHost project to MyService project:

Build WCFHost project, this should build MyService library and copy the dll file to WCFHost project.

We need to make few adjustments in our host, to compile it. Only this section contains changes:
- in line 2 we're updating service type to MyService.Service
- in line 6 we're updating type of interface used to MyService.IService

Uri baseAddress = new Uri("http://localhost:8000/Service");
ServiceHost serviceHost = new ServiceHost(typeof(MyService.Service), baseAddress);
try
{
 serviceHost.AddServiceEndpoint(
  typeof(MyService.IService),
  new WSHttpBinding(),
  "Service");

 ServiceMetadataBehavior smb = new ServiceMetadataBehavior();
 smb.HttpGetEnabled = true;
 serviceHost.Description.Behaviors.Add(smb);

 serviceHost.Open();
 Console.WriteLine("The service is ready.");
 Console.WriteLine("Press <ENTER> to terminate service.");
 Console.ReadLine();

 serviceHost.Close();
} 
 
We should update service reference in our client project, in order to do this you should:
  1. set startup project mode to current selection, 
  2. start WCFHost,
  3. rightclick on Service References - ServiceReference in WCFClient project and choose "Update Reference"
  4. start WCFClient project - there should be no errors.
Congratulations - you're done.
You can download project from here: http://sites.google.com/site/terespl/files/WCFTutorialpart02.zip