Monday, December 23, 2013

Rebind AngularJS in ajax call

Just a quick tip when I am trying to working on the angular with jquery ajax.

After the data is assigned in an ajax call back function, angular won't be able to monitor change,
in this case, $scope.$apply() will be needed to reflect data binding.

Thursday, December 19, 2013

SharePoint 2013 TypeLoadException Error when set up BDC

If you set up the BDC model and you may get an error in ULS log as below,


The Type name for the Secure Store provider is not valid. ---> System.TypeLoadException: Could not load type 'Secure Store Service' from assembly 'Microsoft.SharePoint, Version=15.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c'. 
InnerException 1: System.TypeLoadException: Could not load type 'Secure Store Service' from assembly 'Microsoft.SharePoint, Version=15.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c'.   


The reason is that in the BDC service application, its external system instance not set up correctly for the property "secure store implementation", when the instance is created it is blank, not like SharePoint 2010 the value is pre-populated, so naturally by the name definition, I put in the secure store service proxy name such as "Secure Store Provider".

This is wrong, what we should put is the type name as below,
Microsoft.Office.SecureStoreService.Server.SecureStoreProvider, Microsoft.Office.SecureStoreService, Version=15.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c

Then it worked.

Monday, October 14, 2013

Good Links for Entity Framework Code first design and relationsahip association

Just read the next two blogs which are really useful in design domain driven model with EF code first, and worth noting here as reference in my daily dev work life.

This msdn series article discussed how to build a real model in DDD and the pitfalls in a traditional database mapping view.
http://msdn.microsoft.com/en-us/magazine/dn451438.aspx

This blog has clearly explained the relationships in using entity framwork code first.
http://weblogs.asp.net/manavi/archive/tags/C_2300_/default.aspx

Wednesday, October 2, 2013

Using external list to building screens for users to CRUD and adding search filters

When the external content type is created, the filters can be added in the read list operation. If you create a site page and add the Business Data List web part, the filters will be shown automatically for users to be able to search. However, the search functions created are really hard to use. The below article show a step by step guide to build a custom filter screen on top of the list web part, which can be customized and easier to use.

http://arsalkhatri.wordpress.com/2012/01/07/external-list-with-bcs-search-filters-finders/

Also many times users will want to be able to just press enter to be able to search, so I added the key press event for the button as well,

  var body = document.getElementsByTagName('body')[0];
  body.onkeydown = function (e) {
        if (window.event.keyCode === 13) { 
ApplySearchFilters();
        }
  }

And when I tried to add the wild search for a field which is not null in database, do not use Ignore filter if Value is Null. Instead, just check the Custom value radio button, it will work.

For all other fields with nullable fields, Null is fine.






Thursday, September 26, 2013

SharePoint slow to start up after application pool recycled

After deploy solution through visual studio the application pool will be recycled.
Then it is painful slow to start the first page.

There are a few articles talking about this,
http://blog.muhimbi.com/2009/04/new-approach-to-solve-sharepoints.html
http://ddkonline.blogspot.com.au/2010/05/fix-sharepoint-very-slow-to-start-after.html

I just execute the vb script below as the article discussed to add the registry settings, without reboot the server, and it worked much faster.

const HKEY_USERS = &H80000003
strComputer = "."
Set objReg=GetObject("winmgmts:{impersonationLevel=impersonate}!\\" & strComputer & "\root\default:StdRegProv")
strKeyPath = ""
objReg.EnumKey HKEY_USERS, strKeyPath, arrSubKeys
strKeyPath = "\Software\Microsoft\Windows\CurrentVersion\WinTrust\Trust Providers\Software Publishing"
For Each subkey In arrSubKeys    
objReg.SetDWORDValue HKEY_USERS, subkey & strKeyPath, "State", 146944
Next


How to use SharePoint workflow 2013 if this is not fixed.

I have been checking out the SharePoint workflow 2013, which gave many exciting new features and I am all up to try it in demo. Then I found this article here. It said if you develop a workflow in Visual studio 2012 and deploy it, then any later changes for the workflow will not get updated in the SharePoint. It seems that you can only develop the workflow once and if it is wrong, you can not update it, you need to start again for a new one. WTF.

