Powershell function to add script to the profile

I’m currently in the middle of learning powershell; More specifically, on day 4 of the Microsoft 10325a Automating Administration with Windows Powershell 2.0.

With my coding background, i’ve tended to write most of the script inside functions to try and promote reuse.  I’ve found that maintaining a library of functions to be a bit of a headache so ended up writing the function below.  It’s by no means perfect (lets face it, PoSH is a little new to me currently… lets see how long before v2 makes it onto my blog), but it does the job.

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
function Add-CodeToProfile() {
<#
.Synopsis
  Adds a code snippet to your PoSH user profile 
.Description
  Ideally, you will want to add whole functions, not just one line scripts.
.PARAMETER Scriptblock
  A block of script that you want to save for future reuse
.PARAMETER FileName  
  If specified, a file will be created to store the script in. 
#>
PARAM (
    [Parameter(Mandatory=$true)][string]$Scriptblock,
    [string]$FileName
)
    [string]$usersProfilePSdir = "$env:userprofile\My Documents\windowspowershell\v1.0\";
    [string]$usersProfilePS1 = $usersProfilePSdir + 'profile.ps1';
 
    if(-not(Test-Path "$env:userprofile\My Documents\windowspowershell")) {new-item "$env:userprofile\My Documents\windowspowershell" -type directory}
    if(-not(Test-Path "$env:userprofile\My Documents\windowspowershell\v1.0")) {new-item "$env:userprofile\My Documents\windowspowershell\v1.0" -type directory}
 
    if(-not(Test-Path $usersProfilePSdir)) {
        #Add PS1
        new-item $usersProfilePSdir -type file
    }
    else 
    {
        #Add a line break at the end of the file
        "`r`n" >> $usersProfilePS1;
    }
 
    #check filename
    if ($fileName -eq "") {
        #Add function to users profile
        $Scriptblock >> $usersProfilePS1
    }
    else {
        #Add function to new file
        $newScriptFile = $usersProfilePSdir + $fileName + '.ps1';
        $Scriptblock >> $newScriptFile;
 
        #Add reference to profile
        '"' + $newScriptFile + '"' >> $usersProfilePS1
    }
}

Tags:

Thursday, December 1st, 2011 Powershell No Comments

MIUI Android – Tasker Volume interaction problems

Having recently started putting community rom’s onto my Motorola Defy (tinkered with CyanogenMod and LiquidArc), I got a bit fed up with the LiquidArc rom and fancied a change; Queue the MIUI android rom.

I’m not going to go into the virtues of the rom, but needless to say it’s put my ICS angst on hold.

One issue i did come across was that Tasker wasn’t quite working correctly.  Whenever it came to change the system volumes the correct changes never got applied.  After googling it, there’s a few suggestions to change the “Third Party Access” setting in the call settings.  However in version 1.11.18 this setting doesn’t appear.

The correct solution is that the version of Superuser in the rom is particularly keen to deny the AllowPhone state permission.  All of the other versions of superuser that i’ve seen only control access to applications that specifically request root access.  This version doesn’t seem to have that limitation.Explicitly allowing Tasker to “Monitor Calls” means that it’ll once again be able to control the volumes.

Tags: , , , ,

Tuesday, November 29th, 2011 Misc 1 Comment

Json viewer for debugging in Visual Studio 2010

When  dealing with XML in Visual Studio, it’s really nice debugging it.  You hover over the variable and click XML Visualizer.

