Category: C#

  • How To Use the Box API To Adjust User Properties and Make Read-Only in Bulk (w/example)

    • Get up to date on the APIs you need for users @ https://developer.box.com/v2.0/reference
    • Sign up for your developer account at your enterprise @ https://yourenterprise.app.box.com/developers/console (replace with your enterprise application name in the link above)
    • Create your Box app & API Key – link here and here
    • Pull down the Box Windows SDK @ – https://github.com/box/box-windows-sdk-v2
    • Update the pem file with your actual pem information from the app you created
      • in case you’re wondering it should contain the —–BEGIN ENCRYPTED PRIVATE KEY—– and —–END ENCRYPTED PRIVATE KEY—–
    • Update the properties appropriately in the app.config

    [sourcecode]
    <appSettings>
    <add key="boxClientId" value="uniquestringhere" />
    <add key="boxClientSecret" value="uniquestringheretoo" />
    <add key="boxEnterpriseId" value="1234567" />
    <add key="boxPrivateKeyPassword" value="uniquestringhereforpassword" />
    <add key="boxPublicKeyId" value="uniquepublickeyid" />
    <add key="ClientSettingsProvider.ServiceUri" value="useifneeded" />
    </appSettings>
    [/sourcecode]

    • From there you can update your Main runner in the program.cs appropriately. In the case of my sample below I am getting authorized, retrieving my users and looping through everyone but the main admin account and making them read-only. I’m also writing the information out to a file so I’ll have the logs of who was set / not set.

    [sourcecode]

    var privateKey = File.ReadAllText("private_key.pem");

    var boxConfig = new BoxConfig(CLIENT_ID, CLIENT_SECRET, ENTERPRISE_ID, privateKey, JWT_PRIVATE_KEY_PASSWORD, JWT_PUBLIC_KEY_ID);
    var boxJWT = new BoxJWTAuth(boxConfig);

    var adminToken = boxJWT.AdminToken();
    Console.WriteLine("Admin Token: " + adminToken);
    Console.WriteLine();

    var adminClient = boxJWT.AdminClient(adminToken);

    var items = await adminClient.UsersManager.GetEnterpriseUsersAsync("", 0, 1000);
    items.Entries.ForEach(async i =>
    {
    if (i.Login != "myspecialadminaccount@domain.com")
    {
    BoxUserRequest userRequest = new BoxUserRequest()
    {
    Id = i.Id,
    Status = "cannot_delete_edit_upload"
    };
    System.Console.WriteLine("\t{0}", i.Name);
    System.Console.WriteLine("\t{0}", i.Id);
    System.Console.WriteLine("\t{0}", i.Login);
    System.Console.WriteLine("\t{0}", i.Type);
    System.Console.WriteLine(" ");
    // Turn on for prod
    BoxUser user = await adminClient.UsersManager.UpdateUserInformationAsync(userRequest);
    Console.WriteLine(userRequest.Name + "updated to read-only");
    System.Threading.Thread.Sleep(2000);
    stringtext = i.Name.ToString() + " – " + i.Id.ToString() + " – " + i.Login.ToString() + " – " + i.Type.ToString() + " – updated to readonly" + Environment.NewLine;
    System.Console.WriteLine(" ");

    }
    else
    {
    BoxUserRequest userRequest = new BoxUserRequest()
    {
    Id = i.Id
    };
    System.Console.WriteLine("\t{0}", i.Name);
    System.Console.WriteLine("\t{0}", i.Id);
    System.Console.WriteLine("\t{0}", i.Login);
    System.Console.WriteLine("\t{0}", i.Type);
    System.Console.WriteLine(" ");
    Console.WriteLine(userRequest.Name + " NOT updated to read-only");
    System.Threading.Thread.Sleep(2000);
    stringtext = i.Name.ToString() + " – " + i.Id.ToString() + " – " + i.Login.ToString() + " – " + i.Type.ToString() + " – NOT updated to readonly" + Environment.NewLine;
    System.Console.WriteLine(" ");

    }
    });
    File.AppendAllText("C:\\Temp\\" + "log.txt", stringtext);
    [/sourcecode]

    • Enable your box application to your enterprise accounts – link here
    • Run your app (In TEST with test accounts! Then, with approval, prod.)
      • If the app won’t run…check:
        • code syntax errors
        • certificate pem
        • values in the app config
        • authorization status in the admin Console on Box
        • that your app is enabled and still available on the enterprise developer site

    Hope this helps! I can send the source out on request if needed (just let me know).

  • .Net MVC – Display a user’s Full Name instead of User.Identity.Name (DOMAIN\USERNAME)

    I had a request come in on a MVC web app to display a user’s full name instead of their domain network username. The app was using something like:

    [sourcecode]
    <p>Hello, @User.Identity.Name</p>
    [/sourcecode]

    which displayed like:

    Hello, MYDOMAIN\myusername!

    So to update this on the MVC web app (and avoid a dedicated helper) here is what I did:

    In your _ViewImports.cshtml include:

    [sourcecode]
    @using System.DirectoryServices.AccountManagement
    [/sourcecode]

    Then, in your _Layouts.cshtml place this

    [sourcecode]
    @{
    var context = new PrincipalContext(ContextType.Domain);
    var principal = UserPrincipal.FindByIdentity(context, User.Identity.Name);
    }
    [/sourcecode]

    The above will render the user’s currently logged in claims and return their claim attributes as needed. You can use others as you have them also for other purposes, too.

    Now, in your _Layouts.cshtml you can switch your original hello item to:

    [sourcecode]
    <p>Hello, @principal.GivenName @principal.Surname!</p>
    [/sourcecode]

    You should get a friendlier format like:

    Hello, Jared Meredith!

    Hope that helps. Questions or comments are always welcome!

  • 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.

  • 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!

  • 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.