https://connect.microsoft.com/VisualStudio/feedback/details/779905/sharepoint-2013-workflow-deployment-doenst-update-workflow-definition

Luckily, there is a fix as the workaround tab mentioned from the link above.
A vssphost5.exe process needs to be terminated before deploy.

And this link,
http://social.msdn.microsoft.com/Forums/sharepoint/en-US/8420797e-cb85-4949-9e0e-5060a9060c10/how-to-update-copy-of-sharepoint-2013-azure-workflow

And the official known workflow issues article is a must read.
http://office.microsoft.com/en-us/help/sharepoint-server-2013-known-issues-HA102919021.aspx#_SharePoint_Designer

Crate custom task form in SharePoint 2013 workflow

With the SharePoint 2013 workflow, the InfoPath based form is not used for task forms, instead custom aspx page will need to be created. This is actually a good move to give developers back the flexibility to extend it more.

The blow is so far the best article to teach how to do it.

http://sp2013.pro/2013/03/creating-spd-2013-workflows-part-23-implementing-custom-asp-net-task-form/#more-124

Wednesday, July 10, 2013

SharePoint 2013 and IE 10 work together

I access the SharePoint 2013 sites using IE 10, then if I tried to go to Site Settings page, I got this error,

An error has occurred with the data fetch. Please refresh the page and retry.

F12 to open the developer tools I can see it is a SCRIPT5: Access is denied error.

There are a few options to look at,

1. Check IE10 browser compatibility
Hold ALT-T, and go to Compatibility view settings to set up the SharePoint site.

2. Disable Tracking Protection

3. Add the site to the trusted sites from internet options

Monday, June 10, 2013

Correctly add the javascript intellisense for SharePoint 2013 for Visual studio 2012

In visual studio 2012, it is quite easy to add a javascript intellisense.

Add a scripts folder and in the folder add an _reference.js file to reference the javascripts.
Such as,
/// <reference path="/LAYOUTS/My_custom_package/jquery-1.10.1.js" />
For adding the SharePoint 2013 client javascript library, the below codes are needed.
/// <reference name="MicrosoftAjax.js" />
/// <reference path="~/_layouts/15/init.js" />
/// <reference path="~/_layouts/15/SP.js" />
/// <reference path="~/_layouts/15/SP.Runtime.js" />
/// <reference path="~/_layouts/15/SP.UI.Dialog.js" />
/// <reference path="~/_layouts/15/SP.Core.js" />
 

 

Saturday, June 8, 2013

Sharepoint 2013 Search Experience

It is generally good experience in SharePoint search. However there are a few issues needs to wait maybe until the service pack out.

1. The search result web part is not able to return custom managed property, it seems to be an existing bug that any extra managed property can not return the data even it is shown on REST.
http://social.msdn.microsoft.com/Forums/en-US/sharepointsearch/thread/f53c87d0-af81-445c-8338-1bfea6ca780e

2. Event the document id feature is activated, the docId managed property is only returning integer even after a full crawl. A second managed property has to be created to point to the previous crawl property as ows__l_docId, then it works.

3. For the content search web part, there are limitation to allow five managed properties in the design template, and the paging has no page numbers.

4. When the search crawling is stuck in "Full Crawling" status, reboot worked.

And some references regarding to search,
http://social.technet.microsoft.com/Forums/en-US/sharepointsearch/thread/3878d445-9772-4852-aea2-4f35d072b60e


SharePoint Load ClientContext

This how to load ClientContext

var clientContext;
var website;

SP.SOD.executeFunc('sp.js', 'SP.ClientContext', sharePointReady);

// Create an instance of the current context.
function sharePointReady() {
    clientContext = SP.ClientContext.get_current();
    website = clientContext.get_web();

    clientContext.load(website);

    clientContext.executeQueryAsync(onRequestSucceeded, onRequestFailed);
}

function onRequestSucceeded() {
    alert(website.get_url());
alert(g_wsaSiteTemplateId );
}
function onRequestFailed(sender, args) {
    alert('Error: ' + args.get_message());
}

SharePoint Search master page

Recently worked on the custom master page, and the master page should be applied in the search site collection as well, then here is the tricky things.

In the search site collection page, the default.aspx page has style sheet that disable the ribbon div.
And in the results.aspx page, the titlerow is also made invisible, and the logo is moved below.

