Thursday, 22 September 2016

How to pass named parameters with Invoke-Command




-ArgumentList is based on use with scriptblock commands, like:
Invoke-Command -Cn (gc Servers.txt) {param($Debug=$False, $Clear=$False) C:\Scripts\ArchiveEventLogs\ver5\ArchiveEventLogs.ps1 } -ArgumentList $False,$True
When you call it with a -File it still passes the parameters like a dumb splatted array. I've submitted a feature request to have that added to the command (please vote that up).
So, you have two options:
If you have a script that looked like this, in a network location accessible from the remote machine (note that -Debug is implied because when I use the Parameter attribute, the script gets CmdletBinding implicitly, and thus, all of the common parameters):
param(
   [Parameter(Position=0)]
   $one
,
   [Parameter(Position=1)]
   $two
,
   [Parameter()]
   [Switch]$Clear
)

"The test is for '$one' and '$two' ... and we $(if($DebugPreference -ne 'SilentlyContinue'){"will"}else{"won't"}) run in debug mode, and we $(if($Clear){"will"}else{"won't"}) clear the logs after."
Without getting hung up on the meaning of $Clear ... if you wanted to invoke that you could use either of the following Invoke-Command syntaxes:
icm -cn (gc Servers.txt) { 
    param($one,$two,$Debug=$False,$Clear=$False)
    C:\Scripts\ArchiveEventLogs\ver5\ArchiveEventLogs.ps1 @PSBoundParameters
} -ArgumentList "uno", "dos", $false, $true
In that one, I'm duplicating ALL the parameters I care about in the scriptblock so I can pass values. If I can hard-code them (which is what I actually did), there's no need to do that and use PSBoundParameters, I can just pass the ones I need to. In the second example below I'm going to pass the $Clear one, just to demonstrate how to pass switch parameters:
icm -cn $Env:ComputerName { 
    param([bool]$Clear)
    C:\Scripts\ArchiveEventLogs\ver5\ArchiveEventLogs.ps1 "uno" "dos" -Debug -Clear:$Clear
} -ArgumentList $(Test-Path $Profile)

The other option

