Fiddler Script; default parameter value? - fiddler

Can't seem to find this on the docs anywhere, or on here.
I have a function;
static function Foo(oSession: Session, item1: String, item2: String)
Currently I call it like this;
Foo(oSession, "bar", null);
I would like to be able to omit the "null".
Thanks.

C# script is available in Fiddler now and luckily it compiles against .NET 4.0 so optional arguments are supported. So you have to switch to C#.

Related

Difference between "New-Object WindowsPrincipal([WindowsIdentity]::GetCurrent())" and "[WindowsPrincipal] [WindowsIdentity]::GetCurrent()"

I'm trying to check if Powerhell script is running as Administrator.
After searching the web, I got some sample code that works fine.
In order to get the WindowsPrincipal object, I found two sample code as below.
First:
New-Object Security.Principal.WindowsPrincipal([Security.Principal.WindowsIdentity]::GetCurrent())
Second:
[Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()
The second one made me confused.
According to this page, I know that the [ ] is a cast operator.
And according to this page, PowerShell is built on the .NET Framework. In my opinion, this means that the above two PowerShell scripts can be converted to C#.
So I try it.
When I convert the first PowerShell script to C#. It work fine as below.
## First PowerShell script
New-Object Security.Principal.WindowsPrincipal([Security.Principal.WindowsIdentity]::GetCurrent())
// C#
var wp = new WindowsPrincipal(WindowsIdentity.GetCurrent());
But when I try to convert the second PowerShell script to C#. I get compile error. The IDE tells me that WindowsIdentity cannot be cast to WindowsPrincipal.
## Second PowerShell script
[Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()
// both C# code below cause compile error
var wp = System.Security.Principal.WindowsIdentity.GetCurrent() as System.Security.Principal.WindowsPrincipal;
var wp2 = (System.Security.Principal.WindowsPrincipal)System.Security.Principal.WindowsIdentity.GetCurrent();
Just as I tried on C#, the System.Security.Principal.WindowsIdentity type cannot be directly converted to the System.Security.Principal.WindowsPrincipal type. But why is the second PowerShell script available?
Or is the [ ] operator in the second PowerShell script not a type conversion operator?
Maybe this operator do more than just convert object type?
What's the difference between first PowerShell script and second PowerShell script?
Did I missing any other things?
TLDR: PowerShell can do Magic. C# can't do Magic.
PowerShell can juggle Chainsaws, bowling pins, and balls at the same time.
C# can only juggle balls if they are defined ahead of time. Trying to add a new Chainsaw into the juggling routine causes the juggler(compiler) to complain.
The issues are the differences between Functions, Object types, and how to cast object types.
System.Security.Principal is the base .NET library. The library can be used by C# and PowerShell.
WindowsIdentity.GetCurrent() is a function in the library.
WindowsPrincipal is an object type e.g. like string or int.
Calling WindowsIdentity.GetCurrent() returns a WindowsIdentity object, which you can then use in your code.
Since WindowsIdentity is not necessarily the object type you want to work with, we want to use a WindowsPrincipal object. Unfortunately we cannot directly cast from WindowsIdentity to WindowsPrincipal object. We have to use the WindowsPrincipal constructor.
In PowerShell, you create a new object either by the New-Object cmdlet, or by simply using a variable for the first time. This convenience is because PowerShell is a scripting language, where using a variable e.g. $a = 1 implicitly creates a new variable. e.g.
PS C:\> Get-Variable test
Get-Variable : Cannot find a variable with the name 'test'.
At line:1 char:1
+ Get-Variable test
+ ~~~~~~~~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (test:String) [Get-Variable], ItemNotFoundException
+ FullyQualifiedErrorId : VariableNotFound,Microsoft.PowerShell.Commands.GetVariableCommand
PS C:\> $test = 1
PS C:\> Get-Variable test
Name Value
---- -----
test 1
Using the New-Object example:
New-Object Security.Principal.WindowsPrincipal([Security.Principal.WindowsIdentity]::GetCurrent())
This is the right way to do it. You are creating a new object of type WindowsPrincipal, and passing the Windows Identity to the constructor.
The second method:
[Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()
Is "wrong" because it uses casting, and earlier we stated that we cannot directly cast from WindowsIdentity to WindowsPrincipal object. So how does this work? Well, I said earlier that PowerShell does Magic, well I'll get to that in a minute. First let's see the correct C# Code:
Calling .NET Framework specific functions in C# do differ in Syntax than PowerShell. And the reason for the specific compile error you are getting is because we are trying to cast the object, which we can't.
The example:
using System.Security.Principal;
var wp = WindowsIdentity.GetCurrent() as WindowsPrincipal; // compile error
The Compiler translates it to:
WindowsIdentity.GetCurrent()
Run function GetCurrent()
as WindowsPrincipal;
Expect a return type of WindowsPrincipal <-- compile time error. The compile error is because the function does not return a type of WindowsPrincipal, instead it returns a type WindowsIdentity.
Second example is also a variation that doesn't work because it can't cast the object directly. e.g.
using System.Security.Principal;
var wp = (WindowsPrincipal) WindowsIdentity.GetCurrent(); // compile error
The Compiler translates it to:
WindowsIdentity.GetCurrent()
Run function GetCurrent() and return with the WindowsIdentity object.
(WindowsPrincipal) WindowsIdentity.GetCurrent();
Take the WindowsIdentity object and directly cast it to a WindowsPrincipal type, which it can't.
The correct C# code also needs the new keyword is:
var wp = new WindowsPrincipal(WindowsIdentity.GetCurrent());
The Compiler translates it to:
WindowsIdentity.GetCurrent()
Run function GetCurrent() and return with the WindowsIdentity object.
new WindowsPrincipal(WindowsIdentity.GetCurrent())
Create a new WindowsPrincipal object passing the WindowsIdentity object into the constructor. Which now works.
So why does the second example:
[Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()
Work in PowerShell by doing something that is "wrong"? Because PowerShell is a scripting language, and is interpreted on the fly, and can use Magic, it can interpret the above and perform some Type Conversion Magic Quote:
Direct assignment. If your input is directly assignable, simply cast your input to that type.
Language-based conversion. These language-based conversions are done when the target type is void, Boolean, String, Array, Hashtable, PSReference (i.e.: [ref]), XmlDocument (i.e.: [xml]). Delegate (to support ScriptBlock to Delegate conversions), and Enum.
Parse conversion. If the target type defines a Parse() method that takes that input, use that.
Static Create conversion. If the target type defines a static ::Create() method that takes that input, use that.
Constructor conversion. If the target type defines a constructor that takes your input, use that.
Cast conversion. If the target type defines a implicit or explicit cast operator from the source type, use that. If the source type defines an implicit or explicit cast operator to the target type, use that.
IConvertible conversion. If the source type defines an IConvertible implementation that knows how to convert to the target type, use that.
IDictionary conversion. If the source type is an IDictionary (i.e.: Hashtable), try to create an instance of the destination type using its default constructor, and then use the names and values in the IDictionary to set properties on the source object.
PSObject property conversion. If the source type is a PSObject, try to create an instance of the destination type using its default constructor, and then use the property names and values in the PSObject to set properties on the source object. . If a name maps to a method instead of a property, invoke that method with the value as its argument.
TypeConverter conversion. If there is a registered TypeConverter or PSTypeConverter that can handle the conversion, do that. You can register a TypeConverter through a types.ps1xml file (see: $pshome\Types.ps1xml), or through Update-TypeData.
Basically, whenever you do a type conversion in PowerShell, it will perform Magic and try each method to convert the type dynamically on the fly for you. That is why it can handle you throwing a new Chainsaw or bowling pin at the juggler. PowerShell can interpret that we aren't trying to convert a chainsaw into a ball, and instead that a chainsaw is just another object, and we already know how to juggle objects.
This interpretation isn't a part of .NET, and so C# can't do that, and we have to explicitly define everything, and do everything correctly. This means that you can convert all C# and .NET code into valid PowerShell code, but not the other way around.

What is [cmdletbinding()] and how does it work?

According to get-help about_Functions_CmdletBindingAttribute
The CmdletBinding attribute is an attribute of functions that makes them operate like compiled cmdlets
We can use it on the top of our scripts. What is the function in this case? An internal implicit "main" function called by the PowerShell engine for all its inputs?
Regarding this syntax:
[CmdletBinding(ConfirmImpact=<String>,
DefaultParameterSetName=<String>,
HelpURI=<URI>,
SupportsPaging=<Boolean>,
SupportsShouldProcess=<Boolean>,
PositionalBinding=<Boolean>)]
What are we doing? Instantiating a cmdlbinding object and passing an argument list to its constructor? This syntax can be found in param() - for example: [Parameter(ValueFromPipeline=$true)]. Does this syntax have a particular name, and can it be found elsewhere?
Lastly, are we able, as simple PowerShellers, to mimic this functionality and modify the behavior of scripts by setting an attribute?
Generally speaking, CmdletBinding is what makes a function into an Advanced function. Putting it at the top of a script makes the script an "advanced" script. Functions and scripts are much the same, where the script file name is equivalent to the function name and the script content is equivalent to the scriptblock section of a function.
CmdletBinding attributes give you control over function capabilities, such as adding Confirm and WhatIf support (via SupportsShouldProcess), Disable parameters positional binding, and so on.
CmdletBinding, Parameter etc. are special attribute classes that scripters can use to define PowerShell's behavior, e.g. make a function an Advanced function with Cmdlet capabilites.
When you call them via e.g. [CmdletBinding()] you initialize a new instance of the class.
Read more about the CmdletBindingAttribute class at: MSDN
Read more about the ParameterAttribute class at: MSDN
More about Attribute classes here and here
Regarding the syntax question, the format closely matches how you apply a .NET attribute class to a member using named parameters in C#.
Compare the (simplified) grammar for attributes from section B.2.4 of The PowerShell Language Specification with that from section C.2.13 of the C# Language Specification:
B.2.4 Attributes (PowerShell)
attribute: [ attribute-name ( attribute-arguments ) ]
attribute-arguments: attribute-argument attribute-argument , attribute-arguments
attribute-argument: simple-name = expression
C.2.13 Attributes (C#)
attribute: [ attribute-name ( named-argument-list ) ]
named-argument-list: named-argument named-argument-list , named-argument
named-argument: identifier = attribute-argument-expression
I agree it might have been nice from a sense of conceptual brevity to e.g. re-use hashtable initialization syntax for attribute initialization. However, I can imagine supporting all the options from hashtables (like [A(P=v)] and [A('P'=v)] and $n = 'P'; [A($n=v)] and such, or some particular subset of them) just to use ; as the separator character would have been more trouble than it was worth.
On the other hand, if you want to use advanced functions, then maybe it makes sense to learn an advanced syntax :)

scala play 2.0 get request header

I am converting some of my java code to scala and I would like to be able to get a specific header and return it as a string.
In java I have:
return request().getHeader("myHeader")
I have been unable to achieve the same thing in scala. Any help would be greatly appreciated! Thanks!
You could write:
request.get("myHeader").orNull
If you wanted something essentially the same as your Java line. But you don't!
request.get("myHeader") returns an Option[String], which is Scala's way of encouraging you to write code that won't throw null pointer exceptions.
You can process the Option in various ways. For example, if you wanted to supply a default value:
val h: String = request.get("myHeader").getOrElse("")
Or if you want to do something with the header if it exists:
request.foreach { h: String => doSomething(h) }
Or just:
request foreach doSomething
See this cheat sheet for more possibilities.
Accepted answer doesn't work for scala with playframework 2.2:
request.get("myHeader").getOrElse("")
It gives me the below error:
value get is not a member of
play.api.mvc.Request[play.api.mvc.AnyContent]
use below
request.headers.get("myHeader").getOrElse("")

javascript arguments are messed up when passed to NPAPI plugin function

I am using a simple NPAPI example from https://github.com/mikma/npsimple.
When I try to pass arguments from javascript to the NPAPI invoke function, the
parameters recieved by the NPAPI function are garbage, though argument count is
passed correctly. The following is the definition of the function in which I am trying to print the "args" array after converting them to char*:
invoke(NPObject* obj, NPIdentifier methodName, const NPVariant *args, uint32_t argCount, NPVariant *result)
Am I missing something here?
It is really hard to tell what you're trying to do based on what you have given us. Specifically, as smorgan requested, we need to know how you are trying to convert the args array to char*.
You are aware of how the NPVariant works? If it's a string, the NPVariant type will be NPVariantType_String and you will need to use both the UTF8Characters member of the NPString struct (which in turn is part of the NPVariant union) and the UTF8Length member, since the string may or may not be null terminated.
Also, keep in mind that depending on what you put in, it may or may not be valid to make your NPVariant a char*. If that helps, great; if it doesn't, please post the contents of the function in which you are trying to handle the input as well as the specific javascript calls that you are making. You haven't given us enough to work with to give you more than guesses as to what problem you may be having.

Xquery: Passing functions as argument

I'm working on an xml project in Xquery (using Exist) and I was wondering how I could achieve the following:
I want to create a function evaluate:
evaluate(argument, function)
argument here can be anything and should be compatible with the function.
function is a reference to a function.
some examples:
evaluate(6,nextPrime) -> newtPrime(6) = 7
evaluate("text",toCaps) -> toCaps("text") = TEXT
Is this or something very similar possible in Xquery? And if so, how?
Thank you in advance!
I couldn't tell you about exist, but MarkLogic has function pointers:
xquery version "1.0-ml";
declare function local:upper($str)
{
fn:upper-case($str)
};
let $function := xdmp:function(xs:QName("local:upper"))
return xdmp:apply($function, "blah")
Evaluating this returns BLAH.
dave was right similar support for higher order functions is found in Exist.
http://en.wikibooks.org/wiki/XQuery/Higher_Order_Functions
I did not use the exist mechanisms since QName only supports string literals and I could not achieve the dynamic behaviour I needed for my application.
Instead I used this trick:
declare function moviestat:call1($name, $param){
let $query := concat($name, "($param)")
return util:eval($query)
};
note that a generic function for any number of arguments can also be made
(but was not needed in application)