Tag Archives: JavaScript

Automated JS unit testing in VS Code

I love using VS Code, and i want to be more diligent about unit testing especially with JavaScript. There didn’t seem to be an obvious way to do this in VS Code, so I cobbled together a few resources that ended up working well. It does require you have node.js installed on your machine first, so get that then proceed.

By the way, for those of you familiar with unit testing this may seem remedial and possibly outdated. It’s new to me, and I don’t want to forget how I did this, so feel free to leave comments and contribute to me and other newcomers to JS unit testing what works for you and what you suggest should be done differently.

There are plenty of test suites and task runners, choose what works best for you. The key takeaway is we need a test suite and a task runner of some kind. For this I’m using QUnit and Karma.

With VS Code open to your project folder, open the terminal and run the following commands:

npm install karma --save-dev
npm install karma-qunit karma-phantomjs-launcher --save-dev
npm install -g karma-cli
npm install --save-dev qunitjs

Once those are done installing configure karma by running this command:

karma init karma.conf.js

Follow the prompts to configure how it will run. For automated testing ensure you answer “Yes” when it asks if you want to re-run tests when a file changes. It’s not like WebStorm where it waits a few seconds, sees no activity, auto-saves then runs the tests, but it will autorun if you save the file. Once finished run this command to launch the task runner:

karma start

That’s it, now when you write your JS tests they will autorun and display in the terminal whenever you save changes. Of course, you can also open the browser to your html file you make when building your tests, such as with QUnit. There are other browsers you can use as well, including PhantomJS for headless browser testing. Let me know what works for you!

Eric

Eric Oszakiewski is a professional software developer based in Scottsdale, AZ with over 35 years of IT experience, and 19 years Native American Gaming experience. He is currently working as a Sr .Net/SharePoint Developer for General Motors, and also as a consultant.

More Posts - Website

Follow Me:
TwitterFacebookLinkedInGoogle PlusYouTube

Know REST For the Query – SharePoint Saturday Phoenix 2014

Thank you for all who attended my session, below is the video. Big thanks to Becky Bohanon for enhancing the audio!

The slide deck is available here: Slide Deck

The JavaScript file that was used to do all of the REST calls is available here: demo.js

Eric

Eric Oszakiewski is a professional software developer based in Scottsdale, AZ with over 35 years of IT experience, and 19 years Native American Gaming experience. He is currently working as a Sr .Net/SharePoint Developer for General Motors, and also as a consultant.

More Posts - Website

Follow Me:
TwitterFacebookLinkedInGoogle PlusYouTube

Read a SharePoint list using JavaScript

There are countless ways to read data from a SharePoint list, and also myriad methods to do this in JavaScript, but I’m going to document this one way as a place to get started, and a published function I can refer back to if needed!

First consider the following: Reading SharePoint list data using JavaScript requires the SP.js file to be loaded already. So, we should be putting this function inside of a $(document).ready(function())}; and if needed inside an ExecuteOrDelayUntilScriptLoaded(functionName, ‘sp.js’); Once in there, it would look something like this:

