Category: Developer


Document ready in SharePoint

Last time, my team has worked with javascript on SharePoint page

There are a inject javascript on the page with a Script editor webpart. We did a try to run a function after page load with a common jquery fuction

$(document).ready()

As our expect, code included inside $( document ).ready() will run once the page Document Object Model (DOM) is ready for JavaScript code to execute. More detail about this function you can find more at http://learn.jquery.com/using-jquery-core/document-ready/

But our problem is the code was not execute as normal. So we work around on this

$(document).ready(function() {

setTimeout(function(){ execute code here},3000);

});

It works but it was not a good solution.

After research, I cannot remember exactly where, but finally I belive below code is the best solution for this issue.

SP.SOD.executeFunc(‘sp.js’, null, function(){
// Execute code here
})

 

Cheers

Hoang Nhut NGUYEN

Last month, I have worked on a requiremnt with public webiste which using Office 365  SharePoint Online and allow anonymous user submit/add data to a specific list.

As your know, When you enable anonymous access to a Web site, you allow anonymous users (and authenticated users who have not been granted access to the site) to browse the entire Web site, including any list, library, folder within a list or library, list item, or document that inherits its permissions from the Web site.

The issue come from Anonymous cannot submit a Contact Form or a Registration form. That mean, in technically, we can not save information to SharePoint for further requirements.

But happy to know that, there is a customized sandbox solution Wsp365.Anonymous.wsp to allow Administration grant Add/Edit permissions to Anonymous user for any custom list.

You can download the solution here, or codeplex, then upload it to https://yourpublicsite.sharepoint.com/_catalogs/solutions/Forms/AllItems.aspx, Active it.

Back to your list, your will see a new ribbon button.

anonymousaccess

Then you can grant appropriate permission as your expect

anonymousgrantaccess

 

Cheers,

Hoang Nhut NGUYEN

SharePoint menu items and ribbon controls are implemented as objects known as custom actions. Custom actions are defined as elements in Extensible Markup Language (XML) files. In SharePoint 2013, it now easy to add and implement ribbon controls with Visual Studio 2012/2013
For understanding, custom actions with Ribbon follow you able to:

  • Create custom action menu items.
  • Create custom action ribbon controls.
  • Access SharePoint objects from custom actions.

Menu items are custom actions incorporated into the built-in SharePoint user interface. As examples, the Site Actions menu is built from a number of built-in, context-sensitive actions that appear as menu item links. And the Site Settings page includes links that are defined by built-in actions. You can build your own custom actions by creating XML definitions in element files in Visual Studio projects, and you can specify where they appear, such as on the Site Settings menu or on a specific administrative page.

Like menus, the ribbon is context-sensitive and shows appropriate actions to users when users need them. For example, when a user browses to a document library, the ribbon controls for adding new folders and documents are shown. SharePoint includes many ribbon controls, and groups them together into related actions. For example, the New Document, the New Folder, and the Upload Document ribbon controls are grouped together on the ribbon

To create a ribbon item, you can use following step on Visual Studio

  1. Right-click Lab09, click Add and then click New Item.
  2. Click Empty Element.
  3. In the Name textbox, type YOURRIBBON and click Add.
  4. After the wizard, just open Elements.xml and check the XML file. Below XML allow you create button with an icon, when user click on it a javascript code will run

Hope this code wil help you understand how to work with Custom Action, CommandUIDefinitions

<Elements xmlns="http://schemas.microsoft.com/sharepoint/">
 <CustomAction Id="NewUIRibbonControl"
 RegistrationType="List" RegistrationId="101"
 Location="CommandUI.Ribbon">
 <CommandUIExtension>
 <CommandUIDefinitions>
 <CommandUIDefinition Location="Ribbon.Documents.New.Controls._children">
 <Button
 Id="NewUIRibbonControl.YOURRIBBON"
 Alt="Help"
 Sequence="1981"
 Command="showpage"
 Image32by32="/_layouts/..../linktoyourimage.png"
 LabelText="Help Videos"
 TemplateAlias="o1"/>
 </CommandUIDefinition>
 </CommandUIDefinitions>
 <CommandUIHandlers>
 <CommandUIHandler Command="showpage" CommandAction="javascript:window.open('http://google.com');" />
 </CommandUIHandlers>
 </CommandUIExtension>
 </CustomAction>
 </Elements>

Cheers
Hoang Nhut NGUYEN

