Skip to main content

Posts

Showing posts from 2015

Node.js Looping and Async Calls: A Love Story

Problem :  I needed to create a node application that would ping a list of servers and return their status (if are they up or down).  All seemed easy enough until I needed to create asynchronous calls within a “for loop”.  The async method’s callback contained logic to simply build and return another object with the result data. Unfortunately, I couldn’t get ANY data back. Research :  After poking around some blogs and chatting with a coworker, I learned about node’s infamous “queue” of processes which fires AFTER my code finishes execution.  That is, when my “for loop” makes the async calls (let’s say, 5 times), the callback doesn’t fire until the end of my code is reached. Here’s what I initially coded: “returnObj” was serialized and written to the DOM well before the async callback was executed, writing a big, fat NOTHING to the browser.  This confused me for hours. What I needed to do was somehow write the response to the browser AFTE...

[Resolved] Sitecore ParseException: End of string expected at position...

Problem:  I have a line of code that uses Sitecore Fast Query to pull all items + children starting with a site item, like so: Item [] allItems = db.SelectItems( "fast:" + sitecorePath + "//*" ); Unfortunately, I would get a Sitecore parsing error at runtime: ParseException: End of string expected at position... Turns out Sitecore doesn't like hyphens ('-') in any sitecore path when using fast query, which I have a few distributor sites in a folder which contained hyphens. Solution: I create a simple method that resolves a sitecore path to be Sitecore fast query friendly:             string sitecorePath = "" ;             if (siteItem.Paths.FullPath.Contains( "-" ))             {                 String [...

SQL Server - Trim All Trailing "/" in a Table Column

Problem : Some of our redirects in our main web application were acting a little screwey. Turns out our stand-alone URL redirect app didn't play well with URLs with a trailing "/".  I needed to simply trim all trailing "/" from URLs that have them. Solution : Here's the script I created: BEGIN TRANSACTION        SELECT [url] AS ' url  with trailing "/"'        FROM    [URLRedirects] . [dbo] . [Redirects]        WHERE   RIGHT( [ url ] , 1 ) = '/'        UPDATE [Redirects]        SET     [ url ] = CASE RIGHT( [ url ] , 1 )                                          WHEN ...

Download a file directly to your "Downloads" folder without a dialog box

Problem: I built a custom web app and I wanted to download a log file directly to my downloads folder without a dialog . This app is only used by me and I specifically wanted all downloaded files in this location, no questions asked (by me, i guess) Research: I found many solutions that included a dialog box asking me where I want the file to be downloaded, but I wanted to bypass this process all together .  The key is this line of code: string pathUser = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile); I figured that getting the user would be hard to do, but this pretty much takes care of it. Solution: I added this to my dev tools.           protected bool SaveFileToDownloadsFolder(string fullFileName, string renamedFile)         {             string pathUser = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile);             stri...

Android http request crash fix executing getInputStream()

The Problem: In my Android app, I needed to make a simple call to a REST endpoint. I created a separate class extending the AysyncTask class like I am supposed to and as far as I was concerned, my code was clean and compiled just fine. Unfortunately, a runtime error occurred when getInputStream() was executed.  It jumped right to my “finally” block and the process ended suddenly. My Research: I added printStackTrace() to my finally block. When I caught and examined the stack trace, this is what I found: SecurityException: Permission denied (missing INTERNET permission?) The Solution: After extensive googling, I realized I needed to add a setting to my AndroidManifest.xml file:      <uses-permission android:name="android.permission.INTERNET" /> After running debugger, I finally made a successful htttp request. Here’s my code.      String json = "";          ...

Capturing Enter-key click event via Javascript (JQuery)

The Problem: The website I work on has a search submit button inherited on all pages.  Some pages have forms with submit buttons.  the result:  Enter-key click event chaos! Currently, when a user fills a form and clicks the enter key to submit it, the search box submit button is triggered rather than the form button. Therefore, user gets pissed. The Solution: I captured the enter key click event on page load and set what button to be triggered when enter-key is pressed.  If a form buttons is visible, click that submit button first.  If not, let the enter key trigger the search box submit button as usual. The Code: $(document).bind('keypress',function(e){ if(e.keyCode === 13) { var buttons = $('.continue-button:visible'); if(buttons.filter('#formSubmit').length > 0) buttons.filter('#formSubmit').click(); else if (buttons.filter('.next').length > 0) buttons.filter('.next').click(...

Large Data and JSONP - Dealing with IE's Cross Domain Headaches

The Problem: I created dynamic form generating application which sends form data (json object via JQuery ajax call) to an endpoint which then stores data to a database.  I’m using a third party service which appends more data to the object (company data by email address/IP address) which makes the object HUGE!  Posting the data to the endpoint works perfectly (Chrome and Firefox ), but IE, not so much.   Here’s the issues: The form generator app is used on cross-domain sites, which IE isn’t too happy about.   In other words, No Posting! JSONP works with GET requests, but the 2083 char limit in IE chops the request, resulting in No Transport or json call fail. Json = Error: jQuery was not called The Idea: What if I did the following: Create a new endpoint called “ThanksIE” Chop the json object every 1500 characters and sent multiple jsonp requests to  new endpoint. Each request will also have a similar guid, and index parameter ...

Return JSON straight up (not a string) in ApiController

The Problem: Had a hard time returning a plain JSON object from an ApiController (MVC4).  Instead, I'm getting the JSON object as a string. For example: "{\"dobSP\":\"90.25\",\"latestSP\":\"2025.9\",\"dobStampPrice\":\"0.15\",\"latestStampPrice\":\"0.49\",\"dobStampImage\":\"http://media1.s-nbcnews.com/j/msnbc/Components/Photos/051207/051207_stamp_news_hmed.grid-4x2.jpg\",\"latestStampImage\":\"http://media1.s-nbcnews.com/j/msnbc/Components/Photos/051207/051207_stamp_news_hmed.grid-4x2.jpg\",\"dataUpdated\":\"1/8/2015 11:27:48 AM\"}" What I've Learned: My Get method (in the controller) was specified to return a string object.  What I needed to return was a HttpResponseMessage type.   The Fix: I simply created a method that created the response for me:         private HttpResponseMessage ConvertToHttpResponse(string t...

Linq to DataTables - The Easy Way

The Problem: Couldn't easily read an excel file and query it programmatically. Using JSON.Net took a little longer than I thought it would. Wanted to brush up on my Linq skills. This was a rush job The Solution: Utilized "Excel Data Reader", which allowed me to read Excel data and converted it to a DataSet Used Linq to query the data easily, and produced manageable code (for me anyway) Used JSON>NET to serialize my code and write to the DOM Code Samples:             DataRow dr = ds.Tables[0].Rows.Cast<DataRow>()                 .Where(row => row["Column1"] == DBNull.Value)                 .FirstOrDefault(); In this example, I'm wrote a simple Linq query which returned all rows in the DataTable what has any data in the first column. Not the most sophisticated, but you get the point. What I've Learned: Origina...