g_wsaSiteTemplateId variable is available to know the base template of the site.

So to make it be consistent with the original master page, javascirpt code can used to manually make those div blocks enabled.

_spBodyOnLoadFunctionNames.push("start");
function start(){...}

or include jquery such as,
if (g_wsaSiteTemplateId.substring(0, 4) == "SRCH")
{
//set the div back to visible
                $('#s4-ribbonrow').css({'display':'block', 'height':'30px'});
                $('#s4-titlerow').attr('style', 'display: block !important;');              
                $('#searchIcon').css({'display':'none' , 'height':'0px'});
}







Thursday, May 23, 2013

Get the Site Content Type ID and feature ID in powershell

Sometimes the site content type ID is needed for development.
Go to Site Settings -> Site Content Type -> Content Type,
The content type ID is in the URL.

In Powershell, the following scripts are useful for the content types enumeration,
$sitecollection = Get-SPSite http://localhost
$sitecollection.RootWeb.ContentTypes include all the site content types

To get the specific content type by its ID
$c = $sitecollection.RootWeb.ContentTypes | where {$_.Id -eq "0x....."}

Also if create the custom content type page in visual studio, the elements.xml need to specify the PublishingAssociatedContentType such as,
<Property Name="PublishingAssociatedContentType" Value=";#Custom Article;#0x010100C568DB52D9D0A14D9.....;#" />

To list all the features
$site.Features to list all the site collection features.
$site.Features["GUID"] to get the specific feature

Also Get-SPFeature
Get-SPFeature -site http://site | where {$_.DisplayName -eq "..." }

There is a very useful tip to list the object properties
ps_object | Get-Member







 

Add user as term store administrators from powershell

To be able to import the data into the term store, the user has to have the permission to do it, which is set in the "Managed metadata web service" service application.

Also it can be easily done in power shell as such,

$taxonomySession = Get-SPTaxonomySession -Site "http://localhost"
$termStore = $taxonomySession.TermStores["Managed Metadata Web Service Proxy"]

$termStore.AddTermStoreAdministrator("administrator")
$termStore.CommitAll()

Wednesday, May 22, 2013

Powershell script to read CSV file and XML

Working in SharePoint means a lot opportunity to use powershell. There is a specific powershell function very useful.

Import-csv $csvFilePath

This function reads the csv file and the first line will be the header line to create properties for each row.

For eg, if there is a csv file as

Name, Site, Url
aa,site a, http://sitea
bb,site b, http://siteb

After call Import-csv will load the data as a collection,
$data = Import-csv $csvfile

You can enumerate each row or filter them.
$data | foreach { $_. Name }
$data | where {$_.Name -eq "aa"}

And another convenient way to read data as xml format is just,
[xml] $xmldoc = Get-Content "xmldata.xml'

Sometimes if there is an error message such as "Cannot convert value "System.Object[]" to type "System.Xml.XmlDocument", it is usually because of the mal-formatted XML.

Everyday common SharePoint development issue and timps

Now I am back to start some SharePoint 2013 development work. Then there are some issues and useful links that I need every day. I write them down here in case later I need it again.

1. Deployment solution from visual studio and have this error,
"recycle iis application pool' :object reference not set to an instance of an object".
Just close visual studio and start again, then it worked.

2. Search in ShaePoint 2013 is a great function and their search API in REST is very useful,
http://blogs.msdn.com/b/nadeemis/archive/2012/08/24/sharepoint-2013-search-rest-api.aspx

The search address is in http://server/_api/search/query/?querytext='...'&selectproperties=''&startrow=..&rowlimit=..

3. Remove a web part from a page,
Sometimes the web part is not functionall as expected and needs to be disconnected from the page then enter the http://server/page_address?contents=1

4. Force reinstall fetaure in visual studio
Sometimes I am getting this error in deployment,
"Error occurred in deployment step 'Add Solution': A feature with ID xxxx-xxx-xxx-xxx has already been installed in this farm"
Need to set the AlwaysForceInstall = "True".
By the way, ImageUrl can be added to show a different feature image.

5. How to find the list template ID
Go to Site Contents -> Create list -> then right click on the page to get the url, the template ID is there.
Also a similar way can be used to get the associated content type ID.