If you want to run a small job  such as notify, run a path code job, when administrators or power users on sites perform operations such as Create/Delete a site, Microsoft provide  The SPWebEventReceiver class provides methods that you can override to create these event handlers,
which are run in the following scenarios:

  • SiteDeleting. Before a site collection is deleted
  • SiteDeleted. After a site collection is deleted
  • WebDeleting. Before a site is deleted
  • WebDeleted. After a site is deleted
  • WebMoving. Before the Url of a site is changed
  • WebMoved. Before the Url of a site is changed
  • WebAdding. Before a new site is created
  • WebProvisioned. After a new site has been created

In this article, I will show you how to handle Web event receiver for the WebAdding event. This event receiver will use the  ConfigurationManager class to read the appSetting value. Based on the value of this setting, the Web event receiver either allows or disallows the creation of subsites.

  1. In the Solution Explorer window, right-click yoursolution, point to Add and then click New Item.
  2. Click Event Receiver.
  3. In the Name text box, type ControlSubsites, and then click Add. The SharePoint Customization Wizard appears.
  4. In the What type of event receiver do you want? list, click Web Events.
  5. In the Handle the following events checkbox list, check the A site is being provisioned checkbox.
  6. Click Finish.
    Visual Studio adds an event receiver class with stub methods for the event you chose to handle.
  7. Replace the existing code in the WebAdding event handler with the following code
string configuredValue = ConfigurationManager.AppSettings["YouKey"].ToString();
if (configuredValue == "1")
{ 
	properties.ErrorMessage = "Sub webs are not allowed";
	properties.Status = SPEventReceiverStatus.CancelWithError;
	properties.Cancel = true;
	return;
} 
base.WebAdding(properties);

Since we are using ConfigurationManager, dont forget to add the namespage

using System.Configuration;
using System.Web;

Hope it help.
Hoang Nhut NGUYEN

SharePoint provides classes that help you work with Web.config entries for your solution in a robust  and simple way. Whenever your solutions need to add, edit, or retrieve Web.config entries, use these  classes, rather than creating your own approaches for working with Web.config files.
This article, I would like to show you

  • Describe the relationship between Web.config files and SharePoint Web applications in a multi-server  farm environment.
  • Add Web.config entries programmatically by using the SharePoint object model.
  • Retrieve and use Web.config entries in your solution code

Overview

Web.config entries for a SharePoint Web application affect all site collections in that Web application.

Web.config entries need to be propagated to all Web servers in a SharePoint farm. The SharePoint object model does this for you.
A SharePoint Web Application (SPWebApplication) is analogous to a traditional IIS Web site. In fact, when you create a Web application by using the SharePoint Central Administration application, an IIS Web site is automatically created. You can verify that the IIS Web site has been created by looking in IIS Manager, where you can see its structure, Web.config file, and virtual directory mappings. The Web.config file contains the settings required by the SharePoint Web application, just as that file would do for ASP.NET Web sites.

The settings in the Web.config file affect all site collections, sites, and sub-sites in the SharePoint Web application. Therefore, you must be careful when editing Web.config, as changes normally have farreaching implications.

Below code snippet will show you how to work with App setting for add and modify an keyname

void AddAndModifyKeyName(bool status)
{ 
	SPWebApplication webApp = SPWebApplication.Lookup(new Uri("http://SharePoint"));
	try
	{ 
		SPWebConfigModification mySetting = null;
		if (status)
		{ 
			mySetting = new SPWebConfigModification(); 
			mySetting.Path = "configuration/appSettings";
			mySetting.Name = "add [@key='yourkeyname'] [@value='1']";
			mySetting.Sequence = 0;
			mySetting.Owner = "Yourname";
			mySetting.Type = SPWebConfigModification.SPWebConfigModificationType.EnsureChildNode;
			mySetting.Value = "";
			webApp.WebConfigModifications.Add(mySetting);
		} 
		else
		{ 
			foreach (SPWebConfigModification modification in webApp.WebConfigModifications)
			{ 
				if (modification.Owner == "Yourname")
				{ 
					modification.Value = "";
				} 
			} 
		} 
		webApp.Update();
		webApp.Farm.Services.GetValue().ApplyWebConfigModifications();
	} 
	catch
	{ 
	} 
} 

 

Hoang Nhut NGUYEN

 

SharePoint is growing in VietNam, in 1 month, I met 2 CIO and 1 CEO in banking and reseller business domain. They are planning to build up a collaboration platform for their company. A frequently question but important was placed  – “Should we go with SharePoint on-premise or Office 365?”

In this post, I want to focus some limitations of SharePoint Online that I think they’re important to consider before make decisions

1. Storage

iStock_000006910539Small

Microsoft offer 3 packages with differences storage capability

