Garrett Serack: CardSpace and more... News Feed 
Friday, December 11, 2015  |  From Garrett Serack: CardSpace and more...


It took me a long time to actually start using PowerShell for my daily scripting tasks, mainly beacuse I was so damn good at CMD shell scripts, and it was such a hassle to learn to do everything differently.



However, as I worked more with PowerShell, I got to like it a lot, and now use it for virtually all my automation needs.



Daily dose of what’s wrong



A couple of big gripes come from the lack of a decent ternary operator in the language–which is a very terse way of cramming a whole if/else statement into a single expression:



A C# Example:



// The ugly, bloated mess
  string dude;
  if( age > 50 ) {
    dude = "Old Man"
  } else {
    dude = "Young Punk"
  }

  // Using a ternary, cleans up your code!
  var dude = age > 50 ? "Old Man"  : "Young Punk";


That time when someone tried to fix it with some duck-tape



Sadly, there exists no comparable feature in PowerShell. Searching the internets, I found an attempt to make something that is kinda the same:



From a blog post by Jeffrey Snover:



# ---------------------------------------------------------------------------
# Name:   Invoke-Ternary
# Alias:  ?:
# Author: Karl Prosser
# Desc:   Similar to the C# ? : operator e.g. 
#            _name = (value != null) ? String.Empty : value;
# Usage:  1..10 | ?: {$_ -gt 5} {"Greater than 5;$_} {"Not greater than 5";$_}
# ---------------------------------------------------------------------------
set-alias ?: Invoke-Ternary -Option AllScope -Description "PSCX filter alias"
filter Invoke-Ternary ([scriptblock]$decider, [scriptblock]$ifTrue, [scriptblock]$ifFalse) 
{
   if (&$decider) { 
      &$ifTrue
   } else { 
      &$ifFalse 
   }
}


Which lets one use a construct that looks like this:



dude =  (?:  {$age -gt 50} {"Old Man"} {"Young Punk"})


sigh … I’ll give high marks for terse, but … not really the same readability as a C-style ternary.



Hack like nobody is watching



I have made (in my ever-so-humble opinion) a far smarter way to accomplish the support of a Ternary in PowerShell.



Let’s take a look at some examples, and I’ll show the code to accomplish this at the end.




Simple, straightforward ternary



$x == ( 'a' -eq 'a' ) ? "yes" : "no"
echo "Result: $x"




Result: yes



How about if it’s false



$x == ('a' -eq 'b' ) ? "that would be not correct" : "of course they are not equal"
echo "Result: $x"




Result: of course they are not equal



More fun



$x == ('a' -lt 'b' ) ? ('a' -ne 'b') : ('a' -eq 'b' )
echo  "Result: $x"




Result: True



The other thing that’s missing from a PowerShell is a null-coalescing operator. In a c# example:



// An ugly, bloated mess
  var answer = SomeFunction();
  if( answer == null ) {
    answer = "not found";
  }

  // Using the null-coalescing operator:
  var answer = SomeFunction() ?? "not found";


Which offers a clean, tight and simple way of saying if the answer is null, then use this answer instead.
Maybe we can do the samething in PowerShell?



How much would you pay for a null-coalescing operator like C# ?



$z == $null ?? "This works!"
echo  "Result: $z"




Result: This works!



Of course, it still thinks like powershell so 0, false and $null are all still ‘negative’



$b == (1 +2 -3) ?? 100
echo  "Result: $b"




Result: 100



And regular numbers work nice:



$b == (1 +2 +3) ?? 100
echo  "Result: $b"




Result : 6



Let’s try some more complicated examples



function get-null { return $null }

function get-somevalue { return "SomeValue" }

function invoke-sample { 
    # this is what I've wanted for years!
    return = { get-null } ?? { get-somevalue } 
}

echo "Result: $(invoke-sample)"




Result: SomeValue



A slight variation



function invoke-sample { 
    # this is what I've wanted for years!
    return = ( get-null ) ?? ( get-somevalue )
}

echo "Result: $(invoke-sample)"




Result: SomeValue



What does this one do?



function invoke-sample { 
    # this is what I've wanted for years!
    return =  get-null  ?? ( get-somevalue ) 
}

