Blog

  • How To Make A SharePoint List System.String Column (Built From An BCS External Content Type List) Into A Clickable Hyperlink

    So for this example I have a SQL database that I am pulling into an external content type called OfficeLocations. From this external content type I have created a SharePoint list that is referencing it. The issue I ran into is that the GoogleMapLink text coming from SQL was in a NVARCHAR format (which was System.String on the external content type and Single line of text for the column) and you cannot modify those columns.

    officelocationslistsetting

    This left me with a list that had a link but it was not clickable:

    officelocationslistsetting1

    Annoying right? So what do we do? Let’s mess with the XSL template of the item and see what happens…so I popped into SharePoint designer and created a view off of the SharePoint list and modified the XSL template of the GoogleMapLink column to use the string field as the href of the <a> tag and supplied my own text to give the link a more user friendly readable URL.

    To the code (the bolded elements are the only additions I made):
    [sourcecode language=”xml”]
    <xsl:template name="FieldRef_Text_body.GoogleMapLink" ddwrt:dvt_mode="body" match ="FieldRef[@Name=’GoogleMapLink’]" mode="Text_body" ddwrt:ghost="hide">
    <xsl:param name="thisNode" select="."/>
    <xsl:variable name="currentValue" select="$thisNode/@*[name()=current()/@Name]" />
    <xsl:choose>
    <xsl:when test="@AutoHyperLink=’TRUE’">
    <xsl:value-of select="$thisNode/@*[name()=current()/@Name]" disable-output-escaping ="yes"/>
    </xsl:when>
    <xsl:otherwise>
    <strong><xsl:element name="a"></strong>
    <strong> <xsl:attribute name="href"></strong>
    <xsl:value-of select="$thisNode/@*[name()=current()/@Name]"/>
    <strong> </xsl:attribute></strong>
    <strong> <xsl:text>Link</xsl:text></strong>
    <strong> </xsl:element></strong>
    </xsl:otherwise>
    </xsl:choose>
    </xsl:template>
    [/sourcecode]
    This created clickable links titled “Link” on the list itself. You can see the results below:

    officelocationslistsetting2

    Much cleaner, right? If you wanted the full link you could do that too. Hope that helps.

  • Getting Event ID 144 On Your Web Application Proxy When Trying To Connect To ADFS?

    Perhaps as you were setting up your brand new shiny 2012 R2 Web Application Proxy (WAP) to connect to your 2012 R2 Active Directory Federation Services (ADFS 3.0) server you ran into a 404 error in the web browser followed by this error message in the event viewer logs when trying to do your idpinitiated sign on test from the internet using the WAP DNS URL:

    Event ID 144

    The Federation Service Proxy blocked an illegitimate request made by a client, as there was no matching endpoint registered at the proxy.

    Huh?!?!? Okay, so here is one of the reasons why it is generating: the root part of your DNS you use at the proxy must match the DNS you have on your internal ADFS server.

    For example, if you configured your internal federation service name to be different (adfs.internaldomain.com) than the web application proxy name (adfs.yourexternalweb.com) then when the proxy tries to interpret the request it sees the mismatching DNS as an illegitimate request, thus blocking it. And while the WAP will publish various web applications that have different DNS this does not cover the initial configuration of the WAP when it is initially pointed to the internal ADFS server.

    So what’s the solution?

    Get a DNS entry on your internal domain to point to your internal ADFS server using what you used for the web application proxy. These names MUST match for the WAP to work. If you cannot get a DNS entry on your internal domain to match the DNS on the external domain then my recommendation would be to use your etc/hosts file to point your proxy to your ADFS server.

    Once you have the DNS entry or etc/hosts entry in place for your WAP and ADFS server then do the following:

    1. Put the adfs.yourexternalweb.com public cert (with private key) on the ADFS server to be used for communications.
    2. (Assuming ADFS has already been configured) Remove the adfs role from the ADFS server and do not save the databases and reboot.
    4. Install the ADFS role with the new matching Federation Service name (adfs.yourexternalweb.com). Make sure to point to the newly installed certificate. Do not utilize old database information. Create a new WID database.
    5. Remove the WAP role from the WAP server.
    6. Reboot.
    7. Reinstall WAP role and Configure. Once post deployment has completed successfully do NOT create an app for ADFS as it is automatically publishing ADFS as a proxy under the covers.

    Hope this helps. Questions are welcome.

  • Resolving CRM XRMServices System.ServiceModel.ServiceActivationException Issues With Multiple IIS Site Bindings

    So if you ever attempt to go from http to https (or vice versa) on your CRM environment be aware that you may face the following issue with your XRM Services if you have multiple bindings set in IIS:

    WebHost failed to process a request.
     Sender Information: System.ServiceModel.ServiceHostingEnvironment+HostingManager/12547953
     Exception: System.ServiceModel.ServiceActivationException: The service '/Dev/XRMServices/2011/Organization.svc' cannot be activated due to an exception during compilation. The exception message is: The value could not be added to the collection, as the collection already contains an item of the same type: 'System.ServiceModel.Description.UseRequestHeadersForMetadataAddressBehavior'. This collection only supports one instance of each type.
    Parameter name: item. ---> System.ArgumentException: The value could not be added to the collection, as the collection already contains an item of the same type: 'System.ServiceModel.Description.UseRequestHeadersForMetadataAddressBehavior'. This collection only supports one instance of each type.
    Parameter name: item
     at System.Collections.Generic.KeyedByTypeCollection`1.InsertItem(Int32 index, TItem item)
     at Microsoft.Crm.Extensibility.SdkServiceEndpointBuilder.AddDefaultPorts(ServiceHost serviceHost, PortSchemeDictionary portSchemes)
     at Microsoft.Crm.Extensibility.SdkServiceEndpointBuilder.AddDefaultEndpoint(ServiceHost serviceHost, Type implementedContract)
     at Microsoft.Crm.Extensibility.SdkServiceEndpointBuilder.BuildEndpoints(ServiceHost serviceHost, Type implementedContract, Func`1 messageInspectorFactory)
     at Microsoft.Crm.Extensibility.SdkServiceHost.InitializeRuntime()
     at System.ServiceModel.ServiceHostBase.OnOpen(TimeSpan timeout)
     at System.ServiceModel.Channels.CommunicationObject.Open(TimeSpan timeout)
     at System.ServiceModel.ServiceHostingEnvironment.HostingManager.ActivateService(ServiceActivationInfo serviceActivationInfo, EventTraceActivity eventTraceActivity)
     at System.ServiceModel.ServiceHostingEnvironment.HostingManager.EnsureServiceAvailable(String normalizedVirtualPath, EventTraceActivity eventTraceActivity)
     --- End of inner exception stack trace ---
     at System.ServiceModel.ServiceHostingEnvironment.HostingManager.EnsureServiceAvailable(String normalizedVirtualPath, EventTraceActivity eventTraceActivity)
     at System.ServiceModel.ServiceHostingEnvironment.EnsureServiceAvailableFast(String relativeVirtualPath, EventTraceActivity eventTraceActivity)
     Process Name: w3wp
     Process ID: 8388

    Why you ask?! This is due to the fact that CRM is quite finicky about only wanting one particular binding for the CRM instance. Having the multiple bindings without properly setting it up will cause some conflicts (starting with the one above). So the solution here is to ensure you only have one binding in IIS. Once you have your bindings set up properly be sure to perform an IISRESET on the web server. This should resolve the error and make the XRMServices play nice. If it does not check to make sure you do not have any hard-coded values of URLs or ports anywhere. Hope this helps.

  • Use No Captcha reCaptcha In ASP.Net Web Application Form Page With C#, JSON and JavaScript

    Users are getting more and more tired of interpreting images with random numbers or letters that take 2-3 tries to get. Google has a new release of the reCaptcha to include a  “No Captcha” feature. You can read about that more here. Here are the steps that I took to include this newer version into a ASP.Net web application.

    • Obtain a google account and sign up for reCaptcha 
    • Create a Visual Studio C# based web forms application and create a page where you will have your reCaptcha to live
    • Download Json via NuGet (instructions are here)
    • Once you have reCaptcha information be sure to insert the following in the head section of your web page:

    [sourcecode language=”javascript”]
    <script src="https://www.google.com/recaptcha/api.js&quot; type="text/javascript"></script>
    [/sourcecode]

    • Then place in your web page where you want the reCaptcha to live. Remember to replace “yoursitekey” with the Google reCaptcha site key:

    [sourcecode]
    <div class="g-recaptcha" data-sitekey="yoursitekey"></div>
    [/sourcecode]

     

    • Create a class in your web application called ReCaptchaClass (credit for class and credit for proxy) and put the following code into the class. Remember to replace “yoursecretkeygoeshere” with the Google reCaptcha secret key:

    [sourcecode]
    using Newtonsoft.Json;
    public class ReCaptchaClass
    {
    public static string Validate(string EncodedResponse)
    {
    var client = new System.Net.WebClient();
    IWebProxy defaultWebProxy = WebRequest.DefaultWebProxy;
    defaultWebProxy.Credentials = CredentialCache.DefaultCredentials;
    client.Proxy = defaultWebProxy;
    string PrivateKey = "yoursecretkeygoeshere";
    var GoogleReply = client.DownloadString(string.Format("https://www.google.com/recaptcha/api/siteverify?secret={0}&amp;response={1}", PrivateKey, EncodedResponse));
    var captchaResponse = Newtonsoft.Json.JsonConvert.DeserializeObject(GoogleReply);
    return captchaResponse.Success;
    }
    [JsonProperty("success")]
    public string Success
    {
    get { return m_Success; }
    set { m_Success = value; }
    }

    private string m_Success;
    [JsonProperty("error-codes")]
    public List ErrorCodes
    {
    get { return m_ErrorCodes; }
    set { m_ErrorCodes = value; }
    }
    private List m_ErrorCodes;
    }
    [/sourcecode]

    • Once the class is created place the following snippet in the code behind of your page (likely in a button click event of some kind):

    [sourcecode]
    string EncodedResponse = Request.Form["g-Recaptcha-Response"];
    bool IsCaptchaValid = (ReCaptchaClass.Validate(EncodedResponse) == "True" ? true : false);

    if (IsCaptchaValid) {
    //Valid Request
    }
    [/sourcecode]
    That’s it! Easy enough, right? I hope it helps. Questions are always welcome.

  • Redirect All HTTP Requests To HTTPS With IIS URL Rewrite

    Make sure you obtain the appropriate version of URL Rewrite for your version of IIS.

    Once you have the URL Rewrite module installed then create a new blank inbound rule and give it a name (mine is Redirect to HTTPS).

    Once you have the rule created select to match the pattern with regular expressions using .* as the pattern:

    Capture1

    For your conditions, add a condition with the input as {HTTPS} matching the pattern of OFF:

    Capture2

    For the action select Redirect and set your Redirect URL to https://{HTTP_HOST}/{R:0}. Select to append query string and indicate the Redirect type is a Permanent (301):

    Capture3

    Once this is completed (and assuming you have configured your sites for SSL) then you can test it by browsing any page or directory on your site with HTTP and watch it change to HTTPS. Easy enough, right? Hope this helps.

  • Write a JavaScript/HTML Form Submit Post From C# APSX Code Behind

    There may be a case where you are taking information from a form and need to post it to a web site somewhere else. One quick method of performing that post is to execute it from the code behind using C# (via context.response) and JavaScript. This is a scaled down example of a case where I was submitting a POST from the code behind of a web part control:

    A couple things to note:

    • You can add as many fields as you wish to post, I am only using two
    • You can use string.Format to get C# variables to put directly in the POST

    [sourcecode]
    protected string value1;
    protected string value2;

    value1 = "something";
    value2 = "something else";

    Context.Response.Write("&lt;form name=’Form1′ id=’Form1′ method=’post’ action=’https://www.mywebsitetopostto.com/example’&gt;&quot;);
    Context.Response.Write("&lt;input type=’hidden’ name=’__VIEWSTATE’ id=’__VIEWSTATE’ value=” /&gt;");
    Context.Response.Write(string.Format("&lt;input type=’hidden’ name=’txtValue1′ id=’txtValue1′ runat=’server’ value='{0}’ /&gt;", value1));
    Context.Response.Write(string.Format("&lt;input type=’hidden’ name=’txtValue2′ id=’txtValue2′ runat=’server’ value='{0}’ /&gt;", value2));
    Context.Response.Write("&lt;/form&gt;");
    Context.Response.Write("document.Form1.submit();");
    Context.Response.Flush();
    Context.Response.End();
    [/sourcecode]
    Ideally you would use this in a case where you are posting content and the page you are posting to will process and serve something after the form that receives your post processes what you sent. Please do not use this snippet and blame me for a blank page 🙂

  • Convert A Links List To A DropDownList By A Web Part In SharePoint 2013 (C#)

    So I have been enjoying the benefit of Mike Smith’s article for a while now (http://techtrainingnotes.blogspot.com/2010/12/sharepoint-convert-links-list-to.html). A client I did a project for was wanting to carry this functionality forward to 2013. The problem: this method didn’t work in 2013.

    So I took a programmatic approach to lose the JavaScript dependency. It also will sort the dropdown names by what you type as the description by using the sortedlist in the code behind. It’s fairly simple, here’s what I did:

    • Created a links list and populated some URLs and Descriptions (!!! You need both for below to work, otherwise remove the description dependency in my code !!!)
    • Create a SharePoint 2013 Visual Web Part project
    • Add the dropdownlist control to the control

    In the .ascx control I have:
    [sourcecode]
    <asp:DropDownList ID="linkDropDown" runat="server" Font-Names="Arial" Font-Size="10pt"
    Width="300px" OnSelectedIndexChanged="linkDropDown_SelectedIndexChanged" AutoPostBack="true" EnableViewState="true">
    <asp:ListItem Text="Link to …" Value="#"></asp:ListItem>
    </asp:DropDownList>
    [/sourcecode]

    • Add the code to the code behind of the control

    Now the code behind, here’s my using statements:
    [sourcecode]
    using System;
    using System.ComponentModel;
    using System.Web.UI.WebControls.WebParts;
    using Microsoft.SharePoint;
    using System.Collections;
    using System.Web.UI;
    using System.Web.UI.HtmlControls;
    using System.Web.UI.WebControls;
    [/sourcecode]
    and here is what I have in the Page_Load and the SelectedIndexChanged event
    [sourcecode]
    protected void linkDropDown_SelectedIndexChanged(object sender, EventArgs e)
    {
    Context.Response.Redirect(linkDropDown.SelectedValue.ToString());
    }

    protected void Page_Load(object sender, EventArgs e)
    {
    SortedList sortedLists = new SortedList();

    using (SPSite siteCol = new SPSite("http://mysharepoint2013site/&quot;))
    {
    using (SPWeb web = siteCol.RootWeb)
    {
    SPList list = web.GetList("/Lists/NameOfLinksList");
    SPListItemCollection items = list.GetItems();

    foreach (SPListItem it in items)
    {
    SPFieldUrlValue fieldValue = new SPFieldUrlValue(it["URL"].ToString());
    string description = fieldValue.Description;
    string url = fieldValue.Url;
    sortedLists.Add(description, url);
    }
    }

    IDictionaryEnumerator enumerator = sortedLists.GetEnumerator();
    while (enumerator.MoveNext())
    {
    ListItem listitem = new ListItem();
    listitem.Text = enumerator.Key.ToString();
    listitem.Value = enumerator.Value.ToString();
    linkDropDown.Items.Add(new ListItem(listitem.Text.ToString(), listitem.Value.ToString()));
    }
    }
    [/sourcecode]
    Deploy and enjoy!

  • Convert Doc and Docx to PDF in SharePoint 2013 with Word Automation Services (C#)

    Most of you whom are searching around on this are aware of the solution for SharePoint 2010 (https://msdn.microsoft.com/en-us/library/office/ff181518(v=office.14).aspx). And chances are after you tried on your own to do this for 2013 that there was no List Definition type in VS, right? So after finding this (https://camerondwyer.wordpress.com/2013/09/20/how-to-create-a-custom-sharepoint-list-definition-using-visual-studio-2012/) I decided to frankenstein the old methods with the updated way to do it in Visual Studio. The results of the successful experiment are below.

    Code It

    This article describes the following steps to show how to call the Word Automation Services to convert a document:

    1. Creating a SharePoint 2013 Empty Project and Adding the SharePoint list.
    2. Adding a reference to the Microsoft.Office.Word.Server assembly.
    3. Adding an event receiver.
    4. Adding the sample code to the solution.

    Creating a SharePoint 2013 List Definition (sort of) Application in Visual Studio 2012

    This article uses a SharePoint 2013 list definition application for the sample code.

    To create a SharePoint 2013 list definition application in Visual Studio 2012

    1. Start Microsoft Visual Studio 2012 as an administrator.
    2. In Visual Studio 2012 select File | New Project
    3. Select Templates | Visual C# | Office/SharePoint | SharePoint 2013 – Empty Project, Provide a name and location for the project/solution and OKcapture1-vsprojectName the project and solution something meaningful (ConvertWordToPDF perhaps?).
      To create the solution, click OK.
    4. Select a site to use for debugging and deployment.
    5. Select the site to use for debugging and the trust level for the SharePoint solution.
      Note
      Make sure to select the trust level Deploy as a farm solution. If you deploy as a sandboxed solution, it does not work because the solution uses the Microsoft.Office.Word.Server assembly. This assembly does not allow for calls from partially trusted callers.
    6. To finish creating the solution, click Finish.
    7. Once the new solution has been created, we can use the new Visual Designer to create the List Definition. Right click the project in the solution explorer and select Add | New Item
    8. Select Visual C# Items | Office/SharePoint | List, provide a name and click OK
    9. Provide a display name for the list. Go with the “Create a customizable list template and a list instance of it” and choose the Document Library.

    Adding a Reference to the Microsoft Office Word Server Assembly

    To use Word Automation Services, you must add a reference to the Microsoft.Office.Word.Server to the solution.

    To add a reference to the Microsoft Office Word Server Assembly

    1. In Visual Studio, from the Project menu, select Add Reference.
    2. Locate the assembly. By using the Browse tab, locate the assembly. The Microsoft.Office.Word.Server assembly is located in the SharePoint 2013 ISAPI folder. This is usually located at c:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\15\ISAPI\. After the assembly is located, click OK to add the reference.

    Adding an Event Receiver

    This article uses an event receiver that uses the Microsoft.Office.Word.Server assembly to create document conversion jobs and add them to the Word Automation Services conversion job queue.

    To add an event receiver

    1. In Visual Studio, on the Project menu, click Add New Item.
    2. In the Add New Item dialog box, in the Project Templates pane, click the Visual C# SharePoint 2013 template.
    3. In the Templates pane, click Event Receiver.
    4. Name the event receiver ConvertWordToPDFEventReceiver and then click Add.
      The event receiver converts Word Documents after they are added to the List. Select the An item was added item from the list of events that can be handled.
    5. Click Finish to add the event receiver to the project.

    Adding the Sample Code to the Solution

    Replace the contents of the ConvertWordToPDFEventReceiver.cs source file with the following code. Just remember to make sure you replace “Word Automation Services” with the name of it in the web applications in central admin.
    [sourcecode]
    using System;
    using System.Security.Permissions;
    using Microsoft.SharePoint;
    using Microsoft.SharePoint.Security;
    using Microsoft.SharePoint.Utilities;
    using Microsoft.SharePoint.Workflow;

    using Microsoft.Office.Word.Server.Conversions;

    namespace ConvertWordToPDF.ConvertWordToPDFEventReceiver
    {
    /// &lt;summary&gt;
    /// List Item Events
    /// &lt;/summary&gt;
    public class ConvertWordToPDFEventReceiver : SPItemEventReceiver
    {
    /// &lt;summary&gt;
    /// An item was added.
    /// &lt;/summary&gt;
    public override void ItemAdded(SPItemEventProperties properties)
    {
    base.ItemAdded(properties);

    // Verify the document added is a Word document
    // before starting the conversion.
    if (properties.ListItem.Name.Contains(".docx")
    || properties.ListItem.Name.Contains(".doc"))
    {
    //Variables used by the sample code.
    ConversionJobSettings jobSettings;
    ConversionJob pdfConversion;
    string wordFile;
    string pdfFile;

    // Initialize the conversion settings.
    jobSettings = new ConversionJobSettings();
    jobSettings.OutputFormat = SaveFormat.PDF;

    // Create the conversion job using the settings.
    pdfConversion =
    new ConversionJob("Word Automation Services", jobSettings);

    // Set the credentials to use when running the conversion job.
    pdfConversion.UserToken = properties.Web.CurrentUser.UserToken;

    // Set the file names to use for the source Word document
    // and the destination PDF document.
    wordFile = properties.WebUrl + "/" + properties.ListItem.Url;
    if (properties.ListItem.Name.Contains(".docx"))
    {
    pdfFile = wordFile.Replace(".docx", ".pdf");
    }
    else
    {
    pdfFile = wordFile.Replace(".doc", ".pdf");
    }

    // Add the file conversion to the conversion job.
    pdfConversion.AddFile(wordFile, pdfFile);

    // Add the conversion job to the Word Automation Services
    // conversion job queue. The conversion does not occur
    // immediately but is processed during the next run of
    // the document conversion job.
    pdfConversion.Start();

    }
    }
    }
    }
    [/sourcecode]
    Deploy and enjoy!

  • Encrypt And Decrypt A Sitecore ConnectionStrings.Config File

    Encrypting .Net application web.config files are easy enough. However Sitecore is NOT a fan of you messing with the web.config. This is even part of the reason the connection strings are stored out into a separate file in Sitecore. I’ll go through a quick method of taking care of doing it on the separate Sitecore file.

    • Ensure you have .Net framework installed where you are going to perform the encryption (my examples are 4.0, you can use 2.0 if need be)
    • !!!IMPORTANT!!! Make a backup of your Sitecore ConnectionStrings.config file
    • Create a folder on C: to hold your encrypt/decrypt batch files (example will be C:\decrypter) where the .Net framework exists
    • Open notepad and create a batch file (encrypt.bat), put the following in for your encryption statement and then save it to your folder you just created

    [sourcecode]
    echo Encrypting app_config/connectionstrings.config
    C:\Windows\Microsoft.NET\Framework64\v4.0.30319\aspnet_regiis.exe -pef "connectionStrings" "C:\decrypter"
    Pause
    [/sourcecode]

    • Repeat this step for the decryption statement (decrypt.bat)

    [sourcecode]
    echo Encrypting app_config/connectionstrings.config
    C:\Windows\Microsoft.NET\Framework64\v4.0.30319\aspnet_regiis.exe -pdf "connectionStrings" "C:\decrypter"
    Pause
    [/sourcecode]

    • Create a blank web.config (THIS IS YOUR WEB.CONFIG YOU MADE AND NOT THE SITECORE WEB.CONFIG!!!), put and wrap your Sitecore connection strings (from ConnectionStrings.config) inside and save it to the folder you created. it should look something like:

    [sourcecode]
    <?xml version="1.0" encoding="utf-8"?>
    <configuration>
    <connectionStrings>
    <add name="core" connectionString="user id=sitecoreuser;password=sitecorepw;Data Source=servernameorip;Database=Sitecore_Core" />
    <add name="master" connectionString="user id=sitecoreuser;password=sitecorepw;Data Source=servernameorip;Database=Sitecore_Master" />
    <add name="web" connectionString="user id=sitecoresql;password=sitecorepw;Data Source=servernameorip;Database=Sitecore_Web" />
    <add name="reporting" connectionString="user id=sitecoresql;password=sitecorepw;Data Source=servernameorip;Database=Sitecore_Analytics" />
    </connectionStrings>
    </configuration>
    [/sourcecode]

    •  Once you have both batch files and the web.config then run the encrypt batch file as an administrator. It will look something like this:

    encrypt

    • You’ll then have a web.config in your folder now similar to this:

    [sourcecode]
    <?xml version="1.0" encoding="utf-8"?>
    <configuration>
    <connectionStrings configProtectionProvider="RsaProtectedConfigurationProvider">
    <EncryptedData Type="http://www.w3.org/2001/04/xmlenc#Element&quot;
    xmlns="http://www.w3.org/2001/04/xmlenc#"&gt;
    <EncryptionMethod Algorithm="http://www.w3.org/2001/04/xmlenc#tripledes-cbc&quot; />
    <KeyInfo xmlns="http://www.w3.org/2000/09/xmldsig#"&gt;
    <EncryptedKey xmlns="http://www.w3.org/2001/04/xmlenc#"&gt;
    <EncryptionMethod Algorithm="http://www.w3.org/2001/04/xmlenc#rsa-1_5&quot; />
    <KeyInfo xmlns="http://www.w3.org/2000/09/xmldsig#"&gt;
    <KeyName>Rsa Key</KeyName>
    </KeyInfo>
    <CipherData>
    <CipherValue>(you’ll have a long cipher here)</CipherValue>
    </CipherData>
    </EncryptedKey>
    </KeyInfo>
    <CipherData>
    <CipherValue>(you’ll have a long cipher here)</CipherValue>
    </CipherData>
    </EncryptedData>
    </connectionStrings>
    </configuration>
    [/sourcecode]

    • Once completed take the connectionStrings section of the web.config and replace your ConnectionStrings.config file with the encrypted connectionStrings section (run notepad in admin mode if your sitecore is in the web root).
    • Recycle the app pool to refresh. You should now be encrypted!
    • If this fails for you at some point then replace your Sitecore connectionStrings.config file with the backup you took at the start.
    • And yes, to decrypt (to update your strings) put your encrypted connectionstrings section in your web.config (THIS IS YOUR WEB.CONFIG YOU MADE AND NOT THE SITECORE WEB.CONFIG!!!) in the windows folder you made and run the decrypt.bat as an admin. You should get:

    decrypt

    Again, I hope this helps someone. Questions and comments are always welcome! And for the sake of hoping I catch the skimmers here, DO NOT MODIFY THE SITECORE WEB.CONFIG. DO THIS ON THE CONNECTIONSTRINGS.CONFIG! You have been warned…

  • Sluggish Sitecore Development Environment? Here’s An Easy Method To Disable Sitecore Analytics

    When you install a new 8.0 instance of Sitecore you will find the site can be laggy and sluggish to load. To speed up your dev environment I would recommend this easy fix.

    First create a folder called z in your app config sitecore path: C:\inetpub\wwwroot\yoursitecore\Website\App_Config\z

    Then, create a file called zwoa.config and paste the following in:
    [sourcecode]
    <configuration xmlns:patch="<a href="http://www.sitecore.net/xmlconfig/">http://www.sitecore.net/xmlconfig/</a>"&gt;
    <sitecore>
    <pipelines>
    <initialize>
    <processor type="Sitecore.Pipelines.Initialize.PrecompileSpeakViews, Sitecore.Speak.Clientpro" >
    <patch:delete />
    </processor>
    <processor type="Sitecore.ContentTesting.Pipelines.Initialize.RegisterContentTestingCommandRoute, Sitecore.ContentTesting" >
    <patch:delete />
    </processor>
    <processor type="Sitecore.Pipelines.Initialize.PrecompileSpeakViews, Sitecore.Speak.Client" use="ContentTesting" >
    <patch:delete />
    </processor>
    </initialize>
    <mvc.renderPageExtenders>
    <processor patch:after="processor[@type=’Sitecore.Mvc.ExperienceEditor.Pipelines.RenderPageExtenders.RenderExtendersContainer, Sitecore.Mvc.ExperienceEditor’]" type="Sitecore.Mvc.ExperienceEditor.Pipelines.RenderPageExtenders.RenderPageEditorExtender, Sitecore.Mvc.ExperienceEditor"></processor>
    <processor patch:after="processor[@type=’Sitecore.Mvc.ExperienceEditor.Pipelines.RenderPageExtenders.RenderExtendersContainer, Sitecore.Mvc.ExperienceEditor’]" type="Sitecore.Mvc.ExperienceEditor.Pipelines.RenderPageExtenders.RenderPreviewExtender, Sitecore.Mvc.ExperienceEditor"></processor>
    <processor patch:after="processor[@type=’Sitecore.Mvc.ExperienceEditor.Pipelines.RenderPageExtenders.RenderExtendersContainer, Sitecore.Mvc.ExperienceEditor’]" type="Sitecore.Mvc.ExperienceEditor.Pipelines.RenderPageExtenders.RenderDebugExtender, Sitecore.Mvc.ExperienceEditor"></processor>
    <processor type=""Sitecore.Mvc.ExperienceEditor.Pipelines.RenderPageExtenders.SpeakRibbon.RenderPageEditorSpeakExtender, Sitecore.Mvc.ExperienceEditor" >
    <patch:delete />
    </processor>
    </mvc.renderPageExtenders>
    </pipelines>
    <settings>
    <setting name="Analytics.Enabled" > <patch:attribute name="value" value="false" />
    </setting>
    </settings>
    </sitecore>
    </configuration>
    [/sourcecode]
    Refresh your Sitecore in a web browser and watch it go!

  • C# Send A SMS Text Message Programmatically Using Clickatell HTTP API

    I would start off by heading here to better understand the Clickatell HTTP API: https://www.clickatell.com/apis-scripts/apis/http-s/. If you are interested they allow you 10 free text messages to try it out before you buy a package. Just sign up for an account and create your HTTP API and use your information to populate the snippet below.

    For a particular project I am using this API to send out texts for verification purposes. I am using my method inside of a web service to send the information about a user as well as their pre-generated pin. Of course it is a lot different in my project but I am providing the bare bones below.

    If you are a skimmer and you skipped reading anything I said above then here you go:

    Code for MyWebRequest class:
    [sourcecode]
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Net;
    using System.IO;
    using System.Text;
    using System.Configuration;

    namespace CustomWebServices
    {
    public class MyWebRequest
    {
    private WebRequest request;
    private Stream dataStream;

    private string status;

    public String Status
    {
    get
    {
    return status;
    }
    set
    {
    status = value;
    }
    }

    public MyWebRequest(string url)
    {
    // Create a request using a URL that can receive a post.

    request = WebRequest.Create(url);
    }

    public MyWebRequest(string url, string method)
    : this(url)
    {

    if (method.Equals("GET") || method.Equals("POST"))
    {
    // Set the Method property of the request to POST.
    request.Method = method;
    }
    else
    {
    throw new Exception("Invalid Method Type");
    }
    }

    public MyWebRequest(string url, string method, string data)
    : this(url, method)
    {

    // Create POST data and convert it to a byte array.
    string postData = data;
    byte[] byteArray = Encoding.UTF8.GetBytes(postData);

    // Set the ContentType property of the WebRequest.
    request.ContentType = "application/x-www-form-urlencoded";

    // Set the ContentLength property of the WebRequest.
    request.ContentLength = byteArray.Length;

    // Get the request stream.
    dataStream = request.GetRequestStream();

    // Write the data to the request stream.
    dataStream.Write(byteArray, 0, byteArray.Length);

    // Close the Stream object.
    dataStream.Close();

    }

    public string GetResponse()
    {
    // Get the original response.
    WebResponse response = request.GetResponse();

    this.Status = ((HttpWebResponse)response).StatusDescription;

    // Get the stream containing all content returned by the requested server.
    dataStream = response.GetResponseStream();

    // Open the stream using a StreamReader for easy access.
    StreamReader reader = new StreamReader(dataStream);

    // Read the content fully up to the end.
    string responseFromServer = reader.ReadToEnd();

    // Clean up the streams.
    reader.Close();
    dataStream.Close();
    response.Close();

    return responseFromServer;
    }
    }
    }
    [/sourcecode]
    And now the code for the method itself:
    [sourcecode]
    public string SendText(string mobile, string pin)
    {
    // Make sure to add the country code to ensure the text goes through
    string phoneCheck = "";
    if (mobile.Length == 10)
    {
    phoneCheck = "1" + mobile;
    }
    // Clickatell settings
    string textmessage = "Your verification pin is " + pin;
    string parameters = "";
    parameters = "user=yourclickatellusername";
    parameters = parameters + "&amp;password=yourclickatellpassword";
    parameters = parameters + "&amp;api_id=youruniqueclickatellhttpapiid";
    parameters = parameters + "&amp;to=" + phoneCheck;
    parameters = parameters + "&amp;text=" + textmessage;
    parameters = parameters + "&amp;mo=1";
    parameters = parameters + "&amp;from=15558675309";
    MyWebRequest myRequest = new MyWebRequest("<a href="http://api.clickatell.com/http/sendmsg">http://api.clickatell.com/http/sendmsg</a>&quot;, "POST", parameters);
    myRequest.GetResponse();
    } // SendText
    [/sourcecode]
    * Note: If you put this call on a server that will require a proxy then add it to your MyWebRequest class

  • Add An Item To A Custom SharePoint List Using Batch XML With A Web Service (C#)

    If you have multiple active directory environments and SharePoint instances in both of those environments then you will understand why I posted this.

    I received a requirement that while users from a separate domain and SharePoint instance would need to fill out a form on their SharePoint and have the form submission be sent to the other SharePoint instance (on the other domain). This was because they did not want to mix and mingle with forest trusting or having users to have two separate AD accounts to manage the information. Say what?!

    After some initial discovery I had reached a couple quick conclusions:

    – SharePoints on different domains do not talk well to each other without trust

    – Using the built-in lists service on SharePoint has to be done on the server itself unless you are going to have an instance stood up somewhere on the same domain that has all the required SharePoint dlls to be referenced

    All being said, here is an example of what I used as a web service I placed on the SharePoint server that calls the lists web service doing a list add using batch XML:
    [sourcecode]
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Runtime.Serialization;
    using System.ServiceModel;
    using System.ServiceModel.Web;
    using System.Text;
    using Microsoft.SharePoint;
    using Microsoft.SharePoint.Client;
    using Microsoft.SharePoint.Administration;
    using Microsoft.SharePoint.Administration.Claims;
    using Microsoft.SharePoint.WebControls;

    namespace CopyOverItemFromOtherSP
    {

    {
    public string CopyOverFromOtherDomain(string userName, string Name, string userEmail,
    string userPhone, string listColumn1, string listColumn2, string listColumn3,
    string Comments)
    {
    Boolean done = false;

    /* Declare and initialize a variable for the Lists Web service. */
    sitesWebServiceLists.Lists listService = new sitesWebServiceLists.Lists();

    /* Authenticate the current user by passing their default credentials to the Web service from the system credential cache. */
    listService.Credentials = System.Net.CredentialCache.DefaultCredentials;

    /* Set the Url property of the service for the path to a subsite. */
    // Service URLs – MUST CHANGE TO POINT TO SPECIFIC SERVICE ENVIRONMENT
    // Change the web reference URL on the sitesWebServiceLists web service reference to be the address
    // that you are wanting to used based on the environment that you want to write to
    listService.Url = "<a href="#">http://sharepointtocopyitemto/_vti_bin/Lists.asmx</a>&quot;;

    /* Get Name attribute values (GUIDs) for list and view. */
    System.Xml.XmlNode ndListView = listService.GetListAndView("NameOfSharePointList", "");
    string strListID = ndListView.ChildNodes[0].Attributes["Name"].Value;
    string strViewID = ndListView.ChildNodes[1].Attributes["Name"].Value;

    /* Create an XmlDocument object and construct a Batch element and its
    attributes. Note that an empty ViewName parameter causes the method to use the default view. */
    System.Xml.XmlDocument doc = new System.Xml.XmlDocument();
    System.Xml.XmlElement batchElement = doc.CreateElement("Batch");
    batchElement.SetAttribute("OnError", "Continue");
    batchElement.SetAttribute("ListVersion", "1");
    batchElement.SetAttribute("ViewName", strViewID);

    /* Specify methods for the batch post using CAML. To update or delete,
    specify the ID of the item, and to update or add, specify
    the value to place in the specified column. */
    batchElement.InnerXml = "<Method ID=’1′ Cmd=’New’>" +
    "<Field Name=’ID’>New</Field>" +
    "<Field Name=’Title’>" + userName.ToString() + "</Field>" +
    "<Field Name=’Name’>" + Name.ToString() + "</Field>" +
    "<Field Name=’userEmail’>" + userEmail.ToString() + "</Field>" +
    "<Field Name=’userPhone’>" + userPhone.ToString() + "</Field>" +
    "<Field Name=’listColumn1′>" + listColumn1.ToString() + "</Field>" +
    "<Field Name=’listColumn2′>" + listColumn2.ToString() + "</Field>" +
    "<Field Name=’listColumn3′>" + listColumn3.ToString() + "</Field>" +
    "<Field Name=’Comments’>" + Comments.ToString() + "</Field>" +
    "</Method>";

    /* Update list items. This example uses the list GUID, which is recommended,
    but the list display name will also work. */
    try
    {
    listService.UpdateListItems(strListID, batchElement);
    done = true;
    }
    catch
    {

    }
    if (done == true)
    {
    return done.ToString();
    }
    else
    {
    return done.ToString();
    }
    }
    }
    }
    [/sourcecode]

  • Programmatically Install A Root CA Certificate So Users Don’t Have To (C#)

    So here’s the backstory: I received the task of improving certificate enrollment so that users can

    1) Be verified via username, password, captcha & verification pin

    2) Auto Enroll without an external approval

    3) Simplify the process

    As some of you already know, ADCS via web enrollment is…how can we say…dated. So I wrote an application that sits in front of ADCS to first verify the user. Once they are through then the web enrollment is configured to let them run the wizard through to installing their cert. The issue that came to me is that most end-users will not take the time to ensure the root CA makes it to the trusted store (thus giving the classic CA cert is not installed message). So I received the order from on-high to “do it for them”. At first I struggled, attempting to understand how this could be done. I spoke with Microsoft and as I already was aware they indicated that having the user choose the trusted root store for the CA is by design. So what to do…ah I know, let’s just script it out.

    So this is as simple as it gets. Download the cert, store it on the local drive and use the built-in certmgr.exe to perform the root CA to trusted store installation. Here it is (this code is just one a basic console app):

    Code:
    [sourcecode]
    using System.Security.Cryptography.X509Certificates;

    WebClient webClient = new WebClient();
    webClient.DownloadFile("https://yourserver.domain.com/CertSrv/certnew.cer?ReqID=CACert&amp;Renewal=0&amp;Mode=inst&amp;Enc=b64&quot;, @"C:\Temp\certnew.cer");

    X509Store store = new X509Store(StoreName.Root,
    StoreLocation.LocalMachine);
    store.Open(OpenFlags.ReadWrite);
    X509Certificate2Collection collection = new X509Certificate2Collection();
    X509Certificate2 cert = new X509Certificate2(@"C:\Temp\certnew.cer");
    byte[] encodedCert = cert.GetRawCertData();
    Console.WriteLine("We are now installing the CA certificate into the Trusted Root Certificate store …");
    store.Add(cert);
    Console.WriteLine("Done! The CA certificate was successfully. Press any key to close.");
    Console.ReadKey();
    store.Close();
    [/sourcecode]
    This finishes the root CA portion so they can fly through the rest of web enrollment. Hope this helps.

  • Execute An Oracle Stored Procedure With Parameters (C#)

    So you want to execute an Oracle stored procedure with parameters, huh? For this example I have an Oracle stored procedure called MEMBER_TYPE_UPDATE that will update what type of membership I have based on the numeric value. This sort of snippet can be used in a web application directly or called by some form of web service.

    Here are some example values:

    0 = Not a member

    1 = Member

    2 = Member with first tier privileges

    3 = Member with highest level privileges

    The update occurs based on their username and based on that username will attempt to update the numeric value. So below we will be calling a method (passing the two parameters to update with). I will then gather the connection string to Oracle and begin to execute my Oracle stored procedure (while giving it the values passed into the method to be used in the stored procedure).

    Here’s my snippet:

    [sourcecode]
    using System;
    using System.Data;
    using System.Web.Services;
    using Oracle.DataAccess.Client;
    using System.Configuration;

    public string SetUserMembership(string membershipNetworkUserName, int membershipStatusValue)
    {
    string errorString = string.Empty;
    OracleCommand cmd = null;
    try
    {

    string connectionString = string.Empty;
    if (ConfigurationManager.AppSettings["location"].Contains("PROD"))
    {
    connectionString = ConfigurationManager.ConnectionStrings["ConnectionStringPROD"].ConnectionString;
    }
    else
    {
    connectionString = ConfigurationManager.ConnectionStrings["ConnectionStringDEV"].ConnectionString;
    }

    cmd = new OracleCommand();
    cmd.Connection = new OracleConnection(connectionString);
    cmd.CommandType = CommandType.StoredProcedure;
    cmd.CommandText = "ORACLE_USER.MEMBER_TYPE_UPDATE";
    cmd.Parameters.Add("in_employeeUserName", OracleDbType.Varchar2).Value = membershipNetworkUserName;
    cmd.Parameters.Add("in_status_id", OracleDbType.Decimal).Value = membershipStatusValue;
    cmd.Parameters.Add("O_RETURN_STATUS", OracleDbType.Varchar2, 4000).Direction = ParameterDirection.Output;
    cmd.Connection.Open();
    cmd.ExecuteNonQuery();

    string returnString = cmd.Parameters["O_RETURN_STATUS"].Value.ToString();
    if (!returnString.Contains("SUCCESS"))
    {
    // obviously there was an issue and we want to display this somewhere
    errorString = returnString;
    }
    }
    [/sourcecode]

    For a specific call I would call it with SetUserMembership(“username”, “2”);

    Ideally you would have variables there. Hope this helps people to see the parameters in use.

  • Check For A Referring Page URL And Redirect (Classic ASP)

    I spent a while looking around for something that would help me tighten up some pages that did not need reached unless they came from another page that I had authorized.

    In this example we check first that there is a referring URL and if there is not then go to my error page. The next part two checks look to ensure that the referring page is not the two pages we are okay with the referring URL to be.  If the referring URL is not either of those then we know the previous page is not what we want either and we refer to an error page.
    [sourcecode]
    <%
    referer=request.servervariables("http_referer")
    if (referer = "") then
    Response.Redirect "error.asp"
    elseif (referer <> "<a href="https://www.google.com">https://www.google.com</a>&quot😉 then

    elseif (referer <> "<a href="https://www.yahoo.com">https://www.yahoo.com</a>&quot😉 then

    else
    Response.Redirect "error.asp"
    end if
    %>
    [/sourcecode]