function readFromList() {
    var query = new SP.CamlQuery();
    query.set_viewXml('');
    var clientContext = SP.ClientContext.get_current();
    var oList = clientContext.get_web().get_lists().getByTitle('List Name');
    var items = oList.getItems(query);
    clientContext.load(items);
    clientContext.executeQueryAsync(function () {
        if (items.get_count() > 0) {
            var enumerator = items.getEnumerator();
            while (enumerator.moveNext()) {
                var listItem = enumerator.get_current();
                var field = listItem.get_item('Field Name');
            }
        }
    }, function(sender, args) {
        console.log(args.get_message());
    });

I’ll go over each line to explain what’s happening:
var query = new SP.CamlQuery(); – this is preparing a CamlQuery object using SP.js (which is why it’s important to wait for it to be loaded!)
query.set_viewXml – Here’s where you define your CAML query using normal CAML syntax. In the above scenario, it will return the Title field from all items in the list.
var clientContext = SP.ClientContext.get_current(); – this establishes a client context object using the current Site Collection.
var oList = clientContext.get_web().get_lists().getByTitle(‘List Name’); – this creates an object that references the specific list in the specific web you wanted to pull items from.
var items = oList.getItems(query); – this is saying get the items from the list object based on the query defined above.
clientContext.load(items); – you’re now telling the object model to prepare to execute the following object by loading it into the client context.
clientContext.executeQueryAsync – ok, here you actually execute the query you so dutifully prepared just a moment ago. This operation expects a “Success” function and a “Failed” function to be passed in or referred to somehow. The success function will be what you want to do once the query is done executing. The failed function will be how you want to handle any issues.

In the above example, the success function looks like this:

if (items.get_count() > 0) {
            var enumerator = items.getEnumerator();
            while (enumerator.moveNext()) {
                var listItem = enumerator.get_current();
                var field = listItem.get_item('Field Name');
            }
        }

What this is doing is looping through the results of the query and reading each one. The key is, to read a field value the syntax is listItem.get_item(‘Field Name’). Again, lots of ways to read field data, especially system fields like ID, this is just one example.

To handle errors I simply have whatever the error message is log to the console. At this point you can do what you like with the resulting data: put it in a string array and read it later, push it out to the page, make decisions based on the results, etc. Hope this helps!

Eric

Eric Oszakiewski is a professional software developer based in Scottsdale, AZ with over 35 years of IT experience, and 19 years Native American Gaming experience. He is currently working as a Sr .Net/SharePoint Developer for General Motors, and also as a consultant.

More Posts - Website

Follow Me:
TwitterFacebookLinkedInGoogle PlusYouTube

SSRS 2008 functionality in IE9, IE10

Seems lately browsers update faster than the web solutions, or at least faster than we can update the web solutions to keep up with the browser changes. Maybe it’s just me…

Regardless, my company very heavily relies upon custom reporting. Since there were numerous changes in the way IE9 and IE10 render JavaScript DOM objects and other elements, things like SSRS and SharePoint start “breaking”. I recently handled an update enterprise-wide to IE9 by having to modify SharePoint 2010’s compatibility with IE9. Now I had to do it for SSRS, because things like the context menu drop downs on the report items were either invisible or unresponsive when clicked. unresponsive
Thankfully, Chris Snowden posted this response on StackOverflow.

Basically, you’ll need to replace your ReportingService.js file with this one. Click that link, save the file, and follow these steps:

  1. Open Windows Explorer and navigate to your server’s C:Program FilesMicrosoft SQL ServerMSRS10_50.MSSQLSERVERReporting ServicesReportManagerjs directory
  2. Make a backup copy of your existing ReportingServices.js file
  3. Copy this one into the same location. Make sure it’s named “ReportingServices.js”. Do not overwrite your old file just in case.
  4. Restart the SQL Server Reporting Services service on the server
  5. Clear your IE browser cache

That’s it! You should now be able to view the report item’s context drop down menu when clicked. Enjoy!
working

Eric

Eric Oszakiewski is a professional software developer based in Scottsdale, AZ with over 35 years of IT experience, and 19 years Native American Gaming experience. He is currently working as a Sr .Net/SharePoint Developer for General Motors, and also as a consultant.

More Posts - Website

Follow Me:
TwitterFacebookLinkedInGoogle PlusYouTube

SharePoint 2010 compatibility in IE9

SharePoint 2010 is not fully compatible with IE9. To the best of my knowledge this is due to SharePoint’s heavy dependency upon DOM expandos and other features which were available through IE8, but are all removed from IE9. Controls like the Rich TextBox and People Picker tend to render improperly, throw errors on postback, etc. Fortunately, M_Olson posted a JavaScript mod that worked perfectly for me! It looks like this:

function ConvertEntityToSpan(ctx, entity)
{ULSGjk:;    
if(matches[ctx]==null)
	matches[ctx]=new Array();    
var key=entity.getAttribute("Key");    
var displayText=entity.getAttribute("DisplayText");    
var isResolved=entity.getAttribute("IsResolved");    
var description=entity.getAttribute("Description");    
var style='ms-entity-unresolved';    
if(isResolved=='True')
        style='ms-entity-resolved';    
var spandata="";
spandata+="";    
if(PreferContentEditableDiv(ctx))    
{
    if(browseris.safari)        
	{
        spandata+="";        
	}        
	else        
	{
        spandata+="";        
	}    
}    
else    
{
    spandata+="";    
}    
if (browseris.ie8standard)
    spandata+="r";    
if(displayText !='')
    spandata+=STSHtmlEncode(displayText);    
else
    spandata+=STSHtmlEncode(key);    
if (browseris.ie8standard)
    spandata+="rr";    
else    
    spandata+="";    
return spandata;
}
// **** CUSTOM FUNCTION ****
function fixDataInIE9(data)
{    
	if(data.indexOf('') >= 0)    
	{    
		data = data.replace('', '');    
	}    
	return data;
}

Save that as a .js file in your /TEMPLATE/LAYOUTS/1033 path, then reference it at the very bottom of your Master Page, immediately before the two input elements like so:

<script type="text/javascript" src="/_layouts/1033/filename.js"></script>

<input type="text" name="__spText1" title="text" style="display:none;" />
<input type="text" name="__spText2" title="text" style="display:none;" />

Worked like a charm! There are other ways to do this, such as call it from a ScriptLink control, which also works. The key is to load the JavaScript file absolutely last, after all other content has loaded. At least this will give my company the chance to keep using SharePoint 2010 until we can migrate everything to SharePoint 2013.

Eric

Eric Oszakiewski is a professional software developer based in Scottsdale, AZ with over 35 years of IT experience, and 19 years Native American Gaming experience. He is currently working as a Sr .Net/SharePoint Developer for General Motors, and also as a consultant.

More Posts - Website

Follow Me:
TwitterFacebookLinkedInGoogle PlusYouTube