Category Archives: c#

Google URL Shortener for SharePoint items

You can shorten URLs to make them easier to share using the Google URL shortener. For example, the short URL

This is a good way to share and generate short links to share documents.

1) you need to get the API Key for:

2) Install Google APIs Client Library, using NuGet


3) Check all References


4) Use the following method to generate ShortLink

public static string UrlShorter(string largeUrl)
     var finalUrl = string.Empty;
     var key = "API KEY GOOGLE"
     var post = "{\"longUrl\": \"" + largeUrl + "\"}";
     var request = (HttpWebRequest)WebRequest.Create(
             "" + key);
             request.ServicePoint.Expect100Continue = false;
                request.Method = "POST";
                request.ContentLength = post.Length;
                request.ContentType = "application/json";
                request.Headers.Add("Cache-Control", "no-cache");
                using (var requestStream = request.GetRequestStream())
                    byte[] postBuffer = Encoding.ASCII.GetBytes(post);
                    requestStream.Write(postBuffer, 0, postBuffer.Length);
                using (var response = (HttpWebResponse)request.GetResponse())
                  using (var responseStream = response.GetResponseStream())
                    if (responseStream != null)
                      using (var responseReader = new StreamReader(responseStream))
                        var json = responseReader.ReadToEnd();
                        var jss = new JavaScriptSerializer();
                     var dict = jss.Deserialize<Dictionary<string, string>>(json);
                        finalUrl = dict["id"]; 
            catch (Exception ex)
            return finalUrl;



// Build 2016 – The Future of C# (CH9)

Since Roslyn shipped last year we’ve been hard at work building on it to improve tooling, add new language features and enhance Roslyn itself. In this session Dustin and Mads will play with fire, showing early versions of new C# 7 language features such as tuples and pattern matching, new editor features like code style and source generators, and much more.

The news about 7.0 version are:

  • Binary Literals
  • Local Functions
  • Tuple
  • Pattern Matching
  • Ref Locals and Ref Returns
  • Records

Take a look at the presentation