– SharePoint Online for Office 365 Small Business
– SharePoint Online for Office 365 Midsize Business
– SharePoint Online for Office 365 Enterprise, Education, and Government

But in generally, let’s make a simple calculation for 10 users which suitable for these 3 packages

  • Team site storage = 10GB + 0.5GB per user
  • Public web site storage = 5GB
  • OneDrive for Business = 10 x 1TB = 10TB (Microsoft just upgrade OneDrive for business from 25GB to 1TB. And please keep in mind that OneDrive will be used for individual people, that mean you can not share it to any team site)
  • Maximum file size you can upload to SharePoint Online can be configured is 2GB per file.

2. Synchronization

onedrive

OneDrive (SkyDrive old name) can be synced with your desktop version. That mean from your desktop, you can configure to sync your folder with OneDrive as well as a Team Site library. And there are some numbers would be reminded:

  • Can not sync >20,000 items in both SharePoint Online Team Sites + OneDrive
  • Can not sync >5,000 items from SharePoint Onnline Team Sites Library

3. SharePoint Online Site Collection

When you buy a package of SharePoint online as mentioned above, you will get a Site collection with sites/subsites hierarchy. It’s designed numbers of site collection, sites/subsites for your package:

  • Small Business: a single Team Site Collection.
  • Midsize Business plans: limits 20 Team Site Collections.
  • Enterprise, Education, and Government:  limits to 10,000 Team Site Collections.

In all options, just single Public Web Site Collection can be created, 1TB for My sites, 2000 site/subsite per site collection

4. Development Limits

bigstockphoto_Construction_

Sandbox Solutions was designed to allow SharePoint developer can customize/develop on Office365/SharePoint Online. Some important limitation you have to consider when go with online solution

  • No access to file/folder. It mean you can not use IO API commands
  • Only be deployed at a site collection level scope (not farm scope)
  • No access to web.config
  • PDF Documents cannot be opened in the browser
  • Restrictions to access security
  • Cannot overuse system resources
  • Limited Server Object model http://msdn.microsoft.com/en-us/library/gg317460(v=office.14)

5. Connection

20131223091152-scitech87

Most important is the availability and stability of Vietnam connection to Office365.  We have faced with severals of time that we dropped connection by optical cable issues with providers in VietNam. All data will be difficult to reach and very slow connection to download/upload files. If you are decision maker, keep it in mind for the backup connnection solution. Your business in the cloud and make sure it’s always stay in touch.

Hoang Nhut Nguyen
Email: nhutcmos@gmail.com
Skype: hoangnhut.nguyen

SharePoint 2013 – CSOM

Since SharePoint 2010, Microsoft announced Client object model to developer community and it really help to extent SharePoint to many other platform.  SharePoint client object model (CSOM) allow you to manage data in SharePoint such as list data, user profile, ….

In SharePoint 2013, I’m very impressive with CSOM since it support for multiple plat for

  • .NET Framework redistributable assemblies
  • JavaScript library
  • REST/OData endpoints
  • Windows Phone assemblies
  • Silverlight redistributable assemblies

This artile show a code snippet for demo how to get user from a list data

        public static User GetUserFromAssignedToField() 
        { 
            string strUrl="http://" + Environment.MachineName; 
            GetUserFromAssignedToField(strUrl); 
            // create site context 
            ClientContext ctx = new ClientContext(siteUrl); 
            // create web object 
            Web web = ctx.Web; 
            ctx.Load(web); 
            // get Tasks list 
            List list = ctx.Web.Lists.GetByTitle("MyList"); 
            ctx.Load(list); 
            // get list item using Id e.g. updating first item in the list 
            ListItem targetListItem = list.GetItemById(1); 
            // Load only the assigned to field from the list item 
            ctx.Load(targetListItem, 
                             item => item["AssignedTo"]); 
            ctx.ExecuteQuery(); 
            // create and cast the FieldUserValue from the value 
            FieldUserValue[] fuv = (FieldUserValue[])targetListItem["AssignedTo"]; 
            User user = null; 
            for (int i = 0; i < fuv.Length; i++) 
            { 
                Console.WriteLine("Retrieved user Id is: {0}", fuv[i].LookupId); 
                Console.WriteLine("Retrieved login name is: {0}", fuv[i].LookupValue); 
                user = ctx.Web.EnsureUser(fuv[i].LookupValue); 
                ctx.Load(user); 
                ctx.ExecuteQuery(); 
            } 
            return user; 
        } 

For more detail about CSOM: You can find at on MSDN http://msdn.microsoft.com/en-us/library/office/fp179912(v=office.15).aspx

Hoang Nhut NGUYEN