Wednesday, May 15, 2013

Add a sign in as different user in SharePoint 2013

By default, the "Sign-in as different user" option is removed in the site. And this is a very useful function for development and testing purpose.

In the folder,
C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\15\TEMPLATE\CONTROLTEMPLATES

Edit the Welcome.ascx page to add the following link,
         <SharePoint:MenuItemTemplate runat="server" ID="ID_LoginAsDifferentUser"
                 Text="<%$Resources:wss,personalactions_loginasdifferentuser%>"
                 Description="<%$Resources:wss,personalactions_loginasdifferentuserdescription%>"
                 MenuGroupId="100"
                 Sequence="100"
                 UseShortId="true"
                 />
Done :)

Wednesday, January 30, 2013

Example for BizTalk 2013 to use the SB-Messaging and WCF-NetTcpRelay adapter

The BizTalk 2013 provides some new adapters for service bus to be able to use relay service and send/receive message to service bus queue and topics.

Recently Paolo Salvatori has upload an example demonstrate all of those features in here

I have set it up and tried it with one issue when calling netTcpRelay service in the demo client.

The demo client is using an app.config to call the netTcpRelayService. However, I have the error said, "The element 'bindings' has invalid child element 'netTcpRelayBinding'.

This because an extensions section needs to be added for the client to be able to recognize those element.

The client finally worked after the following config added.

<extensions>
    <behaviorExtensions>

<add name="transportClientEndpointBehavior" type="Microsoft.ServiceBus.Configuration.TransportClientEndpointBehaviorElement, Microsoft.ServiceBus, Version=1.8.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />

</behaviorExtensions>

<bindingExtensions>

<add name="netTcpRelayBinding" type="Microsoft.ServiceBus.Configuration.NetTcpRelayBindingCollectionElement, Microsoft.ServiceBus, Version=1.8.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />

</bindingExtensions>

</extensions>

This article here has a complete list for all the extensions that can be added. Just be aware that it is using 1.7.0.0, whereas the latest is 1.8.0.0 now.

Monday, January 21, 2013

SharePoint 2013 Search - Build Query for the specified List only

Just tried with the SharePoint search and their refinement.

1. A custom movie list with the necessary columns has been created.
    The new column will be created as crawl property as ows_columnname
    To used them in the search refinement, the managed property needs to be created and mapped back to the crawl property, also make sure the refinable attribute is set true.

2. A custom search page is created in the pages library.

3. Go to the Site Search Settings (not site collection search settings) to add the new created page in search navigation

4. Go to the created page and edit the web part. On the left, the refiner can be modified as required.

5. The query in search result webpart needs to be updated to query the list only.
Here is the issue I have to get the query correct. It seems to be natural to use the Path contains the ListName. However, that would not work. Path has to include the complete list path.


 
 



The below is what the final search page look like.
 

Saturday, January 19, 2013

SharePoint View BCD List get the error "Login failed for user "NT AUTHORITY\ANONYMOUS LOGON"

The reason is the BDC is created from SharePoint designer and the authentication mode is set to "Connect with user's identity"

If enable the BDC with RevertToSelf to true, then the authentication mode can be set to "BDC identity"

Run the following PS command to set the BDC RevertToSelfAllowed to true.

$bdc = Get-SPServiceApplication | where { $_ -match "Business Data Connectivity Service" }
$bdc.RevertToSelfAllowed =$true
$bdc.Update()



Install SharePoint 2013 workflow Issue - Unable to load one or more of the requested types, Retrieve the LoaderExceptions property for more information.

To be able to use SharePoint workflow 2013, I have configured workflow manager 1.0 successfully.
as http://www.aboutworkflows.com/2012/07/sharepoint-2013-install-sharepoint-2013.html

Then run this command in SharePoint PowerShell,
Register-SPWorkflowService -SPSite http://SERVERNAME -WorkflowHostUri http://SERVERNAME:12291 -AllowOAuthHttp

I got the following error,
Unable to load one or more of the requested types.
 Retrieve the LoaderExceptions property for more information.
At line:1 char:1
+ Register-SPWorkflowService –SPSite "http://mysharepointserver" –WorkflowHostUri "h
ttp:/ ...