If the script is on your local machine, and you don't want to change the parameters to be positional, or you want to specify parameters that are common parameters (so you can't control them) you will want to get the content of that script and embed it in your scriptblock:
$script = [scriptblock]::create( @"
param(`$one,`$two,`$Debug=`$False,`$Clear=`$False)
&{ $(Get-Content C:\Scripts\ArchiveEventLogs\ver5\ArchiveEventLogs.ps1 -delimiter ([char]0)) } @PSBoundParameters
"@ )

Invoke-Command -Script $script -Args "uno", "dos", $false, $true

PostScript:

If you really need to pass in a variable for the script name, what you'd do will depend on whether the variable is defined locally or remotely. In general, if you have a variable $Script or an environment variable $Env:Script with the name of a script, you can execute it with the call operator (&): &$Script or &$Env:Script
If it's an environment variable that's already defined on the remote computer, that's all there is to it. If it's a local variable, then you'll have to pass it to the remote script block:
Invoke-Command -cn $Env:ComputerName { 
    param([String]$Script, [bool]$Clear)
    &$Script "uno" "dos" -Debug -Clear:$Clear
} -ArgumentList $ScriptPath, $(Test-Path $Profile)


from: Stack overflow

Friday, 24 June 2016

Redirecting VS requests to services using fiddler

If you want to look at the traffic with Fiddler, you probably want to go the route of changing the machine.config file so that all .NET applications will send traffic through Fiddler. This helps you ensure that you capture data from processes running in services, etc. Also this is great way to save time when working with multiple services.

Expose call to fiddler 


At first we have to modify web.config by adding following.

<system.net>
      <defaultProxy
                 enabled = "true"
                 useDefaultCredentials = "true">
        <proxy autoDetect="false" bypassonlocal="false" proxyaddress="http://127.0.0.1:8888" usesystemdefault="false" />
      </defaultProxy>
    </system.net>
After this we can see requests from Visual Studio in our fiddler


Now we need to rewrite the requests

For this section we need to download  following plugin

http://www.telerik.com/download/fiddler/fiddlerscript-editor

In fiddler window is FiddlerScript tab usually on right hand side (unless you have changed it)


You can scroll or use search to find: "OnBeforeRequest". I have highlighted it for you on picture above.

Insert following snippet and modify it to what you want to use.


 // fiddler configuration to rewrite call to local instance of services
 if (oSession.HostnameIs("testservice.com")) {
         oSession.hostname = "local.testservice.com";          
 } 
           
Lets describe this:
first line  

 if (oSession.HostnameIs("testservice.com")) {
searches requests based on name and needs to be same


Second line     
this is the replacement line
         oSession.hostname = "local.testservice.com";    

Now if you run application with internal call, it will be redirected to local instance.

Advanced configuration 


You can apply the change in machine.config if you want to apply it to all applications as follows.

Open machine.config in the folder C:\Windows\Microsoft.NET\Framework\v4.0.30319\Config. Note that if you are debugging a 64bit service (like ASP.NET) you will want to look in the Framework64 folder instead of the Framework folder. Similarly, if you are using a .NET version prior to 4.0, you will need to adjust the version part of the path.

Add the following XML block as a peer to the existing system.net element, replacing any existing defaultProxy element if present as follows:

<system.net>
      <defaultProxy
                 enabled = "true"
                 useDefaultCredentials = "true">
        <proxy autoDetect="false" bypassonlocal="false" proxyaddress="http://127.0.0.1:8888" usesystemdefault="false" />
      </defaultProxy>
    </system.net>

Friday, 11 March 2016

Get all users from active directory using c#


I needed to get all members  from active directory using c#.
Now the solution I have found is as follows


using (var context = new PrincipalContext(ContextType.Domain, "yourdomain.com"))
{
    using (var searcher = new PrincipalSearcher(new UserPrincipal(context)))
    {
        foreach (var result in searcher.FindAll())
        {
            DirectoryEntry de = result.GetUnderlyingObject() as DirectoryEntry;
            Console.WriteLine("First Name: " + de.Properties["givenName"].Value);
            Console.WriteLine("Last Name : " + de.Properties["sn"].Value);
            Console.WriteLine("SAM account name   : " + de.Properties["samAccountName"].Value);
            Console.WriteLine("User principal name: " + de.Properties["userPrincipalName"].Value);
            Console.WriteLine();
        }
    }
}
Console.ReadLine();
the solution I have provided is from http://stackoverflow.com/questions/5162897/how-can-i-get-a-list-of-users-from-active-directory


Now the directory entry contains properties defined as string or object and you need to make sure that the data are accessed correctly.



Wednesday, 9 March 2016

C# Querying Organisational Units in Active directory

I am working on active directory queries. I have decided to share come code I have found, coded and updated.

Reference :
AD: Active Directory
OU: OrganisationalUnit (used to structure your AD)

How to get Organisational units from AD using c# & LDAP.

NOTE The important information here is:
Each structure in active directory have its own name and many times I have come across of misspelling the types. For OU we have to setup filter to search only on:

objectCategory = organizationalUnit


Now the full code is as follows


// connect to "RootDSE" to find default naming context
DirectoryEntry rootDSE = new DirectoryEntry("LDAP://RootDSE");

string defaultContext = rootDSE.Properties["defaultNamingContext"][0].ToString();

// bind to default naming context - if you *know* where you want to bind to - 
// you can just use that information right away
DirectoryEntry domainRoot = new DirectoryEntry("LDAP://" + defaultContext);

// set up directory searcher based on default naming context entry
DirectorySearcher ouSearcher = new DirectorySearcher(domainRoot);

// SearchScope: OneLevel = only immediate subordinates (top-level OUs); 
// subtree = all OU's in the whole domain (can take **LONG** time!)
ouSearcher.SearchScope = SearchScope.OneLevel;
// ouSearcher.SearchScope = SearchScope.Subtree;

// define properties to load - here I just get the "OU" attribute, the name of the OU
ouSearcher.PropertiesToLoad.Add("ou");

// define filter - only select organizational units
ouSearcher.Filter = "(objectCategory=organizationalUnit)";

// do search and iterate over results
foreach (SearchResult deResult in ouSearcher.FindAll())
{
    string ouName = deResult.Properties["ou"][0].ToString();
}
Links to Stack Overflow

http://stackoverflow.com/questions/16810382/getting-all-ous-from-a-active-directory

Tuesday, 8 March 2016

System call failed. (Exception from HRESULT: 0x80010100 (RPC_E_SYS_CALL_FAILED))

One day when I have opened Visual Studio I have come across following error


System call failed. (Exception from HRESULT: 0x80010100 (RPC_E_SYS_CALL_FAILED))


This can be caused by Studio attempting to contact TFS and fails.

Resolution is simple

Ensure your connection to TFS server is correct. You can run 'ipconfig /renew' from your command to see if you have connection

Wednesday, 2 March 2016

TFS running javascript tests

As JavaScript development becomes more first class citizen so does its testing.
I have started to write more JavaScript code and want to be sure that I have not broke anything and prove that the code does what expected without hidden traps

I am attempting to do so on configuration:
TFS 2012
VisualStudio 2012
Windows

Assumptions
You know how to write unit test using jasmine test runner
You can create successful build on your tfs

Structure:
Here you will be able to see my code structure for this project.




I have wrote a sample tests

Now I need to make it run on TFS

I had to create a location shared code that contain jasmine resource this resource is added as follows




 In Team Explorer, go to the Builds section and Edit your Build Definition which will run the javascript tests.
- Click on the Process tab
 - Select the row named Automated Tests.
 - Click on … button next to the value.
 Select the Tests to Run and click Edit. Change the Test assembly specification to **\*.js




Tuesday, 23 February 2016

Debug MEF



Nice article about debugging MEF

http://ihadthisideaonce.com/2012/01/31/stop-guessing-about-mef-composition-and-start-testing/

And would it be nice if you can run composition testing?
here is sample example how to do this:
http://ihadthisideaonce.com/2012/06/12/mef-composition-tests-redux/

Sunday, 26 July 2015

Reading emails using c# and POP3

I wanted to write my own automated behaviour after I receive new email and for that I needed to read emails that I get.

I have used OpenPop Nuget package.

Here is my package.config file

<?xml version="1.0" encoding="utf-8"?>
<packages>
  <package id="OpenPop.NET" version="2.0.6.1116" targetFramework="net45" />
</packages> 


Now after installing the package I have needed to add implementation that I took from
https://github.com/foens/hpop/blob/master/OpenPopExamples/Examples.cs to read emails.

Here is my code with configuration.

 // The client disconnects from the server when being disposed
            using (Pop3Client client = new Pop3Client())
            {
                // Connect to the server
                client.Connect("pop.gmail.com", 995, true);

                // Authenticate ourselves towards the server
                client.Authenticate("email@gmail.com", "password");

                // Get the number of messages in the inbox
                int messageCount = client.GetMessageCount();

                // Most servers give the latest message the highest number
                for (int i = messageCount; i > 0; i--)
                {
                    var msg = client.GetMessage(i);
                   Console.WriteLine(msg.Headers.Subject));
                }
            }

Now the issue is that email does not allow me to read the emails.
And the reading fill fail with exception.
If you drill into the exception you will be able to find following link

https://www.google.com/settings/security/lesssecureapps

This will give you configuration option to configure this


Now when I run the code I get my emails through.


Thursday, 23 July 2015

Installing underscore into angular and typescipt

I wanted to know how difficult it is to install underscore js library to project using typescript and angular js into my MVC Application

Turns out you need to download and install underscore.js (Read more about underscore)

using nuget search for "underscore.js"
After installation of this nuget package you will find in your packages.config line such as
<package id="underscore.js" version="1.8.2" targetFramework="net451" />

Note: 

This may differ based on version or framework but the important part is <package id="underscore.js"

Now we have installed underscore.
The directory where the package will be installed is /Scripts/

We need to add reference to our view

<script type="text/javascript" src="~/Scripts/underscore.min.js"></script>

So far this is standard way of using javascript.

Now I have created my typescript. I have named it index.ts

Now typescript does need definitions for it to recognise methods that library exposes and this is done in definition files. You can download definitions from Boris Yankov collection shared on github : https://github.com/borisyankov

File that you are looking for is named: underscore.d.ts

Put the file to same location where you have your underscore js file in my case or with all of your definitions.

Insert following path on top of your file.
/// <reference path="../../underscore.d.ts" />

Why is underscore path: "../../underscore.d.ts"?

it is because of my typescript lives in "/Scripts/App/Index/index.ts" which needs to go two directories up.

After this all we can go to your typescipt file and start using underscore in typescript





Sunday, 28 June 2015

Parse date from yyyy-MM-dd string

Often developer needs to parse formatted string to object.

Here is example I am commonly using:

I have a date time string:

var myString = "2015-06-05"

I need to parse it into DateTime variable 

var myString = "2015-06-05";
var parsedDateTime = DateTime.ParseExact(myString, "yyyy-MM-dd", CultureInfo.InvariantCulture, DateTimeStyles.None);

Monday, 30 March 2015

hide input rendered by editorformodel

The problem
We are using following code for login:

@using (Html.BeginForm())
{
    @Html.EditorForModel()
    <p>
        <button type="submit">Log In</button>
    </p>
}

The model is defined as:


 public class LogInModel
    {
        [Required]
        public string Email { get; set; }

        [Required]
        public string Password { get; set; }

        public string ReturnUrl { get; set; }
    }



So every time the page with the model renders, it will create 3 elements for user to imput data

One for email, second for password and the third for return url.

So how do we hide it?

We hide it using data annotation

 [ScaffoldColumn(false)]



so then our model will become:

    public class LogInModel
    {
        [Required]
        public string Email { get; set; }

        [Required]
        public string Password { get; set; }

        [ScaffoldColumn(false)]
        public string ReturnUrl { get; set; }
    }

Sunday, 29 March 2015

While writing my website I have read many blog posts how to do this the best way.

Couple targets I had in mind

  • Create bundle that will create smaller file to download
  • Almost everyone is using cdn, unless they are living behind firewall
  • And if cdn fails, provide file from local source

Key points:
  • Bundling is simply getting multiple files under one.
  • Minification is making files smaller
In my example I have java script files.

To render the bundle i need script in my page such as

 @Scripts.Render("~/bundles/jquery")

How to create a bundle


In your ASP.NET application you will have to find file: BundleConfig.cs
inside you will be able to find default setup, which might not be used in your template. 

     bundles.Add(new ScriptBundle("~/bundles/jquery")
                .Include("~/Scripts/jquery-{version}.js")); 

You might need to enable optimizations with code

 BundleTable.EnableOptimizations = true;
in order to see the efect on your page once run it.
   

Now to CDN


  1. content delivery network (CDN) is a system of distributed servers (network) that deliver webpages and other Web content to a user based on the geographic locations of the user, the origin of the webpage and a content delivery server.

Is supposed to offload some of the traffic, but what if I cannot access it?

We can create backup configuration, so I a case that cdn is unreachable we do not get down with our application.

How to achieve it?
First we need to tell bundle configuration that we are going to use cdn
  bundles.UseCdn = true;
And then we need to provide code with cdn first
  bundles.Add(new ScriptBundle("~/bundles/jquery", "https://code.jquery.com/jquery-{version}.min.js")
                .Include("~/Scripts/jquery-{version}.min.js"));
Notice the include after the path to cdn. This defacto says if you cannot get the file from here look to this alternative location

Example of the code is here:

One of many sources:
http://www.asp.net/mvc/overview/performance/bundling-and-minification
www.stackoverflow.com

Tuesday, 24 March 2015

xmlDoc.SelectSingleNode keeps same value in foreach loop


I have had an issue when looping through xml child nodes.

where using selector in loop kept same value.

xmlDoc.SelectSingleNode 

Example
var listOfNodes = xmlDoc.SelectSingleNode("//elementSelector");

foreach (XmlNode node in listOfNodes)
{
            var myValue = node.SelectSingleNode(@"//elementSelector").InnerText
}

myValue for each iteration returns same value even though the node changes


Solution is to add '.'

currentVenue.SelectSingleNode(@".//venueName").InnerText;


Now why this is:

The '.' in selector means to select the current node.
Without it, searching starts from the document root, not current element.