Wednesday, December 26, 2012

How to use MVC templates and knockout

Recently I am wirting a MVC4 application with some CRUD operation.
MVC provide the templates view to make model view easier. Knockout is a good javascript library to provide the view model binding. Then how to use best of the two together?

Here is a link which shows a good example to use both.

Basically, the template view only needs to add the attribute data-bind with the model property name.
and the property name can get from ViewData.ModelMetaData.PropertyName.

The link above only shows how to add the data-binding to the template. There are still a few things to be done to use knockout.

Knockout needs a ViewModel javascript to track the items and the code sample only returns a C# Model object.

Here is the data transform maps needed.
C# <Object > ---> JSON (javascript object) ---> KnockOut ViewModel

1. To translate model to json, use the following code,
@Html.Raw(
Json.Encode(ViewData.Model));

However, Json class is from a System.Web.Helpers assembly, which not included by MVC4.
The assembly needs to be added to the project from GAC.

2. knockout mapping is a js library to convert javascript object to viewModel,
which can be downloaded from here..

ViewModel = ko.mapping.fromJS( jsonObj );

Wednesday, December 19, 2012

Create the right connection name for Entity Framework Code First

When setting up the connection string for the Entity framework code first as default to use, the connection name should be the FULL namespace to the context.

For Eg.
<add name="EFWebTest.Models.BlogContext" providerName="System.Data.SqlClient" connectionString="Data Source=.;Integrated Security=SSPI;Initial Catlog=aspnet-EFWebTest" />

The connection string is using sql server. So when the context is loaded, the default database structure will be created in sql server.

Another option is to pass the connection string name in the dbcontext constructor such as,
public sampleDbContext : base("DefaultConnection") {}

Monday, December 10, 2012

SharePoint 2013 Manage Business Data Connectivity Service Access Denied

This is a weird issue that can not manage the Business Data connectivity service.
In the event log, the error details is

The BDC Service application Business Data Connectivity Service is not accessible. The full exception text is: Access is denied.

After followed the fix in this link, then it worked.
Note: This is still not the best solution and should be in dev server only.

 

Sunday, December 9, 2012

Sharepoint show detailed error message

To show a detailed error message, the site web.config needs to be modified with the following things,
1. CustomErrors = Off
2. CallStack = true
3. Debug=true

However, it is still possible to hit the following screen,

 
There is another web.config in _layouts folder need to be modified as well,
 
 

Saturday, December 8, 2012

SharePoint 2013 - Create a search app

It is not hard to create an App for search to use search javascript.

The search REST service is at http://site/_api/search/query?querytext='querytext'

In the app, need to add search permission,
 
In the default app page, the following html elements are defined.
<div id="toolbarDiv">
 
<input type="text" id="queryTerms" />
<button onclick="executeQuery($get('queryTerms').value); return false;">Search</button>
</div>
 
 
And here is the example script to send the query text to search service and display the results.

function executeQuery(queryTerms) {
    Results = {
        element: '',
        url: '',
        init: function (element) {
            Results.element = element;
            Results.url = _spPageContextInfo.webAbsoluteUrl + "/_api/search/query?querytext='" + queryTerms + "'";
        },
        load: function () {
            $.ajax({
                url: Results.url,
                method: "GET",
                headers: { "ACCEPT": "application/json" },
                success: Results.onSuccess,
                error: Results.onError
            });
        },
        onError: function (error) { alert(JSON.stringify(error)); },
        onSuccess: function (data) {
            var results = data.d.query.PrimaryQueryResult.RelevantResults.Table.Rows.results;
            var html = "<table>";
            for (var i = 0; i < results.length; i++) {
                html += "<tr><td>";
                html += results[i].Cells.results[3].Value;
                html += "</td><td>";
                html += results[i].Cells.results[6].Value;
                html += "</td></tr>";
                }
            html += "</table>";
            Results.element.html(html);
        }
    }
    Results.init($('#resultsDiv'));
    Results.load();
       
}

SharePoint Search - how to reate a custom template view

In SharePoint 2013, rather than using XST, it can be created in html and javascript.

1. Create the template

In the Search Site, go to Site Settings -> Master Pages and Page Layout
In the Display Templates / Search Folder,
Based on the existing template and create custom template.html and upload to here.
In the page properties, make sure content type is Item Display Template and the target control type is for Search Results.

2. Set up the template to be used

In the search site, go to Site Settings -> Result Types,
Create a new Result Type and select it to use the new template






Thursday, December 6, 2012

Include twitter bootstrap scripts in MVC 4

Recently I have been looking at the Twitter bootstrap, this is so far the best design toolkit to start your web site. There is a tutorial to start to learn it.

Also now there is a bootstrap package for asp.net mvc4 to install from Nuget.

If you want to use it directly in the MVC4 layout by adding the bootstrap minify script in the layout view page, you will have the error in browser such as,

Unhandled exception at line 6, column 27 in http://localhost:63410/Bootstrap/js/bootstrap.min.js
0x800a138f - JavaScript runtime error: Object expected