echo "Result: $(invoke-sample)"




# perhaps not so surpising...
get-null



We can drop the pretenses; you should have a clue by now.



= $null ?? { "still" + "right" }




stillright



A couple more bits of fun:



echo (= 0 ? 100 : 200 )
echo (= 1 ? 100 : 200 )




200
100



Taking a peek behind the curtain



The ever-so-clever PowerShell enthusiasts will have probably guessed why this works.



It turns out that the power of PowerShell’s aliases is actually quite amazing, and when combined with a means
of evaluating a parameter-regardless if it’s an scriptblock or just a value
made it pretty simple to ‘extend’ assignment with an extra equal sign =



# ---------------------------------------------------------------------------
# Name:   Invoke-Assignment
# Alias:  =
# Author: Garrett Serack (@FearTheCowboy)
# Desc:   Enables expressions like the C# operators: 
#         Ternary: 
#             <condition> ? <trueresult> : <falseresult> 
#             e.g. 
#                status = (age > 50) ? "old" : "young";
#         Null-Coalescing 
#             <value> ?? <value-if-value-is-null>
#             e.g.
#                name = GetName() ?? "No Name";
# 			  
# Ternary Usage:  
#         $status == ($age > 50) ? "old" : "young"
#
# Null Coalescing Usage:
#         $name = (get-name) ? "No Name" 
# ---------------------------------------------------------------------------

# returns the evaluated value of the parameter passed in, 
# executing it, if it is a scriptblock   
function eval($item) {
    if( $item -ne $null ) {
        if( $item -is "ScriptBlock" ) {
            return & $item
        }
        return $item
    }
    return $null
}

# an extended assignment function; implements logic for Ternarys and Null-Coalescing expressions
function Invoke-Assignment {
    if( $args ) {
        # ternary
        if ($p = [array]::IndexOf($args,'?' )+1) {
            if (eval($args[0])) {
                return eval($args[$p])
            } 
            return eval($args[([array]::IndexOf($args,':',$p))+1]) 
        }
        
        # null-coalescing
        if ($p = ([array]::IndexOf($args,'??',$p)+1)) {
            if ($result = eval($args[0])) {
                return $result
            } 
            return eval($args[$p])
        } 
        
        # neither ternary or null-coalescing, just a value  
        return eval($args[0])
    }
    return $null
}

# alias the function to the equals sign (which doesn't impede the normal use of = )
set-alias = Invoke-Assignment -Option AllScope -Description "FearTheCowboy's Invoke-Assignment."


Now, go forth, and bring terseness and compaction to your scripts!


Friday, July 31, 2015  |  From Garrett Serack: CardSpace and more...


I’m not going to bore you with the mundane details of why it took so long to put this blog back online.



Suffice to say, at least I have a place I can do some blogging again.



Yay!


Friday, March 2, 2012  |  From Garrett Serack: CardSpace and more...