The reason is because of the SharePoint Developer Tools for visual studio 2012 preview is also installed.

- Uninstall the sharepoint developer tools for visual studio 2012 preview
- Restart Server
- Run the powershell command again then it worked.
- Also a new office developer tools for visual studio 2012 preview 2 has been released, so I just installed that from web platform installer.

Friday, January 4, 2013

Are there three or four?

This picture really represents the issues we have in the work every day.

Update: I have been thinking what we can do if the thing has been like this. I don't really have a solution as it can be easily said that it is 3.5.
 - At lease, the people can swap their position to understand how the other people look at it
 - Maybe based on how to make the benefits maximum to just decide which can bring the best result.

I am welcome to know any solution you think.

Thursday, January 3, 2013

How to start to use Twitter bootstrap

Recenlty I start to use twitter bootstrap for styling of a small web site. It is very important to go through the web site tutorials and understand each class and what they are. This will make your life much easier and do it right.

Also be careful not to put too much class in the HTML directly. There is an article talking about how to use less mixins to structure your own style better.

Wednesday, January 2, 2013

Example to use ajax post in MVC 4

Since MVC4, it is recommended using jquery and unobtrusive javascript to post form. Here is a quick example to do it in a view to use $.ajax and $.post

   1:   
   2:  <h3>Form 1:</h3>
   3:  @using (Html.BeginForm("Login", "Account", FormMethod.Post, new { Id="form1"}))
   4:  {
   5:      <input type="text" id="text1" name="text1" /><br />
   6:      <input type="text" id="text2" name="text2" /><br />
   7:      <input type="submit" value="submit" id="form1submit" />
   8:  }
   9:   
  10:  <h3>Form 2:</h3>
  11:  @using (Html.BeginForm("About", "Home", FormMethod.Post, new { Id = "form2" }))
  12:  {
  13:      <input type="text" id="txtName" name="txtName" value="abc" /><br />
  14:      <input type="submit" value="submit" id="form2submit" />
  15:  }
  16:   
  17:  @section scripts{
  18:      <script type="text/javascript">
  19:          $(function () {
  20:              $('#form1submit').click(function () {
  21:                  $.ajax({
  22:                      url: '/Home/About',
  23:                      type: 'POST',
  24:                      data: $('#form1').serialize(),
  25:                      success: function (data) {
  26:                          alert(data);
  27:                      }
  28:                  });
  29:   
  30:                  return false;
  31:              });
  32:   
  33:              $('#form2submit').click(function () {
  34:                  var action = $('#form2').attr('action');                
  35:                  $.post(action, $('#form2').serialize(), function (data) { alert(data); });
  36:                  return false;
  37:              });
  38:   
  39:          });
  40:          
  41:      </script>
  42:  }

Tuesday, January 1, 2013

Cool features with CSS3

In this post, it will keep updated to have all the features in CSS3 that I think very useful.

1. Multiple Background Pictures,
#div {
    background-image: url(bg1.gif), url(bg2.gif)
}

Entity Framework One-to-One Relationship Association

In this scenario, Author has many books (1 to m). And the Author has the latest Book (1:1) as well.

Using the link as a reference, here is how I come up with the model and association.

Model:

public class Author
    {
        public int AuthorId { get; set; }
        public string Name { get; set; }
        public int LatestBookId { get; set; }
        public Book LatestBook { get; set; }
        public List<Book> Books { get; set; }
    }
    public class Book
    {
        public int BookId { get; set; }
        public string BookName { get; set; }
        public int AuthorId { get; set; }
        public Author Author { get; set; }
    }

DbContext to set up the relationship using Fluent API

    public class EntityMappingContext : DbContext
    {
        public DbSet<Author> Authors { get; set; }
        public DbSet<Book> Books { get; set; }
        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            base.OnModelCreating(modelBuilder);

            modelBuilder.Entity<Author>()
                        .HasRequired(a => a.LatestBook)
                        .WithMany()
                        .HasForeignKey(u => u.LatestBookId);
            modelBuilder.Entity<Book>()
                        .HasRequired(a => a.Author)
                        .WithMany()
                        .HasForeignKey(u => u.AuthorId).WillCascadeOnDelete(false);
        }
    }