However, the same can’t be said for dealing with JSON.  So I went searching the extension library in Visual Studio 2010 where I’ve got a plethora of other useful tools (mainly around syntax highlighting.. no dice.

A quick google later, and i’ve downloaded http://jsonviewer.codeplex.com/.  Copying the dll’s to MyDocuments\Visual Studio 2010\Visualizers and i’ve now got a shiny new JSON viewer for debugging with.

 

 

Tags: ,

Thursday, November 24th, 2011 Misc No Comments

Phonegap OrientationChange event

Currently phonegap doesn’t support raising the orientationchange javascript event that gets fired by most browsers. The result for my mobile web application is that it works nicely in Safari on the iPad, but once wrapped up in phonegap it’s unable to detect the device orientation being changed.

In the phonegap roadmap the orientationchange is marked as being fixed this month, but until that happens i needed a workaround.

There are quite a few posts on various forums that suggest using various permutations of window.onresize event and changing the panel width manually with panel.setSize() or calling panel.setOrientation().

E.G.

1
2
3
window.onresize = function(event) {
  myPanel.setOrientation(Ext.getOrientation(), windows.innerWidth, window.innerHeight);
}

Unfortunately, it this code only works the first time the orientation is changed. For subsequent orientations, the event doesn’t fire.

 

The solution

After a couple of hours of tweaking and further searching i found this post, which details a solution which works perfectly.

1
2
3
4
5
6
7
8
9
10
    if(Ext.is.iOS && navigator.userAgent.match(/safari/i) == null) {
         Ext.EventManager.onWindowResize(function(){
               if(nativeAppOrientation != Ext.getOrientation()) {
                    var e = document.createEvent('Events');
                    e.initEvent('orientationchange', true, false);
                    document.dispatchEvent(e);
                    nativeAppOrientation = Ext.getOrientation();
               }
       }, this, {buffer: 500});
    }

Tags: , , , ,

Monday, October 24th, 2011 Javascript No Comments

Sencha touch : Ajax, Jsonp and scripttags

I started using the Sencha Touch javascript framework a number of weeks ago.  The basic plan for the application was to create a fully functioning web app, then using phonegap create a native iOS application.

The problem with this approach was that i ended up using Ext.Ajax.request to do all of the data calls without worrying about how phonegap would deal with ajax and the json objects that it was returning.  Needless to say the app didn’t work.  Any calls for data that go outside of the ipad are cross domain calls and need to be implemented with script and jsonp.

 Standard Ajax/Json request

1
2
3
4
5
6
7
8
9
10
11
12
13
14
function GetReportChartAjax() {
  Ext.Ajax.request({
    url: this.reportUrl,
    timeout: 180000,
    disableCaching: true,
    success: function (response, opts) {
      this.GetReportChartCallback(response);
    },
    failure: function (response, opts) {
      this.reportCarousel.setLoading(false);
      console.warn(response);
    }
  });
}

 

JSONP Request

1
2
3
4
5
6
7
8
9
10
11
12
13
14
function GetReportChartJsonp() {
  //Start a timer to handle the JSNOP request timing out.
this.jsonpTimeoutTimerId = window.setTimeout("JsonPRequestTimeoutCheck()", 30000); // for 30 sec
 
   var jp = Ext.util.JSONP.request({
     url: this.reportUrl,
     callbackKey: 'jsoncallback',
      scope: this,
    callback: this.GetReportChartCallback
    });
  }
function JsonPRequestTimeoutCheck() {
  Ext.util.JSONP.callback({ 'Success': false, 'Errors': ['Timed out'] });
}

 

Asynchronous JSONP : The Problem

Now the problem with using the JSONP class is that it’s a singleton.  So by moving from
Ext.Ajax.request to Ext.util.JSONP.request we’ve not only lost the timeout capability, we’re also lost the ability to make asynchronous calls.

If you google it, you’ll find that one suggested approach is to set current to null before each jsonp request. It’s certainly been my experience from using Sencha 1.1 that this doesn’t work.

 

1
2
//Doesn't work
//Ext.util.JSONP.current = null;

 

Asynchronous JSONP : The Solution

The solution is to use a store with a scripttag proxy. As all that’s actually happening is a scripttag being rendered to the page making the request, then you’ll be allowed as many calls as your browser can handle.

We then specify a callback parameter on the load method which allows us to interact with the actual response object rather than let the store fiddle with this json in preparation for it being wrapped up inside a data view.

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
function GetReportChartJsonpProxy() {
 
    var repStore = new Ext.data.Store({
      model: 'ReportImageResponse',
      proxy: {
        type: 'scripttag',
        url: this.reportUrl,
        reader: {
          type: 'json'
        },
        callbackPrefix: 'ReportCallback',
        timeout: 30000
      }
    });
 
    repStore.load({
      scope: this,
      callback: function (records, operation, success) {
        this.GetReportChartCallback(operation.response);
      }
    });
 
  }

Tags: , , ,

Monday, October 24th, 2011 Javascript No Comments

var myBlog = new blog;

Instantiating a new blog, now to actually do something with it.

Sunday, October 16th, 2011 Misc No Comments

Random musings from a man with too much time on his hands (so says my wife anyway).

Expect code snippets as and when i write something clever.

  • Twitter
  • LinkedIn
  • YouTube
  • Facebook
The opinions expressed on this site are my own and do not reflect the views of my employer, or any other party unless otherwise stated.