API, Box, C#, Certificates, Web, XML

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
  <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>
  • 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.
 
            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);
  • 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, AWS, C#, IIS, Programming, Web, XML

Ready to send email in Amazon SES? Let’s Go!

First, consult with AWS and get your credentials:

http://docs.aws.amazon.com/ses/latest/DeveloperGuide/using-credentials.html
and
http://docs.aws.amazon.com/ses/latest/DeveloperGuide/send-using-smtp-net.html

Secondly, let’s make a more easily updatable emailSettings section (encrypt it later, see here if you need help):

  <appSettings>
    <add key="MailFrom" value="donotreply@youremaildomain.com"/>
    <add key="MailTo" value="whoareyousendingto@theiremaildomain.com"/>
    <add key="MailHost" value="	email-smtp.youramazonseshost.com"/>
    <add key="MailPort" value="587"/>
    <add key="MailServerUserName" value="awsSESusername"/>
    <add key="MailServerPassword" value="awsSESpassword"/>
  </appSettings>

Then, include the reference:

	using System.Net.Mail;		

Finally, write your method:

	public static void sendEmail(string to, string from, string subject, string body)
	{
		try
		{
			// Initialize client and message
			using (SmtpClient mailclient = new SmtpClient(ConfigurationManager.AppSettings["MailHost"].ToString(), Convert.ToInt32(ConfigurationManager.AppSettings["MailPort"])))
			{
				// Create message
				mailclient.UseDefaultCredentials = false;
				mailclient.EnableSsl = true;
				mailclient.Credentials = new System.Net.NetworkCredential(ConfigurationManager.AppSettings["MailServerUserName"].ToString(), ConfigurationManager.AppSettings["MailServerPassword"].ToString());
				MailMessage message = new MailMessage(from, to);
				message.Subject = subject;
				message.Body = body;
				message.IsBodyHtml = true;
				mailclient.Send(message);
			}
		}
		catch (SmtpException ex)
		{                
			// Service was not available to send message keep trying
			if (ex.StatusCode.Equals(SmtpStatusCode.ServiceNotAvailable))
			{
				sendEmail(to, from, subject, body);
			}
		}
	}

Great! Now you can call it and send an email

string htmlBody = "<b>Hi! It's my message</b>";
sendEmail(ConfigurationManager.AppSettings["MailTo"].ToString(), ConfigurationManager.AppSettings["MailFrom"].ToString(), "Your Email Subject", htmlBody); 

You can always put whoever and whatever when you call the method using To, From, Subject and Body.

Enjoy! Questions are welcome.

.Net, C#, HTML, Office, Programming, VB, Web

Exporting asp:GridView Results To A Microsoft Excel Spreadsheet in VB/C#

I have received this requirement on more than one occasion so I thought it would benefit others if I posted these snippets. So here we go, let’s export a gridview as an excel file.

For starters let’s add a couple controls to the front-end aspx page:

 
<asp:Button ID="btnExport" runat="server" Text="Export Results To Excel" /> &amp;nbsp;&amp;nbsp;<br /><br />

<asp:GridView ID="grdSearch" runat="server" CellPadding="3" BackColor="White" BorderColor="#CCCCCC" BorderStyle="None" BorderWidth="1px">
 <FooterStyle BackColor="White" ForeColor="#000066" />
 <HeaderStyle BackColor="#006699" Font-Bold="True" ForeColor="White" />
 <PagerStyle BackColor="White" ForeColor="#000066" HorizontalAlign="Left" />
 <RowStyle ForeColor="#000066" />
 <SelectedRowStyle BackColor="#669999" Font-Bold="True" ForeColor="White" />
 <SortedAscendingCellStyle BackColor="#F1F1F1" />
 <SortedAscendingHeaderStyle BackColor="#007DBB" />
 <SortedDescendingCellStyle BackColor="#CAC9C9" />
 <SortedDescendingHeaderStyle BackColor="#00547E" />
 </asp:GridView>

I’m going to assume you know how to wire in your gridview to return results.

With that assumption in place here is the click event that performs the export (in VB):

You will need: Imports System.IO

