CHunky Universe of Vigourous Astonishing SHarepoint :)

Tag Archives: xml

Count lines of code with PowerShell

Today I got a question:

How many lines of code are there in our SharePoint solution?

After a little search, I found that PowerShell is really a nice tool to count lines of code:

I wanted to count lines for different types of code:

  1. Code Behind written in C#, the files have .cs file extension
  2. JavaScript code (except jQuery, angular or knockout frameworks)
  3. PowerShell files (.ps1 and psm1)
  4. Xml files (all the SharePoint .xml files)

Here is the powershell code that counts lines of code:

# go to the solution folder
cd <solution directory>

#count lines in .cs files
ls -include *.cs -recurse | select-string . | measure | select count

#count lines in our .js files
ls -include *.js -recurse `
    -exclude *min.js, jquery*, _*, jsrender*, CamlBuilder*, knockout* `
  | select-string . `
  | measure `
  | select Count

#count lines in our powershell scripts
ls -include *.xml -recurse | select-string . | measure | select count

#count lines in our powershell scripts
ls -include *.ps1, *.psm1 -recurse | select-string . | measure | select count

Just a curious fact, I can’t tell you how many lines of code we have in our solution, but I can reveal the proportions. If I used the flexible box model in css3, it would look like this:

lines of code

There are as many lines of code written in javascript as it is in C#. The main reason that for the big js code base are the SharePoint hosted apps. The PowerShell scripts are as big the javascript code base. Xml files are 4 times bigger than C# code, and it is even bigger than the sum of all lines of code written in C#, JavaScript and PowerShell. It isn’t strange that xml is dominating, almost everything in SharePoint is defined in xml.

Fortunately, there are less cases where you have to write raw xml in Visual Studio 2012/2013 and SharePoint 2013.

How does it look in your project? What language is dominating in your SharePoint project?

javascript: serialize as xml

Why should we need to serialize javascript objects as XML. I don’t know. It is of course more a server side need. And there actually a need for javascript serialization as xml in node.js.

To serialize as json is very simple: JSON.stringify(myobjects). I was just curious if there was a tool for xml serialization in javascript. There is a nice javascript tool called XMLWriter, developed by Ariel Flesler. Consider you have articles and want to serialize them as xml, let’s create a function for serializing:

function createProductXML(articles) {
  var v = new XMLWriter( 'UTF-8', '1.0' );
  v.indentChar = "  ";

  for(var a in articles) {
    var article = articles[a];
    v.writeElementString('number', article.number);
    v.writeElementString('description', article.description);
    v.writeElementString('price', article.price.toString());
    v.writeElementString('quantity', article.quantity.toString());

    for(var c in article.categories) {
      v.writeElementString('category', article.categories[c]);

  return v.flush();

And now we can test it:

var articles = [];
  name: "Ski", 
  number: "X21", 
  description: "The best ski for beginners", 
  summercollection: false, 
  wintercollection: true, 
  price: 20.5, 
  quantity: 20, 
  categories: ["winter", "snow", "fun", "beginner"]
  name: "Helicopter", 
  number: "T21", 
  description: "The best helicopter toy ever", 
  summercollection: true, 
  wintercollection: false, 
  price: 40, 
  quantity: 10, 
  categories: ["toy", "fly", "fun", "children"]
  name: "Book", 
  number: "B21", 
  description: "The best book ever", 
  summercollection: true, 
  wintercollection: true, 
  price: 100, 
  quantity: 5, 
  categories: ["reading", "education", "fun", "puzzle"]
var xml = createProductXML(articles);

The resulting xml is:

<?xml version="1.0" encoding="UTF-8" ?>
  <article summercollection="false" wintercollection="true">
    <description>The best ski for beginners</description>
  <article summercollection="true" wintercollection="false">
    <description>The best helicopter toy ever</description>
  <article summercollection="true" wintercollection="true">
    <description>The best book ever</description>

XMLHttpRequest the hard way

$.ajax is great, it hides much of the complexity. But sometimes we need to work with “raw” javascript 🙂 So let’s look behind the scenes. The XMLHttpRequest (or just XHR) is used to open a connection to a server without a page reload. Internet Explorer calls it ActiveXObject and it differs in IE versions. Wikipedia article gives a good example how to create one constructor for all browsers:

if (typeof XMLHttpRequest == "undefined")
  XMLHttpRequest = function () {
    try { return new ActiveXObject("Msxml2.XMLHTTP.6.0"); }
      catch (e) {}
    try { return new ActiveXObject("Msxml2.XMLHTTP.3.0"); }
      catch (e) {}
    try { return new ActiveXObject("Microsoft.XMLHTTP"); }
      catch (e) {}
    //Microsoft.XMLHTTP points to Msxml2.XMLHTTP and is redundant
    throw new Error("This browser does not support XMLHttpRequest.");

The remainder is more or less the same among the browsers. We open a connection defining the HTTP verb, URI and async mode (true or false):

var xhr = new XMLHttpRequest();"GET", "/_vti_bin/listdata.svc", true);
xhr.onreadystatechange = onStateChange;

Pay attention to onreadystatechange (only lower case letters). If we choose async=false, the UI waits for the response which is not so kind to users, but maybe it is easier to write a program. Well, there is actually no option but to have async=true.

To provide the callback for success and error we can write the responding function onreadystatechange. This function will be called every time the state is changed. There are 5 states:

0 = uninitialized
1 = loading
2 = loaded
3 = interactive
4 = complete

The state 4 “complete” and status 200 (OK) means success.

function onStateChange() {
  if (xhr.readyState == 4) {
    if (xhr.status == 200) {
      response = xhr.responseText;

This onreadystatechange is actually cool stuff. It helps to understand how ajax actually works, and how jQuery “is talking” to browser in order to partially load data. The onreadystatechange callback function opens even new opportunities. What if you want to show a spinner when the data has began to load? Very simple. Let’s just add a couple of code lines to our onStateChange function. When the state is 1 (loading) – show, when 4 (complete) – hide. Suppose we have a spinner object already:

function onStateChange() {
  if (xhr.readyState == 1) {
  if (xhr.readyState == 4) {
    if (xhr.status == 200) {
      response = xhr.responseText;

By the way, if you must parse XML from response, check out this blog post by Santosh

Sys.Web.Request (Update 2013-03-05)

In ASP.NET there is a wrapper for this: Sys.Web.Request. I found it in a question on SharePoint stackexchange. Here is a simple example without any error handling, without any parameters, just to show how to invoke the Sys.Web.Request:

function onCompleted(response, eventArgs) {
    var results = response.get_responseData().d.results;
var url = "the actual url";
var request = new Sys.Net.WebRequest();
request.get_headers()["Accept"] = "application/json";


Another way to make an ajax call is to use SP.RequestExecutor which is javascript utility available in SharePoint 15 (maybe not only 15?) under /_layouts/15/sp.requestexecutor.js. I found this thanks to a question on SharePoint StackExchange: Upload a non-text as an attachment using SharePoint 2013 REST API. I mentioned it in my other post: REST API: Add a plain text file as an attachment to a list item:

var request = new SP.RequestExecutor("/");
	url: "MY URL",
	method: "GET"

Ändra content i ContentEditorWebPart

Det finns ett exempel här.

//defaultAspx är sidan (SPListItem i Sidor)
//måste checkas ut först
//mgr är WebPartManager
//wp är contentEditorWebPart
web.AllowUnsafeUpdates = true;
XmlDocument xmlDoc = new XmlDocument();
XmlElement xmlElement = xmlDoc.CreateElement("Content");
xmlElement.InnerText = ((Microsoft.SharePoint.WebPartPages.ContentEditorWebPart)wp).Content.InnerText.ToString();
xmlElement.InnerText = xmlElement.InnerText.ToString().Replace("#HEADING#", "Welcome for welcome");
wp.Content = xmlElement;
web.AllowUnsafeUpdates = false;

Man måste skapa nytt XmlDocument och XmlElement, om man försöker skriva direkt till wp.Content.InnerText kommer det inte uppdateras. I det här fallet, byter vi ut #HEADING# mot något mer passande.

Formatera export xml av wordpress

Ville spara min blogg som en dagbok för utskrift. Exporterade hela bloggen som xml. Inga problem. Sedan var det dock nästan omöjligt att enkelt skriva in det i Word / OpenOffice.

Jag har skrivit en liten css-fil som formaterar det lite så att man kan skriva ut.

Lägg till:

<?xml-stylesheet type = "text/css" href="wordpress.css"?>

direkt efter:

<?xml version="1.0" encoding="UTF-8" ?>

Lägg filen “” i samma mapp.

Här är wordpress.css

channel title {
channel description {
item title {
creator {
creator:before {
 content:"Skrivet av: ";
post_date:before {
 content:"Datum: ";
comment {
comment_author:before {
 content:"Kommentar av: ";
comment_author {
comment_date:before {
comment_date:after {
/* Ska inte visas*/
link, channel language, pubDate, 
guid, author, base_site_url, 
base_blog_url, wxr_version, generator,
post_id, is_sticky, post_type, post_name, 
status, comment_status, menu_order, 
post_parent, ping_status, post_date_gmt, 
category, postmeta,
comment_id, comment_author_email, 
comment_author_IP, comment_date_gmt, 
comment_approved, comment_type, 
comment_user_id, comment_parent {
/* block style */

title, description, post_date, comment {
Daniel Chronlund Cloud Tech Blog

News, tips and thoughts for Microsoft cloud fans

Вула Чăвашла

VulaCV - Чăвашла вулаттаракан сайт

Discovering SharePoint

And going crazy doing it

Bram de Jager - Architect, Speaker, Author

Microsoft 365, SharePoint and Azure

SharePoint Dragons

Nikander & Margriet on SharePoint

Mai Omar Desouki

PFE @ Microsoft

Cameron Dwyer

Office 365, SharePoint, Azure, OnePlace Solutions & Life's Other Little Wonders


Me and My doings!

Share SharePoint Points !

By Mohit Vashishtha

Jimmy Janlén "Den Scrummande Konsulten"

Erfarenheter, synpunkter och raljerande om Scrum från Jimmy Janlén

Aryan Nava

DevOps, Cloud and Blockchain Consultant


SharePoint for everyone


Ryan Dennis is a SharePoint Solution Architect with a passion for SharePoint and PowerShell

SharePoint 2020

The Vision for a Future of Clarity

Aharoni in Unicode

Treacle tarts for great justice

... And All That JS

JavaScript, Web Apps and SharePoint


Mostly what I know and share about...