After playing with Windows8 a bunch yesterday, all I have is a scene from “The Princess Bride” running thru my head: Inigo Montoya: MY NAME IS INIGO MONTOYA! YOU KILLED MY START MENU! PREPARE TO DIE! [Inigo corners Count Rugen, knocks his sword aside, and slashes his cheek, giving him a scar just like Inigo's] [...]

Saturday, September 3, 2011  |  From Garrett Serack: CardSpace and more...

My pappy always used to tell me “There are three kinds of men: The ones that learn by reading. The few who learn by observation. The rest of ‘em have to pee on the electric fence.” … somedays, I’m surprised how often I get to pee on the damn fence. So, here I am writing [...]

Thursday, June 2, 2011  |  From Garrett Serack: CardSpace and more...

I’d like to introduce a new member of our team; Tim Rogers.   Tim is a new full time employee at Microsoft who started this week, and as he just found out yesterday (his first day in the office), is going to be working as a full-time test resource for CoApp.   Tim has a [...]

Monday, May 9, 2011  |  From Garrett Serack: CardSpace and more...

  We’re nearing the point where we’re able to take open source projects and produce happy-shiny packages for them—uh yeah, nearing.  It’s gonna be a couple more weeks shaking out the tools that generate new Visual Studio project files for a given project and wire all that stuff up. The good news though, is that [...]

Wednesday, May 4, 2011  |  From Garrett Serack: CardSpace and more...

I’ll be in Canada tomorrow at the Vancouver Linux User Group meeting. I’ll be talking about Microsoft, Open Source and CoApp. If you are interested in showing up: Time: 7:30 PM-10 PM Where: iQmetrix offices 250 Howe Street – Suite 1210 Vancouver, BC V6C 3R8 CANADA I’d love to have ya’ll out! And, Pizza & [...]

Tuesday, May 3, 2011  |  From Garrett Serack: CardSpace and more...

It has been an extreme amount of time since I’ve done a status update—we’ve been working hard here, honest!  Under a stack of what seems like a million little things, blogging has taken a backseat to development in recent months, but I’m hoping to correct that (and have some others do some blog posts too!) [...]

Friday, April 29, 2011  |  From Garrett Serack: CardSpace and more...

I recently moved the CoApp source repositories from Launchpad to github, and I wanted make sure that I preserved all the commit history along with it. Fortunately, it’s not too terribly difficult to move from one to the other (provided you jump thru the hoops to getting fast-import working on bzr for Windows). Fixing Bzr [...]

Tuesday, April 26, 2011  |  From Garrett Serack: CardSpace and more...

Just a quick update today—we’ve moved the source repositories for CoApp from Launchpad to Github. While I liked a lot of the things about Launchpad, the website is feeling slower and slower some days, and Bazaar, while offering the features that I like, isn’t getting the attention (and developer resources) that git is.  Combined with [...]

Wednesday, April 13, 2011  |  From Garrett Serack: CardSpace and more...

In my last post, I showed how we’re binding event handlers to the Task after it’s already been started. This of course, is probably not what you want, as it’s possible to lose some events if the task starts up quick enough. So, the CoTask task factory also lets you pass the event listeners as [...]

Wednesday, April 13, 2011  |  From Garrett Serack: CardSpace and more...

During the development of CoApp, I’ve enthusiastically embraced the .NET 4.0 Task Parallel Library (aka, the TPL).  It’s a set of APIs that make developers more productive by significantly simplifying the process of adding parallelism and concurrency to applications. I got religion around this last fall when I saw the PDC presentation that Anders Hejlsberg [...]

Thursday, April 7, 2011  |  From Garrett Serack: CardSpace and more...

(cross-posted from the mailing list) As I mentioned in my last post, CoApp’s design relies heavily on the use of Symbolic Links (symlinks)—a feature which is implemented fairly well in Windows Vista and beyond, but is missing in earlier versions of Windows. Cygwin tried to work around the limitation by using shortcuts (.LNK files), which [...]

Monday, April 4, 2011  |  From Garrett Serack: CardSpace and more...

(cross-posted from the mailing list) When CoApp packages are installed, they install into a predetermined location based on the package metadata—this ensures that all packages play by the rules, and allow us to use Windows features to support things side-by-side installation of applications (ie, havin’ two versions of the same application installed concurrently), and also [...]

Wednesday, March 23, 2011  |  From Garrett Serack: CardSpace and more...

The following is the instructions on how to build the current CoApp bits: 0. You need to have the following tools installed in order to build CoApp: Visual Studio 2010 (I’m told that VS 2010 Express will work) Windows SDK 7.0 or higher — http://bit.ly/bOoxJT Windows WDK 7.1 — http://bit.ly/cU1lvH Bazaar for Windows 2.2.0 — [...]

Wednesday, March 23, 2011  |  From Garrett Serack: CardSpace and more...

I’m moving to a new blog host right now… should have stuff up and running pretty quickly.   G

Thursday, December 9, 2010  |  From Garrett Serack: CardSpace and more...

<html xmlns="">

The question occasionally comes up regarding how to create Zip files from C# without using GPL (or LGPL) code.   If license isn’t an issue, the simple answer is always is to use ZipLib (http://www.icsharpcode.net/OpenSource/SharpZipLib/) which is a wonderful, and well known library for manipulating zip files.


The other solution is to grab WiX  3.5 (http://wix.codeplex.com/) and use the assemblies out of the WiX SDK:


Microsoft.Deployment.Compression.dll
Microsoft.Deployment.Compression.Zip.dll


Which contain the classes you’d need to manipulate zip files (and really easy to boot!)









test.cs

using System;
using System.IO;
using System.Collections.Generic;
using Microsoft.Deployment.Compression.Zip;

namespace TestZip {
public class Test {
public static void Main(string[] args) {
var zipFile = new ZipInfo("test.zip");
var filesToArchive = new List<string>() { @"test.exe", @"test.cs" };
zipFile.PackFiles(null, filesToArchive, null); //create the zip file
zipFile.Unpack(@".\testfolder\"); //unpack the zip file into a folder
}
}
}


 


Pretty simple, eh?

Thursday, July 29, 2010  |  From Garrett Serack: CardSpace and more...

(cross-posted from the mailing list)

It’s been suggested a few times over the last several weeks that CoApp won’t provide any value for the .NET community. With the emergence of several alternative projects to provide a form of package management (NPack, OpenWrap, nu-net, and others), I figured I’d better make some time to explain how CoApp and .NET get along.

 

Q: Isn’t CoApp about packaging applications?

A: Well, oddly enough, the original vision for CoApp was less concerned about actually installing applications, but rather installing shared components.  The ability to install an application comes by virtue that applications tend to be collections of components (shared or private), and a decent package management system should cover these goals easily. 

 

Q: If CoApp is such a great idea for .NET why is all the work focused on native applications ?

A: The reasons that our initial work that we’re doing is focused around native shared libraries and applications, is that they require quite a bit more adaptation to correctly work using modern C compilers and Side-by-Side technology. Once we’ve got the tools to build properly behaving projects to produce binaries that are useful in this fashion, we’ll be in a good place to actually produce packages themselves.

.NET Assemblies, by their very nature are already beautifully designed to be adapted into CoApp packages.  Strong-named assemblies install into the GAC—which is really just the .NET implementation of the Windows Side-by-Side technology--by design. CoApp .NET packages simply install the assemblies into the GAC, where all applications can share them in the way that was intended.

 

Q: What if I don’t want stuff to be in the GAC?

A: I’d ask you to reconsider.  I can appreciate the desire to maintain control over every aspect of building and distributing your application.  On the other hand libraries that designed to be shared shouldn’t require the consumer of the library to do anything, except for consume them.  The publisher of the shared library shoulders the responsibility of maintaining the library and publishing security updates as well new versions.  As with native Side-by-Side assemblies, the publisher can indicate what version of a library should be used when a particular version is requested.

 

Q: What possible reason should I choose using CoApp over another .NET package management ?

A: Well, like I’ve said, a plethora of implementations is always a good thing. From what I can see, most of the other package management systems are focused on assisting developers in getting simplified access to shared .NET components.  CoApp takes a larger scope, hoping to serve developers, end-users, and IT administrators alike.  Our design includes the ability to update any components without the necessity of shutting down or rebooting processes (or even god-forbid, the system itself).  CoApp is designed to apply to software regardless of the language it’s written in, from native (C,C++,etc) to managed code (.NET; C#, VB.NET, etc) ,to dynamic languages (Perl, Python, etc) and web apps (ASP.NET, PHP, and more).

 

Q: Why have you chosen MSI files rather than something simpler and more convenient (like Zip+Manifest)?

A: Oh, trust me, I really wanted to.  I realize that Windows Installer is kindof a bloated beast that has a lot of downsides; we’ve has chosen MSI as the packaging format because it is handles so many other situations very well--one noteable point, is that on XP & Windows 2003, the only way to install a native Side-by-Side components is by using MSIs. We’ve taken steps to lessen the burden by deliberately limiting the scope of what we are using in MSI to not encumber packages in a painful mess.

As well, by using MSIs we gain the ability to leverage things like group policies, Windows Logo certification, transactional installations, and trivial adoption by other non-CoApp consumers—there is nothing that would stop someone from using CoApp packages for some of their dependencies, and without having do anything other than install the MSIs.

 


Hey, rather than commenting here, come join mailing list (join the team at https://launchpad.net/~coapp-developers) and continue the conversation!

Thursday, July 29, 2010  |  From Garrett Serack: CardSpace and more...

(cross-posted from the mailing list)

It’s been suggested a few times over the last several weeks that CoApp won’t provide any value for the .NET community. With the emergence of several alternative projects to provide a form of package management (NPack, OpenWrap, nu-net, and others), I figured I’d better make some time to explain how CoApp and .NET get along.

 

Q: Isn’t CoApp about packaging applications?

A: Well, oddly enough, the original vision for CoApp was less concerned about actually installing applications, but rather installing shared components.  The ability to install an application comes by virtue that applications tend to be collections of components (shared or private), and a decent package management system should cover these goals easily. 

 

Q: If CoApp is such a great idea for .NET why is all the work focused on native applications ?

A: The reasons that our initial work that we’re doing is focused around native shared libraries and applications, is that they require quite a bit more adaptation to correctly work using modern C compilers and Side-by-Side technology. Once we’ve got the tools to build properly behaving projects to produce binaries that are useful in this fashion, we’ll be in a good place to actually produce packages themselves.

.NET Assemblies, by their very nature are already beautifully designed to be adapted into CoApp packages.  Strong-named assemblies install into the GAC—which is really just the .NET implementation of the Windows Side-by-Side technology--by design. CoApp .NET packages simply install the assemblies into the GAC, where all applications can share them in the way that was intended.

 

Q: What if I don’t want stuff to be in the GAC?

A: I’d ask you to reconsider.  I can appreciate the desire to maintain control over every aspect of building and distributing your application.  On the other hand libraries that designed to be shared shouldn’t require the consumer of the library to do anything, except for consume them.  The publisher of the shared library shoulders the responsibility of maintaining the library and publishing security updates as well new versions.  As with native Side-by-Side assemblies, the publisher can indicate what version of a library should be used when a particular version is requested.

 

Q: What possible reason should I choose using CoApp over another .NET package management ?

A: Well, like I’ve said, a plethora of implementations is always a good thing. From what I can see, most of the other package management systems are focused on assisting developers in getting simplified access to shared .NET components.  CoApp takes a larger scope, hoping to serve developers, end-users, and IT administrators alike.  Our design includes the ability to update any components without the necessity of shutting down or rebooting processes (or even god-forbid, the system itself).  CoApp is designed to apply to software regardless of the language it’s written in, from native (C,C++,etc) to managed code (.NET; C#, VB.NET, etc) ,to dynamic languages (Perl, Python, etc) and web apps (ASP.NET, PHP, and more).

 

Q: Why have you chosen MSI files rather than something simpler and more convenient (like Zip+Manifest)?

A: Oh, trust me, I really wanted to.  I realize that Windows Installer is kindof a bloated beast that has a lot of downsides; we’ve has chosen MSI as the packaging format because it is handles so many other situations very well--one noteable point, is that on XP & Windows 2003, the only way to install a native Side-by-Side components is by using MSIs. We’ve taken steps to lessen the burden by deliberately limiting the scope of what we are using in MSI to not encumber packages in a painful mess.

As well, by using MSIs we gain the ability to leverage things like group policies, Windows Logo certification, transactional installations, and trivial adoption by other non-CoApp consumers—there is nothing that would stop someone from using CoApp packages for some of their dependencies, and without having do anything other than install the MSIs.

 


Hey, rather than commenting here, come join mailing list (join the team at https://launchpad.net/~coapp-developers) and continue the conversation!

Saturday, July 17, 2010  |  From Garrett Serack: CardSpace and more...

I wrote this a couple years ago, and I ended up in a #cls10 session related to it, so I thought I'd post it unedited. Feel free to destroy it.


 


 


Idea:
    A self-regulating community meritocracy model for collaboration and cooperation.
   
    This can be applied to any type of collaborative organization where individuals efforts
    are rewarded when the organization benefits. Examples:
        Content Wikis : Wikipedia, etc
        Projects : Software development, etc.
        Organizations that work together for common benefit: ISO, ECMA, etc.
   
    This model is designed to significantly reduce the ability for a Pariticipant to game the
    system for self-benefit. (Examples of which: Attempts at ISO Vote stacking by MS)
   
Participants:
    Individuals - People who particpate in the community
    Organizations - Collections of associated individuals who are both responsible to the
                    organization and responsible for the organization's behavior.
                   
                    Organizations have the authority to grant some or all of their Achievement
                    benefits to a member Participant. (completey subject to the Organization's
                    philosophy)
   
Concepts:
    Action - An activity that a Participant is involved with:
        Contribution - a type of action that is adding to the value of the community,
        [Recognition|Transgression] - the recognition of an activity a pariticipant, filed by someone in the community
       
        Bill - a request for a policy change or ammendment to the fabric of the community
             --these are never negative, but the introduction of bills as a nusance can be considered anti-social
   
    Merit - a quantifiable contribution to the community
    Karma - a instantaneous measurement of a Participant's [value?] in the community
        - [short-term] karma - the value that represents a participant's [value] within the [time window]
        - [long-term] karma - the sum/eternal acheivement karma that is prior to the [time window]
    [Potential] - given the evaluation of past performance, the expected future value.
            - value is weighted in [time window] increments:
                current [time window] - 40%
                current -1 [time window] - 30%
                current -2 [time window] - 20%
                remaining [time window] - 10%

    [Time Window] - the length of time that is considered to be "right now" {~90 days?}
   
    [Achievement Level] - the state that a Participant holds inside the community.
                          there are four levels, each has a weight associated with it [name:weight]
        - [Fellow:10]   the highest level of achievement
                        considered fully trusted and can act on behalf of the community
                        unrestricted Contributions access.
                        only Individuals can be Fellows
                        By virtue of creating the community, founders tend to be fellows

        - [Trusted:6]   Considered extremely trustworthy
                        Contributions are assumed to be accepted, but is still placed in the [review queue]

        - [Associate:2] Proven record of positive actions to the community.
                        Contributions are publicly viewable, are required to be reviewed prior to acceptance
        - [Volenteer:1] Any member of the community without a proven track record.
   
        - [Owner:100]   NOT PART OF PUBLIC COMMUNITIES
            - Some Organizations may still require individuals that are granted 'super' status (ie, benevolent dictator)
            - Public communities should never have Owners.
           
    [Review Queue]  - Contributions that should be given a [Rating]
   
    [Rating] - Quantifiable examination of an Action
        - Intent:
            Positive - The community is not harmed by the contribution {hmm}
            Negative - The community is harmed by the contribution {considered anti-social}
        - Acceptance
            Excellent - This is a valuable addition to the community,
                        of a quality that requires no revision before acceptance
            Good      - This is a valuable addition to the community,
                        with feedback the contributor should evaluate prior to acceptance
                        but can be accepted without additional change
            [Almost]  - This is on the right track to being accepted,
                        with feedback to the contributor that must be rectified before acceptance is possible
                            (this may be a conversation, or a modification to the contribution)
            [Insufficient] - this contribution does not meet community standards for acceptance
                            The contribution rejected, and must be resubmitted.
        - Significance - the amount of Merit that the contribution has.
            [Extreme:10] - this is a crowning acheivement that has the highest level of benefit to the community
            [High:6] - this is very valuable to the community
            [Fair:2] - this is valuable to the community
            [Mild:1] - the value is low, but not zero
            [NoEffect:0] - the contribution does not actively add value to the community
        - Comments - constructive feedback on the contribution (no 'A+++ crap,' no 'stupid xxx')
       
    [Sponsor] - a Participant will have multiple Participants who are have acted to approve an acheivement promotion
                Sponsors are then required to act in the event of Negative Actions. Actions can be:
                    - Censure - a revocation of sponsorship
                    - Penalty/Counselling - Application of penalty to the participant's karma, and creating a
                                            conversation to correct behavior.
                    - Forgiveness - the sponsors can forgive the transgression, usually accompanied by
                                    a positive action on part of the participant.
                    - Defense - Sponsors can come to the defence of a Participant, which can potentially reverse
                                the 'negative' intent of the action; (may require approval by quorum)
               
                Because a participant has several sponsors; 
               
              - if a Sponsor fails to act, the lack of action can become a 'negative action' of their own

 Garrett Serack: CardSpace and more... News Feed 

Last edited Dec 7, 2006 at 10:16 PM by codeplexadmin, version 1

Comments

No comments yet.