Different behaviour for same code when in a powershell module vs directly in my script

I was having problems loading one of our DLLs that has references that need Newtonsoft.Json.dll version 8.0.0.0 or 6.0.0.0, but our assembly uses 9.0.1.0. This is not a problem with binding redirects in its app.config when used elsewhere in our solution, but it is when loading our binary in powershell to call one of its functions.

Following davidpodhola’s answer, I did exactly what he suggested in order to redirect Version=8.0.0.0 or Version=6.0.0.0 of Newtonsoft.Json.dll to version 9.0.1.0 which is the version we use in all our projects. We need to load that dll a few times in different scripts, so I made a powershell module in order to call a function which looks like this:

function LoadTfsToolsDll(
    [Parameter(Mandatory=$true)]
    [string] $pathToTfsToolsDll
    )
{
    Try
    {
        $parentFolder = Split-Path -Path $pathToTfsToolsDll
        $pathToNewtonSoft = [io.path]::combine($parentFolder, 'Newtonsoft.Json.dll')
        $newtonsoft = [reflection.assembly]::LoadFrom($pathToNewtonSoft) 

        $OnAssemblyResolve = [System.ResolveEventHandler] {
          param($sender, $e)

          # from:NewtonsoftJson, Version=8.0.0.0 or Version=6.0.0.0
          # to:  NewtonsoftJson, Version=9.0.1.0
          if ($e.Name -eq "Newtonsoft.Json, Version=8.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed") { return $newtonsoft }
          if ($e.Name -eq "Newtonsoft.Json, Version=6.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed") { return $newtonsoft }

          foreach($a in [System.AppDomain]::CurrentDomain.GetAssemblies())
          {
            if ($a.FullName -eq $e.Name)
            {
              return $a
            }
          }
          return $null
        }

        [System.AppDomain]::CurrentDomain.add_AssemblyResolve($OnAssemblyResolve)
    }
    Catch
    {
        throw [System.Exception]::new("Problem doing Newtonsoft.Json's binding redirect. See Inner exception.", $PSItem.Exception)
    }

    Try
    {
        Add-Type -Path $pathToTfsToolsDll
    }
    Catch
    {
        throw [System.Exception]::new("Problem loading TfsTools.dll. See Inner exception.", $PSItem.Exception)
    }
}

Export-ModuleMember -Function LoadTfsToolsDll

Unfortunately, importing the above module using Import-Module, and directly copying the above code at the top of my script (so it is ran first before using our assembly’s function) does not result in the same behaviour.

When having it written directly in my script, it is ran without exceptions, and I can then call my assembly’s function without any problem. However, when importing the module at the beginning of my script, no exception is thrown, but then when calling my assembly’s function I get the following exception, which was supposed to be fixed by my module’s code:

