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 URLhttp://goo.gl/l6MS

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

1) you need to get the API Key for: https://developers.google.com/url-shortener/

2) Install Google APIs Client Library, using NuGet

googleapi

3) Check all References

shorten

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(
             "https://www.googleapis.com/urlshortener/v1/url?key=" + key);
            try
            {
             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)
            {
                System.Diagnostics.Debug.WriteLine(ex.Message);
                System.Diagnostics.Debug.WriteLine(ex.StackTrace);
            }
            return finalUrl;
        }

Thanks

// 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

 

Thanks

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

Google-Crawl-Index-550x331

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 = 
           (ContentPlaceHolder)page.Master.FindControl("PlaceHolderPageTitle");
            contentPlaceHolder.SetRenderMethodDelegate
            (delegate(System.Web.UI.HtmlTextWriter writer,
            System.Web.UI.Control Container)
            {
                writer.Write(xtitle);
            });

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

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

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();
                cstext2.Append("");
                if (!string.IsNullOrEmpty(keywords))
                {
                    cstext2.Append("$('meta[name=keywords]').remove();");
                    cstext2.AppendFormat("$('head').append( '');", keywords);
                }
                if (!string.IsNullOrEmpty(description))
                {
                    cstext2.Append("$('meta[name=description]').remove();");
                    cstext2.AppendFormat("$('head').append( '' );", description);
                }
                if (!string.IsNullOrEmpty(title))
                {
                  cstext2.AppendFormat("document.title = \"{0}\"; ", title);
                }
                csx.RegisterStartupScript(cstype2, csname2, cstext2.ToString());
            }
        }

Thanks

New and improved features in SharePoint Server 2016 Release Candidate

SHP2016

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)
https://technet.microsoft.com/en-us/library/mt346121(v=office.16).aspx

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:

https://github.com/dotnet/core

http://docs.asp.net/en/latest/getting-started/installing-on-linux.html

https://blogs.msdn.microsoft.com/dotnet/2014/12/04/introducing-net-core/

Thanks

Integrate MailChimp in SharePoint/ ASP.net 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 mcapi.net

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("fcsharepoint@outlook.com",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);
        }
        else
        {
            Console.WriteLine("Success");
        }
    Console.ReadKey();
    }

Useful links:

http://perceptivemcapi.codeplex.com/

http://mailchimp.com/

Thanks

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.

Code:

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

SendEmail(senderTo, subjectEmail, body);

Method:

 public bool SendEmail(string sTo, string sSubject, StringBuilder sBody)
 {
  // Email header
  StringBuilder sHeader = new StringBuilder();
  sHeader.Append("<html>");
  sHeader.Append("<body>");

  // Email footer
  StringBuilder sFooter = new StringBuilder();
  sFooter.Append("</body>");
  sFooter.Append("</html>");

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

   //Get the Sharepoint SMTP information from the SPAdministrationWebApplication
  string smtpServer = 
  SPAdministrationWebApplication.Local.OutboundMailServiceInstance.Server.Address;
   
  string smtpFrom = 
  SPAdministrationWebApplication.Local.OutboundMailSenderAddress;

 // 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);

 try
 {
   client.Send(m);
   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)
            {
               try
               {
                 var name = term.Name;
                 var url = term.LocalCustomProperties["_Sys_Nav_SimpleLinkUrl"];
                 dt.Rows.Add(new String[] { name, url });                 
               }
               catch (KeyNotFoundException) { }
             }
           }
       ...
         rptFooter.DataSource = dt; 
         rptFooter.DataBind();

Create ASPX repeater to construct your Menu

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

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.