Posts

Showing posts from 2016

Azure API: Why does my API in the API Management Developer Portal not have a subscription key?

Image
I encountered this problem recently when trying to add an API to my API Management. I followed all the steps but my API execution complained that the subscription key was missing. The reason for the error is that my API was not associated to a Product. To fix this, 1. Open the Publisher Portal from 'Overview' option in the API Management blade 2. Navigate to the 'Products' tab and assign the API to a product 3. Now navigate to the Developer Portal and subscription key value is now set in the request header.

How can I document my API with Swagger?

Image
Swagger has provided a very simple way to document your APIs. I created a simple OOTB Web Application with the Web API template. To create the swagger output: 1. Add the SwashBuckle nuget package 2. Publish the API and navigate to <API URL> /swagger/docs/v1 . This will create the swagger json 3. Save the file in a swagger.json file in the solution. 4. Open the file with the  http://editor.swagger.io/#/ to retrieve the documentation.

C#: How do I create a comma separated list from an object?

        public static string CreateCSVFromObject(object obj)         {             if (obj == null)             {                 throw new ArgumentNullException("obj", "Value can not be null or Nothing!");             }             StringBuilder sb = new StringBuilder();             Type t = obj.GetType();             PropertyInfo[] pi = t.GetProperties();             for (int index = 0; index < pi.Length; index++)             {                 sb.Append(pi[index].GetValue(obj, null));                 if (index < pi.Length - 1)        ...

How can I create a generic data repository for my Entity Framework solution?

I recently created a quick console application that required CRUD activities on a SQL database. I had a few tables to update and did not want the headache of creating multiple items in my DAL. Enter a generic data repository. The code is pretty simple: 1. Create a base interface for the CRUD operations public interface IGenericDataRepository<T> where T : class     {         List<T> GetAll(params Expression<Func<T, object>>[] navigationProperties);         List<T> GetList(Func<T, bool> where, params Expression<Func<T, object>>[] navigationProperties);         T GetSingle(Func<T, bool> where, params Expression<Func<T, object>>[] navigationProperties);         void Add(params T[] items);         void Update(params T[] items);         void Remove(params T[] items);     ...

Azure: How do I create an MVC site to load files to BLOB storage?

I recently created a simple POC site to load files to blob storage containers in Azure. Here is how I achieved it. My code is based on the sample provided  here After creating a simple MVC web project, I added the following nuget packages: DropZone WindowsAzure.Storage Microsoft.WindowsAzure.ConfigurationManager The code is pretty simple: Here is Index.cshtml: @model List<string> <script src="~/Scripts/dropzone/dropzone.min.js"></script> <script src="~/Scripts/bootstrap.min.js"></script> <link href="~/Scripts/dropzone/dropzone.min.css" rel="stylesheet" /> <div class="jumbotron">     <h2>FILE UPLOAD</h2>     <form action="~/Home/Upload"           class="dropzone"           id="dropzoneJsForm"           style="background-color:#00BFFF"></form>         <button id="refresh" onc...

CSS: How do I create a spinning 'loading' icon using an image

Image
The icon can be created using the following simple classes .loading{background:url(../img/loading-purple.gif) no-repeat center} .loading > div{display:none} Here is a sample image that could be used. Too easy. However, this is old school. You can create a simpler one using CSS and HTML5. Here is the CSS: .loading-container{display:block;width:100%;min-height:45%;margin-top:60px;text-align:center} .loader {margin:0 auto;text-align:center;width:200px;min-height:100%;display:block;vertical-align:middle} .loader:hover{opacity:1} .loading-spinning-bubbles{position:relative;margin:auto;min-height:1px} .loading-spinning-bubbles .bubble-container {position:absolute;top:calc(50% - 10px/2);left:calc(50% - 10px/2);transform-origin:-150% 50%;-webkit-transform-origin:-150% 50%;-moz-transform-origin:-150% 50%} .loading-spinning-bubbles .bubble-container .bubble {background:#00ac00;width:10px;height:10px;border-radius:50%;animation:bubble 1s infinite;-webkit-animation:bubble ...

Web API: How do I clean up the data in my HttpResponse?

There are some very simple web.config settings that can be applied to reduce the amount on unnecessary data returned in an HttpReponse and to minimise ways that hackers can hijack system information. Here is a quick snippet of web.config settings that may be useful. <Config> <system.web>  <httpRuntime enableVersionHeader="false" /> </system.web> <system.webServer> <httpProtocol>  <customHeaders> <add name="Strict-Transport-Security" value="778000; includeSubdomains" /> <add name="X-Content-Type-Options" value="nosniff" /> <add name="X-Permitted-Cross-Domain-Policies" value="none" /> <add name="X-XSS-Protection" value="1; mode=block" /> <add name="Cache-Control" value="no-store" /> <add name="Pragma" value="no-cache" /> <remove name...

C#: What is the difference between IQueryable vs IEnumerable?

The main difference between the two is the location of the query execution. The following example demonstrates the difference: IQueryable<Model> models = ... models.Where(x => x.ID ...) IQueryable is used from LINQ-to-Anything (such as SQL). In this case, the query filter will be executed on the SQL server. This is great for reducing the amount of data returned from the data store. However, if the code looks as follows: IEnumerable<Model> models = ... models.Where(x=> x.ID ...) The results might be the same but using IEnumerable will cause the query results to be loaded in the memory and the predicate will be executed on the entire result set.

C#: How can I get my Selemium test to log into Azure?

I have been writing some entry level Selenium tests for my Azure website that authenticates using Azure AD. The biggest issue is trying to get the WebDriver to authenticate into the solution. After a lot of learning (read: failed attempts) I have the following solution (read: hack) that seems to work. 1. In my [TestInitialize] method, I load JQuery to the created page public static class Common     {         public static string GetEval(IWebDriver driver, string script)         {             IJavaScriptExecutor js = driver as IJavaScriptExecutor;             return (string)js.ExecuteScript(script);         }         public static string GetFile(string path)         {             using (var reader = new StreamReader(path))             {   ...

CSS: How do I create a single 'back to top' button?

A little CSS and JQuery can produce a lot of magic in an application. Here is the code. 1. Start with a simple html page. The important item here is to have an 'ID' to navigate to. In my case, I called it 'top'. <html> <head>     <base href="/" />     <title>Test Page</title>     <meta charset="UTF-8" />     <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">     <meta name="viewport" content="width=device-width, initial-scale=1.0">     <script src=”//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js”></script>     <link href="css/myStuff.css" rel="stylesheet" /> </head> <body>     <div>         <!-- Start Body Content -->         <div ng-view role="main" id="top"></div>         <!-- End Body Content --> ...

SharePoint: Cannot file "Style%2520Library/Js/myfile.js"

I recent SharePoint deployment raised the interesting error about a missing file. When I checked the expected folder, the file was there so the error seemed a little strange. The solution is in the message: The missing file is Style %2520 Library. The cause was an incorrect link reference in the masterpage. The link was set to <SharePoint:ScriptLink Name="~SiteCollection/ Style%20Library /JS/myfile.js" runat="server" ID="ScriptLink2" /> SharePoint is url encoding the value. The encoded value of '%' is '%25', which results in the strange url. I removed the %20 from the link address and the issue was resolved.

HTML5: How do I store values in the session (and why is $cookie complaining about space).

It appears that there is a size limitation for angular-cookies - 4KB. Bummer. An alternative is to use the HTML 5 objects window.localStorage or window.sessionStorage. See  here  for details I used sessionStorage to hold a single object and an object array from a REST endpoint. The code to get and set the values is as follows: First, set the values: sessionStorage.Object1 = JSON.stringify(singleObject); sessionStorage.Object2 = JSON.stringify(multipleObjects) Now populate objects with the cached values: var single = JSON.parse($.parseJSON(sessionStorage.Object1)) var array = $.parseJSON(sessionStorage.Object2)

C#: Pass multiple values to a REST endpoint without having multiple parameters

Instead of passing the parameters to /REST.svc?param1=a&param2=b var items = new NameValueCollection(); items.Add("param1", "a"); items.Add("param2", "b"); var content = HttpPost("http://MyRestEndpoint", items); public static string HttpPost(string uri, NameValueCollection pairs)         {             byte[] response = null;             using (WebClient client = new WebClient())             {                 response = client.UploadValues(uri, pairs);             }             return System.Text.Encoding.UTF8.GetString(response);         } NOTE: You can quite easily inject a proxy using the following code: client.Proxy = new System.Net.WebProxy("myProxy", 1001);

AngularJS: Creating headers in an ng-repeat

I came across this great directive  here  to create headers based on sections in an ng-repeat. The cides works like a charm. Here is a copy. // html <div ng-repeat="item in data.items | orderBy:... | filter:... as filteredItems" header-list objects="filteredItems" header="getHeader">     <div ng-show="item.$header">{{item.$header}}</div>     <div>Your normal content</div>  </div> // controller function $scope.getHeader = function(item) {   return item.name.slice(0, 1); } // directive app.module("...").directive('headerList', function () {   return {     restrict: 'A',     scope: {       objects: '=',       header: '=' // This must be a function or instance method     },     link: function(scope) {       scope.$watch('objects', function() {         var lastHeader, currentHeader; ...

c#: How can I read / parse a JSON file?

I was tasked with iterating through the JSON results generated by a REST API. I looked at several options such as dynamic array = JsonConvert.DeserializeObject(jsondataasstring) but I finally ended on using  NewtonSoft.JSON  to parse the data. The code is as follows: // get the json data. in my case, I am reading it from a sample file from my MVC app using (StreamReader reader = new StreamReader(HttpContext.Current.Server.MapPath("~/App_Data/sample.json"))) {         json = reader.ReadToEnd(); } JObject jObj = JObject.Parse(json); // navigate to the area in the object tree that you require var messages = jObj["response"]["data"]["messages"]; // I now have a messages array that I can iterate through foreach(var item in messages) {   // Write out the property 'title'   Console.WriteLine(string.Format("The title is {0}", (string)item["title"])); }

Javascript: Why are my FileReader and JSON objects not defined in IE11?

I recently encountered this problem when referencing  FileSaver.js  in my project. The code worked in all browsers except Internet Explorer 11. This  post in StackOverflow helped me resolve the problem. The problem was caused by a meta tag forcing the browser to behave like IE 8. <meta http-equiv="X-UA-Compatible" content=" IE=8 "/> This is an issue as my HTML5 reference is now broken. A simple change resolved the problem. <meta http-equiv="X-UA-Compatible" content=" IE=edge "/>

How do I add additional logic to a input (buttons) click event?

Sometimes you need to add additional logic to a existing buttons 'click' event. The code to add extra logic to the item (without overwriting the existing code) is as follows: 1. Store the elements click event in a variable var clickEvent = $("input[id='MyButtonId']").click 2. Overwrite the existing 'click' function, but execute the saved clicked function. $("input[id='MyButtonId']").on('click', function() {  eval(clickEvent); MyNewSaveMethod();} );

API: How do I pass parameters to a REST API without including them in the QueryString? (Overcome penetration testing issues before they occur)

A recent penetration test of some API code showed that user information (such as an email address) was being displayed in the querystring. The API was: [HttpPost] [Route("api/MyAPIEndPoint")] public void DoSomething(string login, string email) { // stuff } A simple view of the endpoint with a browser would display the users details. The network tab in Chrome showed "api/MyAPIEndPoint?login=X12345&email=test@test.com". A new approach was required. The solution is to include the data in the body of the Request. The factory event is updated as follows: function DoSomething(login, email, success, failure) { var url = "/api/MyAPIEndPoint"; var parameter = { "Login": login,                 "Email": email }; return executePost(url, parameter, success, failure); } function executePost(url, parameters, success, failure) { var req = { method: 'POST', url: url, data: parameters }; $htt...

SharePoint Online: How do I run a Javascript update with a lookup on a NewForm.aspx or EditForm.aspx?

The requirement I faced with my SharePoint online project was to update fields on the new and edit forms once an item had been selected. The main problem was that the update required a lookup to existing data for each item in a multi select box. The obvious solution was to use  PreSaveAction  in a Script Editor webpart, The script looked something like this: <script type="text/javascript" src="//code.jquery.com/jquery-1.11.2.min.js"></script>          <script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/jquery.SPServices/2014.02/jquery.SPServices.min.js"></script> <script type="text/javascript"> var $j = jQuery.noConflict();  function PreSaveAction() {  function SetValue(onComplete) { // clear the target item $("textarea[id*='MyTargetField']").val(''); var listTitle = 'MyLookupList'; var ids = [];                 // get the items fr...

Angular: Redirecting to another location with query strings

There are a couple of ways to redirect to a new location: window.location.href / $window.location.href However, when using routing ($routeProvider), $location is the way to go. To navigate to another route: $location.path("/Search"); $location.replace(); To navigate to another route using query strings (such as ?k=test) $location.path("/Search").search('k', 'test'); To extract the query values, use  $location.search().k;

SharePoint: Urls in the virtual directories

While looking for the virtual location of the list of SharePoint masterpages (which is /_catalogs/masterpage/Forms/AllItems.aspx), I found  this  blog on MSDN outlining other useful folders. There post is replicated here. Site collection level recycle bin: /_layouts/15/AdminRecycleBin.aspx Site level recycle bin: /_layouts/RecycleBin.aspx Recreate default site sp groups: _layouts/15/permsetup.aspx Load document tab initial: ?InitialTabId=Ribbon.Document Delete user from Site collection (on-premises): /_layouts/15/people.aspx?MembershipGroupId=0 Display list in grid view. ‘True’ is case sensitive: ?ShowInGrid=True Quick Launch settings page: /_layouts/quiklnch.aspx Navigation Settings page: /_layouts/15/AreaNavigationSettings.aspx Sandboxed Solution Gallery: /_catalogs/solutions/Forms/AllItems.aspx Workflow history hidden list: /lists/Workflow History Filter toolbar for Lists and libraries: ?Filter=1 Site...

AngularJS: How do I create cascading lists?

I was looking for a cascading list solution and I found one  here  that almost gave me what I needed. I added a few tweaks to get my desired result. UPDATE: Be very careful with the items that are used in the filter. The filter is a string based comparison, so performing a filter on 'ID=1' will also return items for ID=10,ID=11 etc. My solution was to create two new properties: filterId and filterParentId. These are set to '<placeholder>ID<placeholder>'. For example, ###1###. You can then filter So, instead of searching for 1, you could search for ##1##, which would remove the unwanted results. My code is as follows: html:             <select class="form-control"                     ng-model="selectedParentItem"                     ng-change="parentchanged()"                  ...

SharePoint Search: How do I limit a search query to a specific site collection?

The url needs to be as follows (as per this entry ): http://localhost/_api/search/query?querytext='test+path:"http://localhost/subsite/"' The C# code the create the querystring is as follows: string searchRestUrl = "/_api/search/query?querytext='" + text + "+%2b+path:\"" + HttpUtility.UrlEncode(SiteUrl) + "\"'&rowlimit=5"; where SiteUrl is the full url for my site.