Exception calling "getSpecificBuildVNext" with "4" argument(s): "Could not load file or assembly 'Newtonsoft.Json, Version=8.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed' or one of its dependencies. The 
system cannot find the file specified."
At C:\Script\Test Run Scripts\Vision Tests\GCS Tests\Steps\InstallSC.ps1:70 char:4
+             $build = [TFS]::getSpecificBuildVNext('https://tfs.genete ...
+             ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [], ParentContainsErrorRecordException
    + FullyQualifiedErrorId : FileNotFoundException

What is the difference between both of those solutions, and how can I make it work with a powershell module instead of copying the same code several times in different scripts directly?

Why MemberExpression for child’s overridden property show parent’s property

Let’s assume we have 2 classes

class A{
   public abstract int Prop1 {get; set;}
}

and it’s child

class Child : A{
   [CustomAttr(someval)] 
   override public int Prop1 {get; set;}
}

so later in my code I need to get this custom attribute’s val.

bool haveCustomAttr(IExpression<Func<Child, int>> property){
    return ((MemberExpression)property.Body).Member.GetCustomAttributes(typeof(CustomAttr)).Any();
}

so when I call this code

haveCustomAttr(c => c.Prop1)

it’s return false because ((MemberExpression)property.Body).Member it’s for some reason A.Prop1 and not Child.Prop1

it’s possible to fix with more advanced construction like this

((MemberExpression)property.Body).Expression.Type.GetMember(((MemberExpression)property.Body).Member
                .Name)[0].GetCustomAttributes(typeof(CustomAttr), false).Any(); 

But it’s still not clear for me why it’s threat this expression as base class initially if it’s clearly say that it’s expression from Child class. Could someone explain logic behind this for me?

vbHow to get javascript value in asp.net?

How to get javascript value in asp.net?

I am using vb asp.net, javascript and html

When user click on ‘pay’ button in html code, than I will to run some code in javascript, than pass TokenHF.value in asp.net

issue is that: inside page_load() function, test TokenHF.value will be alway empty.
this is bc of on load function. any idea how to get TokenHF.value in asp.net?

vb asp.net code:

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
    Dim test = TokenHF.value
end sub

html code:

<asp:hiddenfield id="TokenHF" runat="server"></asp:hiddenfield>
<div id="card-number-element class="field"></div>
<div id="card-expiry-element" class="field"></div>
<div id="card-cvc-element" class="field"></div>
<input id="postal-code" name="postal_code" class="field" placeholder="90124" />
<button type="submit">pay</button>

javascript code:

<script>
    var stripe = Stripe('pk_test_982wyfu9sfdsf');
    var elements = stripe.elements();

    function setOutcome(result) {
        if(result.token){
            document.getElementById('<%= TokenHF.ClientID %>').value = result.token.id;
        }
    }

    document.querySelector('form').addEventListener('submit', function (e) {
        e.preventDefault();
        var options = { address_zip: document.getElementbyID('postal-code).value,
        };
        stripe.createToken(cardNumberElement, options).then(setOutCome);
    })
</script>

WebClient.UploadString does not give json

I am trying following code, but it gives me response string in HTML, but I want it in JSON.

string _sendGridAPIUrl = "http://localhost/MyServiceHost/Testing/TestService";
            string data = "{\"applicateRegionCode\":\"N\",\"MyID\":\"737\", \"sourceVersion\"=\"6\", \"DivisionName\":\"AE Name\",\"JobTaxName\":\"Test List\",\"Username\":\"jnam\",\"Schema\":\"TTT\"}";
            using (WebClient client = new WebClient())
            {
                client.Headers.Add("Content-Type", "application/json");
                client.Headers.Add("id", "13a94672-08k6-46a8-89cc-ba3217721504");
                client.Headers.Add("key", "354C5TA7-330D-40DC-8524-0000500DE654");

                var str = client.UploadString(_sendGridAPIUrl, data);

Trying Error Handling

I am trying to run a script where if there is an error I wan’t to write something and if there was no error write to host that everything worked.

Here is part of the script where I’m struggling with.

try { 
    New-VM -VMName "$Name"  -NewVHDPath "E:\Microsoft Hyper V\$Name\$Name.vhdx" -NewVHDSizeBytes $VHDSizeBytes -Generation $Generation  -SwitchName "$Switchname" -Path $VMPath | Out-Null
    Set-VMMemory -VMName "$Name" -DynamicMemoryEnabled $true -StartupBytes $MaxStartBytes
    switch (Read-Host "Type (Win10) For Windows 10 Iso file OR (Svr16) For Windows Server 2016"){
        'Win10' {Add-VMDvdDrive -VMName "$Name" -Path E:\ISO\Windows.iso }
        'Svr16' {Add-VMDvdDrive -VMName "$Name" -Path E:\ISO\14393.0.160715-1616.RS1_RELEASE_SERVER_EVAL_X64FRE_EN-US.ISO}
        default {Write-Host "No Such ISO" -BackgroundColor Black -ForegroundColor Red }
    }
    Write-Output (Write-Host "VM '$Name' Created Successfuly" -BackgroundColor Black -ForegroundColor Green )
}
Catch {
    Write-Output (Write-Host " Creation Of Virtual Machine '$Name' Failed!"  -BackgroundColor Black -ForegroundColor Red | Write-Error )
} 

What I need is to try everything between the { } and write “The VM Created successfully” , And if the VM Was not created successfully then write to host “The Creation Failed”.

I am hoping someone can understand what I’m trying to accomplish here.
Thank you in advance.

How to mark certain property as required in json content

I am writing an application where I do need to handle some scenarios beforehand in my controller class like certain property must have been provided otherwise status code would be BadRequest. Here is my class lookalike.

public class MyClass
{
   [Required]
   public IEnumerable<NewObject> NewObjects { get; set; }
}

public class NewObject : INewObject
    {
        public NewObject(string typeName, IEnumerable<Property> properties)
        {
            TypeName = typeName;
            Properties = properties;
        }

        [JsonProperty(Required = Required.Always)]
        public string TypeName { get; }
        public IEnumerable<IProperty> Properties { get; }
    }

public interface IProperty
    {
        string Name { get; }
        object Value { get; }
    }

Now though I have marked TypeName as required property and if I do not pass that in json content while sending request from swagger, json deserialization doesn’t fail. I tried to search but I got an answer that setting Required to Always should work.
Below is the Json Content I am passing through swagger:

{
  "NewObjects": [
    {
      "Properties": [
        {
          "Name": "string",
          "Value": ''
        }
      ]
    }
  ]
}

I wrote below piece of code too by looking at one of the solution:

var config = new HttpConfiguration();

            var jsonFormatter = config.Formatters.JsonFormatter;
            jsonFormatter.SerializerSettings.MissingMemberHandling = MissingMemberHandling.Error;
            config.MapHttpAttributeRoutes();

Still it’s not working:
Note: I am using Newtonsoft.Json version 11.0.1

This seems to be swagger issue because when I serialize input C# object and when again deserialize it, I am getting proper error.
For example in my controller class if I say:

var input2 = JsonConvert.DeserializeObject<MyClass>(JsonConvert.SerializeObject(input))

Then input2 throws an exception.

.NET Core API – Postman returning error on POST request

I’m learning .NET Core API Web from this tutorial: https://docs.microsoft.com/en-us/aspnet/core/tutorials/web-api-vsc

As in the tutorial says, I have a Model called TodoItems

I can send GET requests, but I cannot send any POST request to create a TodoItem to my API Web (please head to the “Use Postman to send a Create request” section from the tutorial link above)

I have done exactly as the tutorial, but I got the Unexpected “<“ error on Postman on POST request enter image description here

Please help.

RegEx: REPLACE REGEX to remove first character and everything after the last _ [duplicate]

This question already has an answer here:

I have this RegEx which Extracts word after removing the first letter a and everything after the last underscore “_”. I need to a same output but for “Replace” RegEx.

Input: asome test file-2_rev2.docx
RegEx: (?<=^a).+?(?=_.+?$)
Result: some test file-2

The code above works but an Extract. I need to be able to use a REPLACE RegEx. Basically the extract Regex put the result into a collection variable and I have to 5 more lines of code to get the value. The replace RegEx must be one liner like I posted. Any suggestion?

I tried below but i need to combine this into one

(^.*?(?=a)a)|[^_]+$

This (^.*?(?=a)a)|[^_]+$ gives me the file name but not removing the last underscore

Check new password against Active Directory history (and maybe it’s complexity policy)?

I have application which allows users to change their passwords. Those users are stored in Active Directory. On password change I need to apply password policies. Complexity policies are easy. But what if password has to differ to last 20 passwords for this user? Is anyhow possible to use AD user’s password history for this?

I know AD stores list of last about 20 passwords’ hashes for each user. Afaik it is not possible to retrieve that list. But is anyhow possible to ask AD if password is contained by that list? Or is possible to ask AD, if password is valid new password for particular user according to policies defined by AD configuration?

Move part of file to another file [on hold]

I have file with few lines:

Lines1

Lines2

Lines3

….

LinesN

I have following code:

My code

while ((line = streamReader.ReadLine()) != null)
{ 
    var str = GetData(line);
    if(str == "Fatal Error")
    {
    }
}    

During GetData I can throw some exception. In this case, I would like to move remaining lines to another file. How can I do this?
Should I declare positionCount? Or is there more smart way?