One month ago, I get a requirement from customer, they need receive email and stored to corresponding document library to SharePoint intranet. Then I thought about incoming email configuration and tried to set it up.

I found an article from Microsoft about step by step guideline to enable incoming email and sync out email to SharePoint with a dedicated email account http://technet.microsoft.com/en-us/library/cc287879(v=office.14).aspx

But when I go throught this articles, I recognized that it’s not easy as I guess and require that you need a power domain permission to implement some steps such as Setup SMTP Server and connect Directory Management Service….

Actually, I got 2 times at least about the question “How can I sync my email to SharePoint library?” from my buddy and colleagues. So I would like write an addins for Microsoft Outlook 2010 to adapt with the customer requirement and share this setup package + source code so that some body find and may be helpfull for you.

The setup package allow install a new tab in Oulook ribbon to configure and sycn selected email to SharePoint 2010 server document library

Before install this add-ins, you need 2 SharePoint list.

– 1 Document Library to store all the Microsoft original basically message files (*.msg). In this article, I named it as “Email Library” so that all selected email from Outlook will be synced to SharePoint and stored in this document library.

– 1 Custom list (which I named “ReviewEmail” in this post), this library was hard coded some neccessary columns with corresponding data type as below

0.ReviewEmailList

  • Subject: Use to stored email subject. This is Multiple line of plain text field, it shouldn’t be single line of text because email subject can be longer than 225 characters
  • ReceiveDate: Date and Time
  • SentDate: Date and Time
  • FromEmail: Single line of text, used to store from email address
  • ToEmail: Since “To Email” may have multiple email addresses, so that I set it to multiple line of plain text field
  • EmailContent: Enhanced rich text (Rich text with pictures, tables, and hyperlinks)
  • FileUrl: Hyperlink. You can download original msg file from here.

1. Run the setup Outlook synchronize to Sharepoint add-ins wizard

0.1 Setup

2. After setup completed, you will see a new Ribbon tab from your outlook and allow you setup SharePoint connection

1.Configure

3. Setup synchronization SharePoint connection from Outlook

You will be asked for

  • SharePoint site url to corresponding SharePoint site/subsite where Email library and Review Email library belongs to
  • Username and Password to login SharePoint server
  • Email library: the library mentioned above
  • Review Email List: the custom list mentioned above to review email data.

2.SetupInfo

  • Then Click Connect button, it will try to connect and save your configuration data for next use.

2.1.SetupSuccess

4. Select with emails you to to sync to SharePoint and click Sync to Server ribbon button, in functionality, the add-ins will read your selected message to save to “Review Email” custom list and upload msg files to “Email Library

3.SelectMutipleEmail - And - SyncToServer

It will show you a simple text if successful, otherwise, an error message will be showed up.

4.SyncSuccess

5. Verify result

  • Selected email were uploaded to Email Library and named with a GUID

5.EmailLibrarySuccess

  • Message’s data was extracted to ReviewEmail custom list with a hyperlink to download msg file

6.ReviewEmailSuccess

See detail of Email was synced to SharePoint from Microsoft Outlook

7.ReviewEmailDetail

I have uploaded setup file and sourcecode to my dirve.

– Installation package https://drive.google.com/file/d/0B55FfAMp1BXddmp2b2NHSC1WdU0

– Source code https://drive.google.com/file/d/0B55FfAMp1BXdVGg0RjEtZnRON1U

Enjoy and hope it help.

Hoang Nhut Nguyen
Email: nhutcmos@gmail.com
Skype: hoangnhut.nguyen

As a SharePoint developer, almost of time you will work with SharePoint object model. Some time you realize that your customize solution make SharePoint performance slow down. It is very important time to think about memory

it is very important to consider for the memory used by your code via these SharePoint objects which was implemented IDisposable interface. It means these types of objects must be disposed right after finish you request for accessing data as soon as possible.

From 2009, Microsoft introduced some guidelines for coding and working with SharePoint object module and SPDisposeCheck is a great utility for checking the disposal patterns for your SharePoint solution, it’s also a helpful utility when you need to review a large of source code from your team.

The latest version of SPDisposeCheck tool has support as Add-in for Visual studio 2008/2010. So you can run SPDisposeCheck when building your Visual Studio project.

You can visit here to get for latest version: http://archive.msdn.microsoft.com/SPDisposeCheck

You can check Roger Lamb’s blog for SPDisposeCheck development team http://blogs.msdn.com/b/rogerla/

There are also couple of White Papers by Scott Harris’s on MSDN for more details:
Best Practices: Using Disposable Windows SharePoint Services Objects
Best Practices: Common Coding Issues When Using the SharePoint Object Model.