To fix this, you need to include JQuery (1.7 above) first before add the bootstrap.min.js
   
@Scripts.Render("~/bundles/jquery")
<script src="/Bootstrap/js/bootstrap.min.js" type="text/javascript"></script>



Wednesday, November 28, 2012

BizTalk BAM Portal View Message Error

In the Bam portal, when tried to click "related documents -> MessageBody", which access the url,

http://localhost/bam/bammanagementservice/bammanagementservice.asmx/GetReferences?viewName=&referenceType=MsgBody...

Then I got the following error message,
Request format is unrecognized for URL unexpectedly ending in '/GetReferences'

 

 
This issue is because the web.config is not fully configured.
 
Fix:
 
In the web.config of the BamManagement web servcie, which is in C:\Program Files (x86)\Microsoft BizTalk Server 2010\BAMPortal\BAMManagementService
 
Add the following configuration,
 
<configuration>
    <system.web>
    <webServices>
        <protocols>
            <add name="HttpGet"/>
            <add name="HttpPost"/>
        </protocols>
    </webServices>
    </system.web>
</configuration>
 
Then it worked.

SharePoint 2013 layout folder path

Just realized that SharePoint 2013 now has two folders for _layout virtual directory.
 _layout --> layout/14
_layout/15 --> layout/15

Tuesday, November 27, 2012

BizTalk Mapping - Use XSLT template to split a csv field to repease fields

Recently in a data integration scenario, I need to map a CSV field values into a repeating field.

The source schema field will be look like this,
<TestData>
     123, A, 23, B, 45, FF, 67, SD, 78, DE,,,
</TestData>
The value of the data is a variable length, also it maybe have some blank values or not.

The destination schema data should be mapped like this,
<Results>
    <Result id="123">A<Result>
    <Result id="23">B</Result>
    <Result id="45">FF</Result>
    <Result id="67">SD</Result>
    ...
</Results>

Because the incoming test data is a variable length csv value, we can not use a table looping and extractor to direct mapping to the destination

The solution I come up is to use a XSLT template with a recursive call.

The solution has a single link to destination Results element to decide if need to create the whole element.

Then the template is linked to the Result element to create each element by keep calling XSLT substring-before(), substring-after() to reduce the string and generate the result.

Also xslt contains() is used to check if the element is the last value. or else substring-before() will return empty string.

Here is the sample codes, we need to run substring-after twice for each round, becasue this scenario is a key-value pair.
 
 <xsl:template name="TokenizeCommaSepString">
    <xsl:param name="stringToTokenize" />
 
    <xsl:if test="$stringToTokenize != ''">

        <xsl:variable name="var:v98" select="substring-before($stringToTokenize, ',')" />
        <xsl:variable name="var:v99" select="substring-after($stringToTokenize,',')" />
       
        <xsl:choose>
            <xsl:when test="contains($var:v99, ',') = 0">              
                <xsl:if test=" $var:v98!='' or $var:v99!='' ">
                    <xsl:element name="Result">
                        <xsl:attribute name="Id">
                            <xsl:value-of select="$var:v99" />
                        </xsl:attribute>
                        <xsl:element name="Value">
                            <xsl:value-of select="$var:v98" />
                        </xsl:element>
                    </xsl:element>
                </xsl:if>
            </xsl:when>
         
            <xsl:otherwise>
                <xsl:variable name="var:v99.2" select = "substring-before($var:v99, ',')" />
                <xsl:if test=" $var:v98!='' or $var:v99.2!='' ">
                    <xsl:element name="Result">
                        <xsl:attribute name="Id">
                            <xsl:value-of select="$var:v99.2" />
                        </xsl:attribute>
                        <xsl:element name="Value">
                            <xsl:value-of select="$var:v98" />
                        </xsl:element>
                    </xsl:element>
                </xsl:if>
            </xsl:otherwise>
        </xsl:choose>

        <xsl:call-template name="TokenizeCommaSepString">
            <xsl:with-param name="stringToTokenize" select="substring-after(substring-after($stringToTokenize,','), ',')" />
        </xsl:call-template>
  </xsl:if>

</xsl:template>


Saturday, November 24, 2012

SharePoint customization content types reference links

During customization in SharePoint solution development, it is always be nice to have a reference in hand to know all the field types and re

SharePoint 2010 field types reference
http://koenvosters.wordpress.com/2010/04/27/available-field-types-in-sharepoint-2010/

Tuesday, November 20, 2012

SharePoint 2013 Apps is an opportunity

Now SharePoint 2013 is out. Since the beta version with the new Apps programming model, I have talked to many developers. Like what I first see this, most of them are disappointed. Apps is not something the SharePoint developers really want, it moves to another direction rather than giving us something better and easier for SharePoint server solutions development.

My opionion about this actually has been changed. I think SharePoint team is on the right track and we need to embrace this model. Since SharePoint 2007, all the versions were built on top of asp.net. And in these years, web development has been changed so much because of the the power of javascript library. In MVC4, you have all the good javascript library included in the box to do amazing things that give very good user experience.