SEO – Change Meta Tags Dynamically in SharePoint or – (JavaScript & C#) – Google Crawlers


Meta tags are a great way for webmasters to provide search engines with information about their sites. They can be used to provide information to all sorts of clients, and each system processes.

Meta tags are added to the <head> section of your HTML page and you can add them dynamically use JavaScript when page load or using c#:

The following examples explain how can you add it on your header Page:

1. Use c#

public static void ApplyTagsCSharp(string xtitle, string xkeywords, 
string xdescription, Page page)
            page.Title = xtitle;
            ContentPlaceHolder contentPlaceHolder = 
            (delegate(System.Web.UI.HtmlTextWriter writer,
            System.Web.UI.Control Container)

            ////Add Keywords Meta Tag
            HtmlMeta keywords = new HtmlMeta();
            keywords.HttpEquiv = "keywords";
            keywords.Name = "keywords";
            keywords.Content = xkeywords;

            //Add Description Meta Tag
            HtmlMeta description = new HtmlMeta();
            description.HttpEquiv = "description";
            description.Name = "description";
            description.Content = xdescription;

2. Use JavaScript with ClientScriptManager

public static void ApplyTagsJS(string title, string keywords, 
string description, string author, ClientScriptManager csx, System.Type tp)
            String csname2 = "isTagFunction";
            Type cstype2 = tp;

            if (!csx.IsStartupScriptRegistered(cstype2, csname2))
                StringBuilder cstext2 = new StringBuilder();
                if (!string.IsNullOrEmpty(keywords))
                    cstext2.AppendFormat("$('head').append( '');", keywords);
                if (!string.IsNullOrEmpty(description))
                    cstext2.AppendFormat("$('head').append( '' );", description);
                if (!string.IsNullOrEmpty(title))
                  cstext2.AppendFormat("document.title = \"{0}\"; ", title);
                csx.RegisterStartupScript(cstype2, csname2, cstext2.ToString());


New and improved features in SharePoint Server 2016 Release Candidate


This section provides detailed descriptions of the new and updated features in SharePoint Server 2016 Release Candidate.

Access Services plus Access client and server
Central Administration is no longer provisioned on all servers by default
Compliance features
Document Library accessibility
Encrypted connections
Fast Site Collection Creation
Filenames – expanded support for special characters
Hybrid in SharePoint 2016
Identify and search for sensitive content in both SharePoint 2016 and OneDrive documents.
Image and Video previews
Information Rights Management
Large file support
MinRole farm topology
Mobile experience
New controls for working with OneDrive for Business
Open Document Format (ODF) available for document libraries
Project Server 2016 Release Candidate
Power Pivot add-in and Power View are now available to use with SharePoint Server 2016 Release Candidate
Sharing improvements
SMTP Connection Encryption
SMTP ports (non-default)

New ASP.Net Core 1.0

In 2002… was born ASP.NET … after 15 years we are presenting a new framework ASP.NET 5 and replace ASP.NET 4.6…

ASP.NET 5 is now ASP.NET Core 1.0.

.NET 5 is now .NET Core 1.0.

Entity Framework 7 is now Entity Framework Core 1.0 or EF Core 1.0

.NET Core introduce a new concept multi-platform and open source as you can see on the following image:

net core

for more info about .net core check the following links:


Integrate MailChimp in SharePoint/ Solutions

MailChimp is an email marketing service and the trading name of its operator, it was sending over 10 billion emails per month on behalf of its users.

MailChimp integrates with the web services you already use, so you can easily sync your data, import content from other sources, and get reports on how your newsletters are impacting your business.

if you what use MailChimp on .net/C# Solutions, you can use API following the steps:

First install the NuGet package: Install-Package

mailchimp nuget

The following example explains how to use it.

static void Main(string[] args)
  const string apiKey = "6ea5e2e61844608937376d514-us2";  // Replace it before
  const string listId = "y657cb2495";                     // Replace it before
  var options = new List.SubscribeOptions();
  options.DoubleOptIn = true;
  options.EmailType = List.EmailType.Html;
  options.SendWelcome = false;

  var mergeText = new List.Merges("",List.EmailType.Text)
                        {"NAME", "Fábio Carvalho"},
  var merges = new List<List.Merges> { mergeText };
  var mcApi = new MCApi(apiKey, false); 
  var batchSubscribe = mcApi.ListBatchSubscribe(listId, merges, options);
        if (batchSubscribe.Errors.Count > 0)
            Console.WriteLine("Error:{0}", batchSubscribe.Errors[0].Message);

Useful links:


Build and Send email method to SharePoint – Using Outgoing SMTP Configuration on Central Administration.

To create and Send emails on sharepoint programmatically you can use the following code, but first you need configure the following things:

  • Configure SMTP on server.
  • Configure Outgoing E-Mail on Central Admininstration

(Central Administration > System Settings > Configure outgoing e-mail settings)

  • Oubound SMTP server is server’s IP.


StringBuilder body = new StringBuilder();
body.Append("TEXT OF BODY EMAIL"); // TextBox
string subjectEmail = "SUBJECT OF EMAIL"; // TextBox
string senderTo = ""; //TextBox

SendEmail(senderTo, subjectEmail, body);


 public bool SendEmail(string sTo, string sSubject, StringBuilder sBody)
  // Email header
  StringBuilder sHeader = new StringBuilder();

  // Email footer
  StringBuilder sFooter = new StringBuilder();

  string htmlBody = sHeader.ToString() + sBody.ToString() + sFooter.ToString();

   //Get the Sharepoint SMTP information from the SPAdministrationWebApplication
  string smtpServer = 
  string smtpFrom = 

 // Add the alternate views instead of using MailMessage.Body
  MailMessage m = new MailMessage();
  m.From = new MailAddress(smtpFrom);
  m.To.Add(new MailAddress(sTo));
  m.Subject = sSubject.ToString();
  m.Body = htmlBody;
  m.IsBodyHtml = true;

 SmtpClient client = new SmtpClient(smtpServer);

   return true;
  catch (Exception) { }
  return false;

Check if Current User is member of SharePoint Group’s – Programmatically c#

In SharePoint, we have the 3 predetermined permission groups:

  • Visitors
  • Members
  • Owners

You can see this permissions grpups in the /_layouts/permsetup.aspx page.

(Site settings->People and Groups->Settings->Setup groups)

There are properties on the SPWeb class:

  • SPWeb.AssociatedVisitorGroup
  • SPWeb.AssociatedMemberGroup
  • SPWeb.AssociatedOwnerGroup

Programmatically you can check if current user are in one of those Groups, using the following code:

bool isVisitor = false;
bool isMember = false;
bool isOwner = false;

SPWeb web = SPControl.GetContextWeb(System.Web.HttpContext.Current);
SPContext currentContext = SPContext.Current;
if (currentContext != null && currentContext.Web.CurrentUser != null)
   SPGroupCollection webGroups = web.CurrentUser.Groups;
   if (webGroups != null && webGroups.Count > 0)
       foreach (SPGroup group in web.Groups)
         if (group.ToString() == web.AssociatedVisitorGroup.ToString())
            isVisitor = web.IsCurrentUserMemberOfGroup(group.ID);
         if (group.ToString() == web.AssociatedMemberGroup.ToString())
            isMember = web.IsCurrentUserMemberOfGroup(group.ID);
          if (group.ToString() == web.AssociatedOwnerGroup.ToString())
            isOwner = web.IsCurrentUserMemberOfGroup(group.ID);
if(isVisitor == true)
 // User is Visitor
if(isMember == true)
  // User is Member
if(isOwner == true)
  // User is Owner

Custom menu in SharePoint using Taxonomy Term Store Navigation – Programmatically C#

This is a simple example how to access to Taxonomy Term Store properties in SharePoint using c# and create a Custom Menu.

First, create the terms on your Taxonomy Manage Navigation. – Site settings> Site Administration > Term Store Management

To get the Simple Link URL information using C#:

DataTable dt = new DataTable();
dt.Columns.AddRange(new DataColumn[] { new DataColumn("Title"), 
                                       new DataColumn("Url") });
         foreach (var term in termSet.Terms)
            if (term.IsDeprecated == false)
                 var name = term.Name;
                 var url = term.LocalCustomProperties["_Sys_Nav_SimpleLinkUrl"];
                 dt.Rows.Add(new String[] { name, url });                 
               catch (KeyNotFoundException) { }
         rptFooter.DataSource = dt; 

Create ASPX repeater to construct your Menu

<asp:Repeater ID="rptFooter" runat="server">
  <asp:Button runat="Server" Text='<%# DataBinder.Eval (Container.DataItem, "Title") %>'
  PostBackUrl='<%# DataBinder.Eval (Container.DataItem, "Url") %>' />

The full list of Term Set properties on Manage Navigation in SharePoint 2013:

_Sys_Nav_Title: the Navigation Node Title

_Sys_Nav_FriendlyUrlSegment: the Friendly Url, also represented by the FriendlyUrlSegment property of the NavigationTerm class.

_Sys_Nav_TargetUrl: the target URL, also represented by the TargetUrl property of the NavigationTerm class.

_Sys_Nav_TargetUrlForChildTerms: the target URL for child terms, also represented by the TargetUrlForChildTerms property of the NavigationTerm class.

_Sys_Nav_CatalogTargetUrl: the catalog target URL, also represented by the CatalogTargetUrl property of the NavigationTerm class.

_Sys_Nav_CatalogTargetUrlForChildTerms: the catalog target URL for child terms, also represented by the CatalogTargetUrlForChildTerms property of the NavigationTerm class.