Protected Sub btnExport_Click(sender As Object, e As EventArgs) Handles btnExport.Click
        Try
            Response.Clear()
            Response.Buffer = True
            Response.ClearContent()
            Response.ClearHeaders()
            Response.Charset = ""
            Dim FileName As String = "filename" + DateTime.Now + ".xls"
            Dim strwritter As New StringWriter()
            Dim htmltextwrtter As New HtmlTextWriter(strwritter)
            Response.Cache.SetCacheability(HttpCacheability.NoCache)
            Response.ContentType = "application/vnd.ms-excel"
            Response.AddHeader("Content-Disposition", Convert.ToString("attachment;filename=") &amp; FileName)
            grdSearch.GridLines = GridLines.Both
            grdSearch.HeaderStyle.Font.Bold = True
            grdSearch.RenderControl(htmltextwrtter)
            Response.Write(strwritter.ToString())
            Response.[End]()
        Catch ex As Exception
            ' Do something important here if you expect strange results
        End Try
    End Sub

Now in C#:

You will need: using System.IO;

try {
	Response.Clear();
	Response.Buffer = true;
	Response.ClearContent();
	Response.ClearHeaders();
	Response.Charset = "";
	string FileName = "filename" + DateTime.Now + ".xls";
	StringWriter strwritter = new StringWriter();
	HtmlTextWriter htmltextwrtter = new HtmlTextWriter(strwritter);
	Response.Cache.SetCacheability(HttpCacheability.NoCache);
	Response.ContentType = "application/vnd.ms-excel";
	Response.AddHeader("Content-Disposition", Convert.ToString("attachment;filename=") + FileName);
	grdSearch.GridLines = GridLines.Both;
	grdSearch.HeaderStyle.Font.Bold = true;
	grdSearch.RenderControl(htmltextwrtter);
	Response.Write(strwritter.ToString());
	Response.End();
} catch (Exception ex) {
	// Do something important here if you expect strange results
}

I realize you may not need some of the formatting that I used in this example so remove the Gridview related property assignments in the export snippet. Also, depending on how you format your gridview on the aspx page will dictate some of the formatting you have on the spreadsheet. Hope this helps, questions are welcome.

Apache, PHP, Troubleshooting, Web

Stuck On “Cannot Load php7apache2_4.dll into server: The specified module could not be found”? Try this…

I recently just performed a PHP upgrade from 5.6.15 to 7.0.1. After doing everything I had suspected I needed to do I received this error in my logs when trying to start Apache:

httpd.exe: Syntax error on line 569 of C:/Program Files (x86)/Apache Software Foundation/Apache24/conf/httpd.conf: Cannot load C:/Program Files (x86)/PHP.7.0.1/php7apache2_4.dll into server: The specified module could not be found.

Here is what I had in that block, bolding the item in question:

LoadModule php7_module "C:/Program Files (x86)/PHP.7.0.1/php7apache2_4.dll"
AddHandler application/x-httpd-php .php
PHPIniDir "C:/Program Files (x86)/PHP.7.0.1/"

Huh??? I checked and double checked and that file was there. After about 2 hours of scratching my head I then found a forum post that clicked for me. You may not be recognizing the .dll file because it has a dependency on the Visual C++ Redistributable for Visual Studio 2015. Once I downloaded and installed the exe files (located here) then after another restart I started seeing my pages again. Hope it helps.

C#, HTML, JavaScript, JSON, Programming, Web

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:
 
<script src="https://www.google.com/recaptcha/api.js" type="text/javascript"></script> 
  • Then place in your web page where you want the reCaptcha to live. Remember to replace “yoursitekey” with the Google reCaptcha site key:
<div class="g-recaptcha" data-sitekey="yoursitekey"></div>

 

  • 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:
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;
    }
  • 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):
string EncodedResponse = Request.Form["g-Recaptcha-Response"];
bool IsCaptchaValid = (ReCaptchaClass.Validate(EncodedResponse) == "True" ? true : false);

if (IsCaptchaValid) {
    //Valid Request
}

That’s it! Easy enough, right? I hope it helps. Questions are always welcome.