Since SharePoint 2013 has a good revamp in their client javascript library, developers finally can do things like the modern web apps can do. So now SharePoint developers have the tools in hand and can work with them in SharePoint 2013. I believe it is time to leave your comfortable zone and start to write your own mordern web apps within SharePoint.

Monday, November 19, 2012

SharePoint 2013 - View data through REST from browser

Now many information can be loaded from browser through REST. This is a quick links list to show what you can expose,

First, In IE, needs to go to Internet Options -> Content tab -> feeds and web slices -> settings
uncheck "turn on feed reading view"

http://spsite/_api/web - list all SharePoint related information
http://spsite/_api/web/lists - all the SharePoint site lists
http://spsite/_api/web/lists/getbytitle('listname') - specific list information
http://spsite/_api/web/lists/getbytitle('listname')/items - show the list data
http://spsite/_api/web/lists/getbytitle('listname')/items(int) - show the list data by id
http://spsite/_api/web/lists/getbytitle('listname')/items(int)?$select=Title,Field1,Field2 - only select the list fields
http://spsite/_api/web/lists/getbytitle('listname')/items?$filter=Title eq 'title'  fitler the data

The reference can be found out in http://www.odata.org -> document -> URL Convention

Here has a very good tutorial about how to do write operation in REST, and how to consume it in JSON data.

SharePoint 2013 - Create JS templates view

SharePoint 2013 has a new feature that you can write custom js codes to render a view rather than xslt view.

Here are the quick steps,

1. Create the custom list and their columns
    In SharePoint 2013, there is list designer that is much easier to create the list content type and columns,
 
2. Create a new view and include the fields you will reference in the java script, those fields can be called by context.CurrentItem.FieldName

3. Add the JSLink to the javascript file, such as
<JSLink Default="TRUE">~site/Scripts/<your custom javascript file>.js</JSLink>

4. Create a new Scripts module and write a custom java script to deploy them, Here is a quick example,


(function () {
    var overrideCtx = {};
    overrideCtx.Templates = {};
    overrideCtx.BaseViewID = 2; // the custom view ID
    overrideCtx.ListTemplateType = 10001; //the template type

    overrideCtx.Templates.Header = "<B><#=ctx.ListTitle#></B><hr><ul>";
    overrideCtx.Templates.Footer = "</ul>";
    overrideCtx.Templates.Item = CustomItem;
    SPClientTemplates.TemplateManager.RegisterTemplateOverrides(overrideCtx);
})();

function CustomItem(context) {
    var ret = "<li>This is a " + context.CurrentItem.Title+ " - " + context.CurrentItem.ISBN + "</li>";
    return ret;
}




Saturday, November 17, 2012

MVC4 Web API Starter needs to know

I have just tried to use the MVC 4 Web API. There are some findings that needs to know during the process,

1. Use cUrl command line tool to test out the rest end points

2. Modify the IIS or IIS Express settings to enable verb PUT, DELETE
This is a link to show how to do this.

3. If need to use web API provided HttpClient class
In package manager console, run:
    Install-Package Microsoft.AspNet.WebApi.Client projectname
to install the necessary libraries


4. This will be a quick example to return the result.

By Calling add MediaTypeWithQualityHeaderValue("application/xml"), a xml format data will be returned. By default, web api return Json format data.

use new System.Net.Http.HttpClient() to send Form data
To use xml format data, need to add the MediaTypeHeader
clt.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/xml"));
To get the result
 var result = clt.GetAsync(new Uri("http://localhost:52094/api/videos")).Result
 
For post complex type data, Call PostAsJsonAsync() such as
clt.PostAsJsonAsync("http://localhost:52094/api/videos/222", customer).Result
 

5. There are some old examples to use HttpRequestMessage and its extension method CreateContent, which are deprecated. it is much easier now.

6. In debug->immediate window, enter GlobalConfiguration object to check the current formatters.
GlobalConfiguration.Configuration.Formatters

Count = 4

[0]: {System.Net.Http.Formatting.JsonMediaTypeFormatter}

[1]: {System.Net.Http.Formatting.XmlMediaTypeFormatter}

[2]: {System.Net.Http.Formatting.FormUrlEncodedMediaTypeFormatter}

[3]: {System.Web.Http.ModelBinding.JQueryMvcFormUrlEncodedFormatter}
 
 


 

Thursday, November 15, 2012

Azure Blob Upload - SocketException

Today when I deployed my MVC 4 application to azure, when I tried to access the blob, I got the following error,

An attempt was made to access a socket in a way forbidden by its access permissions 127.0.0.1:10000

[SocketException (0x271d): An attempt was made to access a socket in a way forbidden by its access permissions 127.0.0.1:10000]
   System.Net.Sockets.Socket.EndConnect(IAsyncResult asyncResult) +6462061
   System.Net.ServicePoint.ConnectSocketInternal(Boolean connectFailure, Socket s4, Socket s6, Socket& socket, IPAddress& address, ConnectSocketState state, IAsyncResult asyncResult, Exception& exception) +271