Most usually we forgot in our code dispose SPWeb or SPSite object after the new operator

//for SPSite
void CreatingSPSiteLeak()
{
    SPSite siteCollection = new SPSite("http://moss");
    // siteCollection leaked
}

//for Open SPWeb
void OpenWebLeak()
{
    using (SPWeb web = new SPSite(SPContext.Current.Web.Url).OpenWeb())
    {
      // SPSite leaked !
    }
}

//for AllWeb
void AllWebsIndexerLeak()
{
    using (SPSite siteCollection = new SPSite("http://moss"))
    {
        SPWeb web = siteCollection.AllWebs[0];
        // SPWeb web leaked
    }
}

//for Add SPWeb
void AllWebsAddLeak()
{
    using (SPSite siteCollection = new SPSite("http://moss"))
    {
        SPWeb web = siteCollection.AllWebs.Add("site-relative URL");
        // SPWeb web Leaked
    }
}
//And many others scene...

Manually configure run SPDisposeCheck as external tool

Implement as below configure

Manually configure run at compile time

Find all projects under the solution that reference the Microsoft.SharePoint namespace and select properties on the project file. Select the Build Events tab and enter the commands below into the Post-build events text box for On Successful Build:

cd $(ProjectDir)

“..\SharePoint Dispose Check\SPDisposeCheck” “$(TargetPath)” > “$(ProjectName)”.SPDisposeCheck.log

findstr /C:”Total Found:” “$(ProjectName)”.SPDisposeCheck.log


More information about the proper disposal of SharePoint objects, see this article

Hoang Nhut Nguyen
Email: nhutcmos@gmail.com
Skype: hoangnhut.nguyen

Last week, I setup my SharePoint Server 2010 on my laptop for development environment.
After finished all installation, I realized that I need test send mail functions. As you may know, I need to configure outgoing e-mail settings from SharePoint Central Administration with existed mail server, or I have to setup a mail server such as Microsoft Exchange or MDaemon,… but these installations required some technical knowledge about IT and not easy to complete it. More than that, it may required for licenses and make slow performance on my laptop for mail services.

The solution I used my Gmail account to send and receive email from my local SharePoint server via hMailServer, it is a free e-mail server for Microsoft Windows. It’s used by Internet service providers, companies, governments, schools and enthusiasts in all parts of the world.

It supports the common e-mail protocols (IMAP, SMTP and POP3) and can easily be integrated with many existing web mail systems. It has flexible score-based spam protection and can attach to your virus scanner to scan all incoming and outgoing email.

The benefits are:
– There is all free and not required for licenses fee
– Fast and and easy to setup
– Gmail is available and have good performance and security

In this post, I just introduce SMTP to send mail and let you try on POP3 and IMAP 😉
OK, Here we go

Firstly, we can download hMailServer from website, I also uploaded current lasted version to Mediafire

After finished download, run hMailServer-5.3.3.exe file, click Next to continue the installation wizard

If your local machine has database instant, click Next to continue the installation wizard, or you can use SQL Compact if don’t have database engine installation.

Click Next on next screen.

On next screen, select Create a new hMailServer database for the first installation

Select your database server type

Input your database server connection information as below

On next screen, select database service to ensure database service is running before hMailServer service is started

Click Close to finish the wizard

After finished the wizard, it prompts for password to be able manage hMailServer configuraiton

Check Run hMailServer Administrator and click Finish to continue configuration

On Conect screen, check on Automatically connect on start-up and click Connect

From left menu, navigate to SMTP, fill your host name to Local host name textbox and SMTP Relayer information. In this step, you have to provide your email account and password to login to Gmail

On RFC compliance, check  as below

Navigate Auto-ban and uncheck Enabled if you don’t use Auto-ban feature

Navigate to My computer under IP ranges, fill your local IP address or keep 127.0.0.1 in Lower IP and Upper IP. Make sure all check box as below

And same to Internet range

Finally, you should disable Firewall service to make sure you have no problems with connection issues

Next step, Login your SharePoint Central Administration. Go to System Settings and select Configure outgoing e-mail settings under E-Mail and Text Messages (SMS) section

Fill Mail settings with your hMailServer information and email address use to send email

To test send mail function, you can open any your web application and go to Site Permissions. Try to add a user and check on Send welcome e-mai to the new users as below

Finally, open mail box of this user and check result

It’s cool!!!

Hoang Nhut Nguyen
Email: nhutcmos@gmail.com
Skype: hoangnhut.nguyen
%d bloggers like this: