CHUVASH.eu
  • About
  • Search

Posts

May 28, 2017

Solpanelexperimentet

Ett litet projekt, ett experiment som jag håller på under min föräldralediga tid: Barnvagssolpanel. Jag har en liten solpanel på 10W som jag fäster på barnvagnen. Med den laddar jag mina batteripack, och med dem min mobil. Jag vill mäta hur mycket energi jag kan samla in under sommarensolpanel.jpg

Utrustning

Solpanel på 10W av märket Exibel köpt på Clas Ohlson. Den ska ge upp till 1,5A i direkt ljus. USB-doktorn. No-brand-produkt. Den visar spänning, ström, tid och kapacitet. USB-anslutningen är lite lös och kan glappa ibland. Den i sig förbrukar lite ström. Av någon anledning backar den flera mAh tillbaka efter man nått 3000 mAh varje gång man ansluter sladden igen. En svart powerbank från Clas Ohlson på 2600mAh = 9,62Wh. Blir laddad så fort solen skiner. I direkt solljus blir det 4,92v x 0,82A = 4W. En silverfärgad powerbank från Clas Ohlson på 3350mAh = 12,1Wh. Den fungerar mycket sämre, ofta laddar den inte alls, trots att den funkar från eluttaget. I skiftande strömförhållanden lägger den av. Är det på grund av någon elektronisk skyddspärr?

read more
June 13, 2016

My PowerShell Profile

Screen Shot 2016-06-13 at 20.52.26 It has been a while I last worked with PowerShell. I had my custom profile where I had my own prompt and some other customizations. Now I cannot find it anymore. I’ll start with the new one and I am saving it on my blog, so it will be easier to find in future: [code language=“powershell”] Function Prompt { $PromptData=“PS $($executionContext.SessionState.Path.CurrentLocation)$(’>’ * ($nestedPromptLevel + 1)) " $host.ui.RawUI.WindowTitle=$PromptData +’-’+(Get-Date).tostring() # .Link# http://go.microsoft.com/fwlink/?LinkID=225750 # .ExternalHelp System.Management.Automation.dll-help.xml } [/code] The prompt function comes from the scripting guy blog. To customize your profile, just open it in a text editor (in my case: code) [code language=“powershell”] code $profile [/code] Update 2018-04-10 You can also include these lines: [code language=“powershell”] $path1 = “C:\Program Files\Common Files\microsoft shared\Web Server Extensions\” $path2 = “15” Add-Type -Path “$path1\$path2\ISAPI\Microsoft.SharePoint.Client.dll” Add-Type -Path “$path1\$path2\ISAPI\Microsoft.SharePoint.Client.Runtime.dll” [/code] VS Code Now we can run VS Code to create ps1 scripts and run selections as we did it in PowerShell ISE.

read more
May 30, 2016

Update Field.JSLink using JSOM or REST

Today I have just a little code snippet to share. This code snippet shows how to update the JSLink property for an existing field using JSOM and REST. For REST I use sharepoint-utilities. [code language=“javascript”] var updateJsLinkCsom = function(config) { var ctx = SP.ClientContext.get_current(); var web = ctx.get_web(); var lists = web.get_lists(); var list = lists.getByTitle(config.listTitle) var fields = list.get_fields(); var field = fields.getByInternalNameOrTitle(config.fieldTitle) field.set_jsLink(config.jsLink) field.update() ctx.executeQueryAsync() }; var updateJsLinkRest = function(config) { SP.SOD.registerSod(‘sputils.js’, ‘/sputils.min.js’) SP.SOD.executeFunc(‘sputils.js’, ‘’, function() { var url = _spPageContextInfo.webAbsoluteUrl + ‘/_api/web/lists/getbytitle(\’’ + config.listTitle + ‘\’)/fields/getbyinternalnameortitle(\’’+ config.fieldTitle + ‘\’)’; var payload = {’__metadata’: {’type’: ‘SP.Field’}, ‘JSLink’: config.jsLink}; var config = {‘headers’ : {‘X-HTTP-Method’: ‘MERGE’ }}; sputils.rest.post(url, payload, config); }); }; var config = { listTitle: ‘’, fieldTitle: ‘’, jsLink: ‘~site/’ }; updateJsLinkCsom(config); updateJsLinkRest(config); [/code] A couple of notes, to update a field we need:

read more
May 19, 2016

Trigger SP2010 Workflows using JSOM

Today I found out how to start workflows in JSOM (JavaScript Object Model in SharePoint). Nothing special, but since it is not documented, it took me a while to find a solution. Here is the code which I want to keep as simple as possible. What you need to start a SP2010 Workflow for a list item or a document in JSOM, you need to load SP.WorkflowServices.js and you need to create the manager and get the service, then you can trigger a workflow using the workflow name, the list guid and the guid of the list item: [code language=“javascript”] var ctx = SP.ClientContext.get_current(); var workflowServicesManager = SP.WorkflowServices.WorkflowServicesManager.newObject(ctx, ctx.get_web()); var service = workflowServicesManager.getWorkflowInteropService(); service.startWorkflow(workflowName, null, listGuid, plainItem.guid, initiationParams); [/code] Here is the code to trigger a workflow for multiple items: [code language=“javascript”] //fire the workflows function fire2010WorkflowForListItems(ctx, listGuid, plainItems) { var workflowServicesManager = SP.WorkflowServices.WorkflowServicesManager.newObject(ctx, ctx.get_web()); var service = workflowServicesManager.getWorkflowInteropService(); for(var i = 0; i < plainItems.length; i++) { var plainItem = plainItems[i]; console.log(‘scheduling workflow for id: ‘, plainItem.id); service.startWorkflow(options.workflowName, null, listGuid, plainItem.guid, options.initiationParams); } console.log(’now executing…’); ctx.executeQueryAsync(function() { console.info(‘yes, workflows completed for ’ + items.length + ’ items’); }, function() { console.error(‘it didnt go well’); }); } [/code]   The code above is inspired from this gist and sharepoint stackexchange. It is a simplified version that only works for list item workflows and SharePoint 2010 workflows. Here is an example how you can get multiple items and batch start a workflow: [code language=“javascript”] //just a couple of variables var options = { workflowName: ‘Behörigheter’, listName: ‘Documents’, initiationParams: {} }; //load list items function startWorfklows() { //Start 2010 Workflow for a List Item var ctx = SP.ClientContext.get_current(); var web = ctx.get_web(); var lists = web.get_lists(); var list = lists.getByTitle(options.listName); ctx.load(list); var items = list.getItems(new SP.CamlQuery()); ctx.load(items); ctx.executeQueryAsync(function() { var listGuid = list.get_id() + ‘’; var en = items.getEnumerator(); var plainItems = []; while (en.moveNext()) { var it = en.get_current(); //do not take checked out files, it won’t work if (!it.get_item(‘CheckoutUser’)) { plainItems.push({id: it.get_id(), guid: it.get_item(‘GUID’) + ’’ }); } } fire2010WorkflowForListItems(ctx, listGuid, plainItems); }, function() { alert(‘boom’); }); } //Load Worfklow Js dependency var wfScript = ‘SP.WorkflowServices.js’ SP.SOD.registerSod(wfScript, _spPageContextInfo.webAbsoluteUrl + ‘/_layouts/15/SP.WorkflowServices.js’); SP.SOD.executeFunc(wfScript, ‘’, startWorfklows); [/code]

read more
May 15, 2016

Create and download a file in javascript

Phew, I spent a lot of time to get this to work:

  • Create a text based file in javascript - a simple csv or txt
  • Download a file in Chrome and Internet Explorer
  • Make Excel understand Unicode characters (å ä ö and many more) in csv directly.

I found many solutions on the Internet that I used to find out a solution that works for me A deep diving jsfiddle about unicode encodings, bom, line endings: http://jsfiddle.net/kimiliini/HM4rW (unfortunately, does not work in IE). There I learned one important thing: we need a BOM in order to make Excel understand that it is not just ASCII. The BOM (byte order mark) for utf-8 is %ef%bb%bf for utf-8. Without this bom you’ll see the right characters in a text editor (except Notepad of course), but if you open the csv file directly in Excel, you’ll see wrong letters. Other good resources are FileSaver.js: https://github.com/eligrey/FileSaver.js and download.js: http://danml.com/download.html and a discussion on that github repository issue: https://github.com/mholt/PapaParse/issues/175 This is my solution that is tested in Chrome and IE10: [code language=“javascript”] function downloadContent(options) { if (!options || !options.content) { throw ‘You have at least to provide content to download’; } options.filename = options.filename || ’tolle.txt’; options.type = options.type || ’text/plain;charset=utf-8’; options.bom = options.bom || decodeURIComponent(’%ef%bb%bf’); if (window.navigator.msSaveBlob) { var blob = new Blob([options.bom + options.content], {type: options.type }); window.navigator.msSaveBlob(blob, options.filename); } else { var link = document.createElement(‘a’); var content = options.bom + options.content; var uriScheme = [‘data:’, options.type, ‘,’].join(’’); link.href = uriScheme + content; link.download = options.filename; //FF requires the link in actual DOM document.body.appendChild(link); link.click(); document.body.removeChild(link); } } //test var separator = ‘;’; downloadContent({ type: ’text/csv;charset=utf-8’, filename: ’tolle.csv’, content: [‘ASCII’, separator, ‘Åbäcka sig’, separator, ’to się podoba: żźćąęłć’, separator, ‘Яшлӑхӑма туйаймарӑм’].join(’’) }); [/code]

read more
April 27, 2016

Minimal Download Strategy. Simple

There are many correct ways (1, 2, 3, 4, 5…) of making scripts work with the Minimal Download Strategy Feature (MDS) in SharePoint 2013 and 2016. But to be honest - every time I need it, I get confused. So now it is time to find a simple solution for that. Who is better at it than the developers of the SharePoint themselves? Look at the MDS code in the built-in Display Templates: mds-001 Let’s keep it as simple as Item_Default.js, let’s take it as it is and create our own scripts. Here is a skeletton of and MDS-ready script: [code language=“javascript”] function runMyCode() { var time = new Date().toISOString(); console.log(‘runMyCode’, time ); } runMyCode(); if (typeof(RegisterModuleInit) == ‘function’) { var scriptUrl = ‘/Style Library/runMyCode.js’; RegisterModuleInit(scriptUrl, runMyCode); } [/code] Which boils down to this in pseudocode:

read more
April 13, 2016

Minimal Display Template

We want to use our own Display Templates on Non-publishing sites - our team sites. Without the Publishing Feature activated you have to create an own javascript file. Here is short and concise instructions how to install it: Display Templates on Non-publishing Sites. As described on that blog, you can make copy of an existing Item_Default.js and adjust to your needs. I also asked Elio Struyf and I got the same tip. I did create my starter template. Here I want to share this very minimal javascript based Display Template. The real Minimal Display Template is in the SPCSR github repository: Item_Minimal.js It has been improved by Elio Stuyf himself :) [code language=“javascript”] (function () { // Config contains variables that are defined in one place var config = { propertyMappings: { ‘Path’:null, ‘Title’:[‘Title’] } }; var templateUrl; var register = function () { if (“undefined” !== typeof (Srch) && “undefined” !== typeof (Srch.U) && typeof (Srch.U.registerRenderTemplateByName) === “function”) { Srch.U.registerRenderTemplateByName(templateUrl, render); } }; render = function (ctx) { // Display template data var cachePreviousTemplateData = ctx.DisplayTemplateData; ctx.DisplayTemplateData = { ‘TemplateUrl’: templateUrl, ‘TemplateType’: ‘Item’, ‘TargetControlType’: [‘SearchResults’, ‘Content Web Parts’], ‘ManagedPropertyMapping’: config.propertyMappings }; var cachePreviousItemValuesFunction = ctx.ItemValues; ctx.ItemValues = function(slotOrPropName) { return Srch.ValueInfo.getCachedCtxItemValue(ctx, slotOrPropName); }; // Retrieve managed property data var path = $getItemValue(ctx, ‘Path’); var title = $getItemValue(ctx, ‘Title’); // HTML markup for an item var htmlMarkup = String.format( ‘’ + ‘{1}’ + ‘’, path, title); // Caching ctx.ItemValues = cachePreviousItemValuesFunction; ctx.DisplayTemplateData = cachePreviousTemplateData; // Return the HTML markup return htmlMarkup; }; // Retrieve all the loaded scripts var allScripts = document.getElementsByTagName(“script”); // Get the last script file (this is the current DT file) var scriptUrl = allScripts[allScripts.length - 1].src; if (scriptUrl.indexOf(’/_catalogs/’) > 0) { // Remove the query string if (scriptUrl.indexOf(’?’) > 0) { scriptUrl = scriptUrl.split("?")[0]; } // Insert the site collection token templateUrl = ‘~sitecollection’ + scriptUrl.substr(scriptUrl.indexOf(’/_catalogs/’)) // Register the template to load register(); if (typeof (RegisterModuleInit) === “function” && typeof(Srch.U.replaceUrlTokens) === “function”) { RegisterModuleInit(Srch.U.replaceUrlTokens(templateUrl), register); } } })(); [/code]

read more
April 7, 2016

SharePoint Utilities - a promising JavaScript Framework

My colleagues at Bool have developed a new JavaScript framework for SharePoint - sharepoint utilities. It started on our DevDay last year - a whole free day when we could learn new things, try out new techniques or build something that was not even requested from a customer. I was not working on sharepoint utilities, so I almost forgot it until… I recently  re-discovered sharepoint utilities. It is on Github, it is MIT licensed and contributions are welcome. The core of sharepoint utilities (sputils) is a set of wrappers for Search, TermStore, REST that allow you be more productive as a developer. What I find especially compelling with that it contains some other fundamental stuff that every SharePoint developer needs:

read more
March 17, 2016

A tiny tool for User Custom Actions

hehyuaf Everybody loves User Custom Actions in SharePoint. That’s the only recommended way of customizing SharePoint. You have heard about it. Unfortunately there is no convinient way of administering them. People have their console applications or powershell scripts to add, update and delete user custom actions. It works but it is hard to open up Visual Studio or PowerShell every time you will try out an idea on a test site. To overcome this, I have created a tiny little tool, packaged as a bookmarklet for your browser. When you click on it, it will show your existing user custom actions and you can add new user custom actions. It is an ongoing little project, available on github, contributions are welcome. What’s left is:

read more
December 15, 2015

Provisioning Google Maps JSLink with SPMeta2

kartta-000

Among PnP Samples there is a solution for using Google Maps. Great solution where where you can pick a point on a map and define a spacial area on the map. Unfortunately it is a sandbox solution. I rewrote it to a code based template with SPMeta2 Framework. Now it can be installed on any site very easily, without needing UserCode Service and a cumbersome process of uploading a wsp package and activating it. The code is very simple, you can see it on github.

read more
  • ««
  • «
  • 8
  • 9
  • 10
  • 11
  • 12
  • »
  • »»
© CHUVASH.eu 2025