[WebException: Unable to connect to the remote server]
   Microsoft.WindowsAzure.StorageClient.Tasks.Task`1.get_Result() +77
   Microsoft.WindowsAzure.StorageClient.Tasks.Task`1.ExecuteAndWait() +171
   Microsoft.WindowsAzure.StorageClient.TaskImplHelper.ExecuteImplWithRetry(Func`2 impl, RetryPolicy policy) +29
   Microsoft.WindowsAzure.StorageClient.CloudBlobContainer.CreateIfNotExist(BlobRequestOptions options) +93
   AzurePictures.Models.ImageRepository.SaveImage(String name, Byte[] buffer) +109
   AzurePictures.Controllers.HomeController.Upload() +316


The issue is when I deployed the application, I am still setting it to useDevelopmentStorage = true,
Just reset the web config to use the Azure one, then it worked.

Monday, November 12, 2012

BizTalk 2010 - Create a dynamic flat file disassembler to set the document schema

In this scenario, there are quite a few different flat files in different flat file schema types, they all need to map into a common format schema to be processed in BizTalk.

It is will be too much to create pipeline for each trading party, so I wrote a custom flat file disassember which inherit from the Microsoft one to set the document schema in the disassemble stage.

There is an existing msdn example to show how to create a custom disassember which inheritted from the Flat file disassembler, Extending the Flat File Disassembler Pipeline Component.

In my scenario, I only need to have some custom code in the Disassemble() method.

1. Understand the received file name,
  IBaseMessageContext context = pInMsg.Context;

  object obj = context.Read("ReceivedFileName", "http://schemas.microsoft.com/BizTalk/2003/file-properties");
In this blog, you can find all the common used properties as reference.

2. Set the DocumentSpecName of the pipeline

DocumentSpecName is a type of SchemaWithNone, which need to add reference to Microsoft.BizTalk.Component.Utilities from GAC.

this property can be created by this.DocumentSpecName = new SchemaWithName("schematype, assemblyname, ..."); 

3. Then just call base.Disasseble(pContext, pInMsg)
4. To inherit from Flat file disassember (FFDasmComp class), need to add reference to Microsoft.BizTalk.Pipeline.Components from GAC. For the Pipeline components interface such as IBaseComponent, IDisassemblerComponent,need to add reference to Microsoft.BizTalk.Pipeline 

When add this custom component into the pipeline, the Flat File Disassembler needs the Document schema to be set up. Although you can override the IComponent.Validate() method to pass the validation, however, it will cause error "value can not be null" in the pipeline processing.

Also the flat file disassembler needs to set the "Recoverable Interchange processing" property to true, or else, there is a "datareader disposed" error sometimes.  

Create asp.net MVC 4 supported membership database

In traditional asp.net, you can run aspnet_regsql to create the membership database.

In this one I will explain how to create mvc 4 membership database.

1. In web.config, add the default (localdb) connection

    <add name="DefaultConnection" providerName="System.Data.SqlClient" connectionString="Data Source=(LocalDb)\v11.0;Initial Catalog=dbname;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|\dbname.mdf" />

2. Install the necessary packages reference in NuGet
Install-Package DotNetOpenAuth
Install-Package DotNetOpenAuth.aspnet
Install-Package Microsoft.AspNet.WebPages.OAuth
Install-Package WebGrease
Install-Package WebMatrix.Data
Install-Package WebMatrix.WebData
Add reference to system.web.helpers from nuget packages, make sure copy to local is true

3. Include the codes from an internet application sample
\Models\AccountModels.cs
\Filters\InitializeSimpleMembershipAttribute.cs
\Controller\AccountController.cs
\Views\Shared\_LoginPartial.cshtml
\Views\Account\* (update the namespace)

4. Also in web.config, remove the default membership provider and role provider section.

5. To use OAuth with Facebook, Google, Twitter etc,
Need to include the file \App_Start\AuthConfig.cs to uncomment the provider code with their appid and app seceret.
Also modify the global.asax.cs to add the line of the code,
AuthConfig.RegisterAuth();

Thursday, November 8, 2012

BizTalk pipeline can not access a disposed object error

I got this error related to Flat file disassembler in the eventlog,

There was a failure executing the receive pipeline: "XXX.Pipelines.ReceivePipeline1, XXX.Pipelines, Version=1.0.0.0, Culture=neutral, PublicKeyToken=28bb1f44fbba3ea7" Source: "Flat file disassembler" Receive Port: "Commodities_Recv_Port" URI: "D:\XXX\Tests\XXX_OUT_In\*.*" Reason: Cannot access a disposed object.
Object name: 'DataReader'.

Fix:

In the flat file disassembler componet in the pipeline design, set the property
"Recoverable interchange processing" to true


 

Wednesday, November 7, 2012

Another scenario for this issue that in biztalk administration console, schema referenced by map has been deleted

This issue seems to happen only in BizTalk 2010, maybe onwards.

A few days ago, I had this issue and I blogged the fix here.

Today it has a different scenario.

As the previous blog said, as long as I removed the masp reference in the BizTalkMgmtDb, the warnning message will not show.

However, as long as I deployed the maps project, this issue shows up again in the administration console. And there are no any maps shown in the application even the maps assembly was added in the resource.

This one seems to do with the maps project and schemas project are in seperated solution, also the map project has reference to schemas from GAC. In the end I have to delete the application and redeploy each project (schemas, then maps) one by one and it worked.

Tuesday, November 6, 2012

BizTalk 2013 Beta released and the stuff I am interested

BizTalk 2013 beta is released and you can download it here

In this release, there are some new features I think that worth while to try,

1. Azure service bus support

2. REST service support

3. ESB toolkit is fully integrated and the configuration is much simplified.

4. Dependency tracking - dependencies between artifacts can be viewed in admin console.

The BizTalk 2013 is still based on the previous architecture but it is upgraded to work nicely with all the latest development environment such as visual studio 2012 and SQL server 2012. That is very good thing.

Thursday, November 1, 2012

A link to set up SAP adapter in BizTalk 2010

Just found the link here that explained how to set up SAP adapter in BizTalk 2010

Get the WCF current directory

A wcf service is running and hosted by IIS. I have the requirment to get the current folder of the serivce.  And it will return NULL if use HttpContext.Current.Server.MapPath since wcf context is diffrent from the default asp.net context.

what we can do is using,
System.Web.Hosting.HostingEnvironment.ApplicationPhysicalPath;

Wednesday, October 31, 2012

Issues in BizTalk SSO and ESB management portal for today

Everyday when you working on a project, there are many issues that caused by the environment set up or change to be fixed.

Today I have two issues to record here.

1. The SSO service account password was updated, then when I went to BizTalk administrator, tried to refresh, I am getting the following error,
"
Cannot perform encryption or decryption because the secret is not available from the master secret server
"
Quickly asked Google and found the solution here, And it worked after run the commands,
ssoconfig -restoresecret SSOxxx.bak

2. Need to deploy the ESB management portal to a QA environment. In this environment, it deals with bizTalk server and a seperate SQL server, obviously we are having the double hop issue with delegation, which need to set SPN.

The linked article ESB 2.1 Portal minimal access configuration (Kerberos)
detailed explain the minimum security requirment and set up process for this type of deployment.

Thursday, October 25, 2012

Service Bus UnauthorizedAccessException token provider was unable to provide a security token while accessing custom STS

I installed the service bus for windows server on my windows server 2012. Then I setuped the new service bus farm and followed the tutorial on MSDN to test the brokered message queue client.

However, I am getting the error as below.

This error can not provide a security token for the user I setup run as from sb farm, which username@domain.

After some test, I realized the issue is caused by the run as user has to be given a full userdnsdomain name. So when you set up the service bus farm, make sure it is uisng username@domain.com format.

Then it worked as expected.

Wednesday, October 24, 2012

A good way to gac the assembly since .net 4

Since .net 4.0, an important change is the GAC location is moved to,
C:\Windows\Microsoft.NET\assembly\GAC_MSIL

and the gacutil program is in,
C:\Program Files (x86)\Microsoft SDKs\Windows\v7.0A\Bin

For .net framework 4.5
C:\Program Files (x86)\Microsoft SDKs\Windows\v8.0A\bin\NETFX 4.0 Tools

So in visual studio.net 2010 or later, in the post build event, you can put in the following codes to add them into the right gac location,

@CALL "%VS100COMNTOOLS%vsvars32.bat"
@gacutil -if   $(TargetFileName)

Sunday, October 21, 2012

When tried to refresh in BizTalk admin console, keeps complaining schema referenced map has been deleted, The local, cached version of the BizTalk Server group configuration is out of date. You must refresh the BizTalk Server group configuration before making further changes

Due to some schema namespace change, and don't want to re-do the maps, so I openned the map in XML edit mode and updated the namespace. Then when I tried to deploy the solution, It failed.
And I am getting the error as the title indicated.

There are some missing or isloated maps data in the database to be cleaned.
In the BizTalkMgmtDb database, look up the bt_mapspec table, delete the map entry for the one the administrator console complained.

And referesh, then it worked.

Wednesday, October 17, 2012

Setup sharepoint 2013 preview in hyper-V encountered an error during setup

I was installing the SharePoint 2013 preview in windows 8 hyper-V environment.
Firstly, it looks good, it is running installing until the last 10% bit,




I am keep getting the unexpected error,



Tried all sorts of ways, such as install all latest update,  run set up as administrator, install office. No matter what, it just can not complete the setup.

The magic to fix it is to modify the virtual machine settings and give 4 virtual CPUs, then it worked !

Many small things that nice to know in SharePoint 2010

Variation Label - used for language locale.
http://office.microsoft.com/en-us/sharepoint-server-help/about-variation-labels-HA010120731.aspx

For List columns performance, need to create indexed list column. This article discusses the database behind the indexed column.
http://blog.dynatrace.com/2009/01/28/sharepoint-list-performance-how-list-column-indices-really-work-under-the-hood/

Feature stapling is a good way to associate the feature to a site definition which is in use, such as Team Site. It has stapler and staplee.
http://blogs.msdn.com/b/kunal_mukherjee/archive/2011/01/11/feature-stapling-in-sharepoint-2010.aspx

Monday, October 15, 2012

Tons of SharePoint 2013 new features links

I haven't really looked at SharePoint 2013 recently, suddenly there are a lot good articles and tutorial blogs to talk about it.

This is a blog site which has a good tutorial to create a sharepoint 2013 site master page and page layout.
http:/microsoftstrategy.com/category/sharepoint-2013

This talks about a new SPSecurityEventReceiver
http://maiomardesouki.com/2012/08/28/whats-new-in-sharepoint-2013-event-receivers/

And Sahil Malik talks about jQuery and cross-domain javascript and using Azure ACS with SharePoint,
http://blah.winsmarts.com/2012-1-jQuery_and_Crossdomain.aspx
http://blah.winsmarts.com/2011-12-Integrate_Azure_ACS_with_SharePoint_in_2_minutes_or_less.aspx

How to use SPXMLContentMapProvider to implement consistent navigation in sp2010,
http://blah.winsmarts.com/2008-1-Implementing_Consistent_Navigation_across_Site_Collections.aspx

SharePoint 2013/2010 claims encoding

Just a wiki document clearly explains the sharepoint user ID meaning, such as
i:0#.w|contoso\chris as my reference.

http://social.technet.microsoft.com/wiki/contents/articles/13921.sharepoint-2013-and-sharepoint-2010-claims-encoding.aspx



Friday, October 5, 2012

Add STS reference is missing in vs.net 2012

VS.net 2012 by default included the Windows Identity Framework and its SDK. However, if you try to right-click the project, you won't be able to find the "Add STS reference" in the context menu.

This has been changed in vs.net 2012 and called "Identity & Access" as below,
 
 
To be able to use this, you need to go to Tools -> Extensions and Updates -> Enter "Identity" in search to install the "Identity and Access Tool" first, then restart vs.net 2012.
 
 
 
 
 
 

Thursday, October 4, 2012

WCF Service configuration tool is the best friend

It is a very productive day today. Have to create a new wcf service and published it as basicHttpBinding, because the service is taking a xml data, so the message size is very possibile to execeed the default 8096 bytes limit.

So the wcf service config needs to be set up with the correct settings such as,

<bindings>
    <basicHttpBinding>
        <binding name="basicHttp" allowCookies="true"
                 maxReceivedMessageSize="20000000" 
                 maxBufferSize="20000000"
                 maxBufferPoolSize="20000000">
            <readerQuotas maxDepth="32" 
                 maxArrayLength="200000000"
                 maxStringContentLength="200000000"/>
        </binding>
    </basicHttpBinding>
</bindings>


Also in service, the bindingConfiguration should be used such as,
<services>
      <service name="Example.Services.TestService">
        <endpoint address="" binding="basicHttpBinding" bindingConfiguration="basicHttp" contract="Example.Services.ITestService"/>
      </service>
  </services>


I have done it a few times, so I just copied & pasted from other service settings and modify it to the one for this service name.

But after a few hours testing, I am still keeping get the "message exceeds the size error". Have to carefully check the web.config and no way find any error for the settings.

In the end, I just removed the old web.config, and bring it up the WCFServiceConfiguration tool to browse to the service assmebly and use the tool to create the correct basicHttpBinding.

Then it worked !!!

The lesson I got from it is, we should use the WCF configuration tool to create the correct config file rather than just copy & paste, which is error-prone and easily can miss something and stucked.



Friday, September 28, 2012

Javascript structural pattern

1. Prototype Pattern,

<script type="text/javascript">
    var Calculator = function (id) {
        this.id = id;
    };
    Calculator.prototype = {
        add: function (x, y) {
            var result = x + y;
            $(this.id).html("<br>" + result + "</br>");
        },
       
        multiply: function (x, y) {
            var result = x * y;
            $(this.id).html("<br>" + result + "</br>");
        }
    };

    $(document).ready(function () {
        var c = new Calculator('#a');
        c.add(12, 32);
        c.id = '#b';
        c.multiply(2, 10);
       
    });
</script>

<div id="a"></div>
<div id="b"></div>

Also arguments can be used for variable length of parameters within function to be able to do things like test(a), test(a, b), test(a, b, c) etc...

2. Module Pattern - to hide the private property/method

var Calculator = function(id) {
    //private members
    var id = id;
    //public members
    return {
         add: function (x, y) {
               $(id).html( x+y);
         }
    };
};

Client:
var c = new Calculator('#a');
c.add(3, 5);

3. Revealing Module Pattern
var calculator = function(id) {
       var id = id;
       var doAdd = function (x, y) { $(id).html (x + y);
       return {
             add  : doAdd;
       }
         
}('#a'); //use this to self invoking.

Client:
calculator.add(3, 5);

4. Revealing Prototype Pattern
var Calculator = function (eq) {
    //this. variables.
};

Calculator.prototype = function() {
     // private members
     var doAdd = function (x, y) {return x + y;}
     return {
           add : doAdd;
     };
}();


.Net 4.5 Security Claims

PluralSight has a quite detailed course to explain the changes in Indentity and Access Control in .Net 4.5, by Dominick Baier.

1. In this video, it shows the new change in .net framework security. The most important change is now the GenericIdentity, WindowsIdentity has inherited from the base class as ClaimsIdentity. All the claims can be accessed from the Claims property. The same is happened in Principle as well, which is ClaimsPrincipal.


 
 

2. How do you extend the claims authentication and authorization in .Net 4.5?

ClaimsAuthenticationManager is a base class to extend to transform the incoming ClaimsPrincipal.
It has a override method,
ClaimsPrincipal Authenticate(string resourceName, ClaimsPrincipal incomingPrincipal)

By updating this method, the incomingPrincipal can be transformed to add/update/remove some extra claims. This is especially useful in federated security scenario. When the identity party authenticated the responsiblie party and send the incoming principal. The server can transform it to provide some extra or their own meaning for the claims.

ClaimsAuthorizationManager is a base class to extend claims based authorization.
It provides the method
bool CheckAccess(AuthorizationContext context)

The claims authorization is different from the previou role-based authorization. The role based authorization is a roles string array, to ask if the user is in a role. Claims based authorization has the concept as Action and Resource to ask if the action for the rsource is permitted or not.

So in the AuthorizationContext, it has theree properties. Action, Resource and Principal.
ClaimsPrincipalPermission is an attribute to decorate on the method for authorization.

To use the custom authentication and authorization classes, the classes need to be include in the config file such as,



For the authentication transfor, using the code,

Thread.CurrentPrincipal = FederatedAuthentication.FederationConfiguration.IdentityConfiguration.ClaimsAuthenticationManager.Authenticate("none", incomingPrincipal);

to transform the incoming principal to custom format.

Also for the project, System.IdentityModel, System.IdentityModel.Services are the necessary project references.

Wednesday, September 26, 2012

WCF Version Strategy

Just went through the following code project articles, which detailed explains the WCF version in all possible scenarios.

WCF Backwards compatible & version strategy: Part 1, Part 2, Part 3

In summary, WCF works best try to match the data contract from the client side to the service implementation. They will throw errors for the "Required" data member when they are not presented.
Also there is a concept called "Version round trip" so the new data member can be preserved and then sent back. But the data contract has been inherited from IExtensibleDataObject

For the version strategy, it categories as strict, semi-strict and agile versioning.

The difference between strict and semi-strict is whether the service contract interface_version2 inherit the interface_version or not. If v2 inherit from v1, then it is semi-strict, and if v2 just include the methods from v1, that is strict versioning. Also the basic idea is the service contract implementation should always implement the interface v1 and v2.

Also there is a blog talking about the general WCF version guidelines

Wednesday, September 12, 2012

SingleWsdl in framework 4.5



Check the diagram above, after I built the service in .net 4.5 and browsing the svc, now there is a new option to return all schemas in one single wsdl, which I blogged before.

This is exetremely useful for BizTalk published service scenario. BizTalk solution usually defines many schemas for each operation in the service, and it is quite hard to distribute the wsdl files to another team to use it. Now it is much easier!

ServiceBus relay service with hosting in IIS

Nowadays in most of the cases, custom developed wcf services are hosted in IIS with windows appfabric, which still based on WAS. So if the services are blocked by firewall and needed to be used by 3rd party, ServiceBus relay service will be a good solution for it.

However, for the services always have to open an outbound port and create a bidirectional socket for communication, which connect to the Service Bus, authentication and listening messages before the client sends request. And for IIS hosting, they only start service when the first request comes through.
This is actually a difficulty, and well explained here.

I just followed the tutorial here and used windows appfabric to enabled the auto-start feature, then it worked.

Thursday, September 6, 2012

Update: signalR-0.5.3 and mvc4 worked

I want to try out the signalR library in mvc 4, so pretty much I follow the basic tutorial to have the basic "chat" program. First,  I run Install-Package "signalR" to install the packages in to the project.
After quickly get the codes there, and hit F5. Oops, it doesn't work. Then here is long hours google and try but I just have no luck. Browsing to "/signalr/hubs" just always gives me the 404 error.

Just an experiment, I recreated a mvc 3 project and running the same codes. This time, browse to "/signalr/hubs" actually returns me the proxy javascript. But I still have javascript error when I tried to send the message (strat to chat). However, If I use an old version (0.3.4), it all WORKS prefectly. The version I get from the msdn sample in here.

Update: Just saw on 11 Sep, there is a new update from Nuget. So I installed it to my MVC4 project.
But specifically in the package manage console, I am running,
install-package signalR -version 0.5.3 <projectname>

Then it all worked. only still in the _layout file,
I am using
<script src="@url.Content("~/scripts/jquery.signalr-0.5.3.min.js") type="text/javascript"></script>
rather than
mvc4 bundle javascript, @Scripts.Render(...)

Next, we can explore how to use signalR within BizTalk to be able to update the client the service/task progress.




Tuesday, September 4, 2012

Jquery file upload in ajax

Recently need to upload pictures to server side, and it should be in ajax way with a progress bar.
The default $.ajax doesn't support form data posted. So here is the jQuery Form Plugin to rescue.
And there is a blog example to use it within asp.net mvc.
Update: just find another blog with links to 7 javascript ajax upload library

Wednesday, August 29, 2012

asp.net MVC4 - $.getJSON with controller and knockout

In this scenario, I am trying to call a backend controller to load the data from backend.
Then the data will be returned as a JSON data to web and mapping back to a knockout view model for binding. And the knockout binding section should be shown by jquery ui dialog and update back to controller for saving.

Here are the listed issues that I got,

- In controller, return Json(data, JsonRequestBehavior.AllowGet), or else $.getJSON call back function won't be triggered if you use get.

- In controller, use new JavaScriptSerializer().Seralize(Model) to return a JSON string representation of data. The string will be used for knockout to load to viewModel

- knockout mapping is a plug-in for automatically mapping the data from JSON to view model. it can be downloaded here.

- Use the following code to create the viewmodel and applybinding
var koModel = ko.mapping.fromJSON(data);
ko.applyBindings(koModel);


Tuesday, August 28, 2012

asp.net mvc 4 - webgrid add it as reference and use javascript in it

1. To use @Html.WebGrid in the razor view page by default it won't be loaded.
The webgrid is in System.Web.Helper, and it needs to be added in web.config like below in system.web section,

< compilation debug="true" targetFramework="4.5">
<assemblies>
<add assembly="System.Web.Helpers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
</assemblies>
</compilation>


2. By default, you can use format: (item) => item.GetSelectLink()) to add a select link for each row.

However, I want to add a javascript function to pass an itemId, then open a jquery ui dialog to load the values and save it by Json format.

You can use HtmlString to override it, format: (item) => new HtmlString("<a href=# onclick=...")

A cleaner way will be create a htmlHelperExtension to return the html string, such as,

    public static class HtmlExtension
    {
        public static IHtmlString Link(this HtmlHelper htmlHelper, Post item)
        {
            var anchor = new TagBuilder("a");
            anchor.AddCssClass("sel");
            anchor.Attributes["src"] = "#";
            anchor.Attributes["onclick"] = string.Format("select({0});", item.Id);
            anchor.SetInnerText("select");
            return new HtmlString(anchor.ToString());
        }
    }

Then in the razor view page, it will become format:(item) => Html.Link((Post)item.Value)
The namespace for the HtmlExtension should be declared, and remember to pass item.Value.

Wednesday, August 22, 2012

SharePoint branding 2010 - reference links

http://bniaulin.wordpress.com/2012/06/27/my-sharepoint-branding-series-on-nothingbutsharepoint/

https://www.nothingbutsharepoint.com/sites/eusp/Pages/Brand-SharePoint-SharePoint-Home-Page-CSS-Reference.aspx

https://www.nothingbutsharepoint.com/sites/eusp/Pages/SharePoint-Farmer-Joes-Team-Site-Put-that-in-your-Content-Editor.aspx

http://sharepointexperience.com/csschart/csschart.html

SharePoint 2013 Social - Community members are not as expected

So after installed SharePoint 2013 preview, I can not wait to create a community site right away to check it out.

The Community Members on the menu is a bit confusing though. I think that should be used to manage the members for the site by category. However, it is not what I thought.

From Microsoft, it is only a list which keeps a record of ongoing activity by members and reputation they accrue. It still should use site permission functions to add users as site members.

User Profile Service in SharePoint 2010

Just tried the user profile service in SharePoint 2010, this is the basic to build the my site as community site. Here is the complete guide to setup all the farm account and permissions. In my dev environment, everything is installed in the same virtual machine, basically the first and the most important step is to start the User Profile Synchronization Service, which is in stopped state by default installation.

Go to Central Admin -> system settings -> Managed Service on Server,

The User Profile synchronizaiton service should be disabled, click on start to start the service. And it will provision FIM services and after a long time wait (5-10mins),  you will be able to use configure synchronization connections to configure AD connection and start importing user profiles.

Hopefully later on we can continue to see how the UPS and the new community site in SharePoint 2013.
In 2013, there is another ADImport mode which only imports from active directory. You can switch between Adimport mode and UPS synchronization mode. Also you don't need the User profile synchronization service to manage the synchronization. It is moved to user profile service.

Sunday, August 19, 2012

A very clean article to discuss when to use RenderAction or RenderPartial in MVC3

This post is the best one so far to explain when to use RenderAction and when to use RenderPartial.

RenderAction basically can be a good place holder for some static contents that can be defined in _layout page. However, if the content is driven by main view content, it will be better define it in section area. There is a good tutorial by ScottGu.
Also in the view if you want to get the current action and controller, you can get it from ViewContext.RouteData.Values["controller" or "action"]