Thursday, 10 September 2015

ServiceStack.Redis C# client demo

This article shows some simple code to communicate with Redis.io , using ServiceStack.Redis. The easiest way to install ServiceStack.Redis client is to use the Nuget Package Manager GUI inside Visual Studio, as there are several packages. The following packages are required:


<?xml version="1.0" encoding="utf-8"?>
<packages>
  <package id="ServiceStack.Common" version="4.0.44" targetFramework="net45" />
  <package id="ServiceStack.Interfaces" version="4.0.44" targetFramework="net45" />
  <package id="ServiceStack.Redis" version="4.0.44" targetFramework="net45" />
  <package id="ServiceStack.Text" version="4.0.44" targetFramework="net45" />
</packages>



The easiest way to install is to use Manage Nuget Packages and search for "redis" and choose "C# Redis client for the Redis NoSQL DB", as displayed above. After adding the Redis client Nuget library, make sure you have access to a Redis server. On Windows, it is possible to install Redis server by downloading it from the GitHub page supported by MSOpenTech. Note that Redis server is officially supported on Linux and in production environments, Redis is considered a bit experimental for Windows servers. However, Redis is now an established technology. It is though suggested to download not the very newest version of the Redis package and server, version 2.6 should work well as of now (p.t. 10.09.2015). Download the Redis client and server from here: Redis 64 Windows binaries (zipped) Installing Redis is dead simple, just unzip and copy Redis binaries to a folder. However, for production environments, you will want to install Redis as a Windows Service. This is explained here: Running Redis as a Windows Service Here is some sample code that communicates with the Redis server (considered to be available on localhost, default port is 6379):

using ServiceStack.Redis;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace RedisTesting
{
    class Program
    {

        static void Main(string[] args)
        {

            RedisTypedClientDemo();

            RedisClientDemo();

            NativeClientDemo();

            TransactionDemo();

            PublishDemo();

            SubscribeDemo();

            Console.WriteLine("Press the ENTER key to exit.");
            Console.ReadLine(); 

        }

        private static void SubscribeDemo()
        {
            using (IRedisClient client = new RedisClient())
            {
                var sub = client.CreateSubscription();
                sub.OnMessage = (c, m) => Console.WriteLine("Got message {0} from channel {1}", m, c);
                sub.SubscribeToChannels("news");
            }
        }

        private static void PublishDemo()
        {
            using (IRedisClient client = new RedisClient())
            {
                client.PublishMessage("debug", "Hello C#");
            }
        }

        private static void TransactionDemo()
        {
            using (IRedisClient client = new RedisClient())
            {
                var transaction = client.CreateTransaction();
                transaction.QueueCommand(c => c.Set("abc", 1));
                transaction.QueueCommand(c => c.Increment("abc", 1));
                transaction.Commit();
                var result = client.Get<int>("abc");
                Console.WriteLine(result);
            }
        }

        private static void RedisTypedClientDemo()
        {
            long lastId = 0;

            using (IRedisClient client = new RedisClient())
            {
                var customerClient = client.As<Customer>();
                var customer = new Customer
                {
                    Id = customerClient.GetNextSequence(),
                    Adress = "123 Main Street",
                    Name = "Bob Green",
                    Orders = new List<Order>
                    {
                        new Order { OrderNumber = "AB123" },
                        new Order { OrderNumber = "AB124" }
                    }
                };

                var storedCustomer = customerClient.Store(customer);
                lastId = storedCustomer.Id;

            }

            using (IRedisClient client = new RedisClient())
            {
                var customerClient = client.As<Customer>();
                var customer = client.GetById<Customer>(lastId);
                Console.WriteLine("Get customer {0}, with name {1}", customer.Id, customer.Name);
            }
        }

        private static void RedisClientDemo()
        {
            using (IRedisClient client = new RedisClient())
            {
                var customerNames = client.Lists["urn:customernames"];
                customerNames.Clear();
                customerNames.Add("Joe");
                customerNames.Add("Mary");
                customerNames.Add("Bob");
            }

            using (IRedisClient client = new RedisClient())
            {
                var customerNames = client.Lists["urn:customernames"];

                foreach (var customerName in customerNames)
                {
                    Console.WriteLine("Customer: " + customerName);
                }
            }
        }

        private static void NativeClientDemo()
        {
            using (IRedisNativeClient client = new RedisClient("localhost", 6379))
            {
                client.Set("urn:messages:1", Encoding.UTF8.GetBytes("Hello C# World"));
            }

            using (IRedisNativeClient client = new RedisClient("localhost", 6379))
            {
                var result = Encoding.UTF8.GetString(client.Get("urn:messages:1"));
                Console.WriteLine("Message:" + result);
            }
        }
    }
}

//Class Customer

using System.Collections.Generic;

namespace RedisTesting
{
    
    public class Customer
    {

        public long Id { get; set; }

        public string Name { get; set; }

        public string Adress { get; set; }

        public List<Order> Orders { get; set; }

    }


}



//Class Order 


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace RedisTesting
{
    
    public class Order
    {

        public string OrderNumber { get; set; }

    }

}


Tuesday, 8 September 2015

Powershell execution from C#

This article will display an entertaining example how to execute Powershell from C#. We will use Linqpad, available here: Download LinqPad now The code executes a Powershell scripts, then uses different objects in System.Management.Automation for working with Powershell from C#. The Powershell script is executed inside Linqpad, where C# code is pasted. The code itself will animate the active processes on the computer running the Linqpad C# code, executing the Powershell script. The code is listed below. Paste the code into Linqpad. You might want to adjust the Task.Delay and for loop for controlling how quick you want to refresh and how long to run (# iterations).










public class CpuNode {

 public CpuNode(string name, int percentage){
  ProcessName = name; 
  Percentage = percentage; 
 }

 public string ProcessName { get; set; }
 
 public int Percentage { get; set; }

}


async void Main()
{
 Chart c = new Chart(); 
 
 Series s  = c.Series.Add("ActiveProcesses"); 
 s.ChartType = SeriesChartType.Column;  

 Title title = new Title("Active processes using CPU (%)", Docking.Top, new Font("Verdana", 18), Color.MidnightBlue); 
 c.Titles.Add(title); 
 
 var ca = new ChartArea();  
 var ca3D = new ChartArea3DStyle(); 
 ca3D.Enable3D = true; 
 ca.Area3DStyle = ca3D; 
 ca.AxisY.Maximum = 100;
 ca.AxisY.Minimum = 0; 
 ca.BackColor = Color.AliceBlue;
 ca.AxisX.Title = "Process name"; 
 ca.AxisY.Title = "CPU Percentage %"; 
 
 Legend lg = new Legend(); 
 lg.Title = "CPU"; 
 lg.BackColor = Color.AliceBlue; 
 c.Legends.Add(lg); 
  
  c.ChartAreas.Add(ca); 
  
  c.Dump(""); 
  
 
 string cpuPsScript = @"get-wmiobject Win32_PerfFormattedData_PerfProc_Process| 
Select-Object -Property Name, PercentProcessorTime | Where-Object { $_.Name -ne '_Total'  } | 
Where-Object { $_.Name -ne 'Idle' } "; 
 
 using (PowerShell powerShellInstance = PowerShell.Create()){
  powerShellInstance.AddScript(cpuPsScript); 
  
  List<CpuNode> nodes = new List<CpuNode>();
 
  for (int i=0; i<1000; i++){
 
  Collection<PSObject> psOutput = powerShellInstance.Invoke();
  
  s.Points.Clear(); 
  
  nodes.Clear();  
 
  int n = 1; 
  foreach (PSObject outputItem in psOutput){
    try {
    string processName = outputItem.Properties["Name"].Value.ToString();
    int processPercentage = int.Parse(outputItem.Properties["PercentProcessorTime"].Value.ToString()); 
    var node = new CpuNode(processName, processPercentage);              
    nodes.Add(node);
    } //try 
    catch (Exception err){
     err.Message.Dump(); 
    } //try-catch  
       
  } //foreach
  
  
  foreach (var node in nodes.OrderBy(x => x.ProcessName)){
   var dt = new DataPoint(n, node.Percentage); 
   if (node.Percentage > 1){
    dt.Label = node.ProcessName + " (" + node.Percentage + "%)"; 
   }
   dt.Color = ColorTranslator.FromHtml("#FF418CF0"); 
   
   s.Points.Add(dt);
   n = n + 1; 
  }
  
  c.ResumeLayout(); 
  
   await Task.Delay(250);
  
 } //for  
  
}

}

// Define other methods and classes here


The code uses the Powershell cmdlet get-mwiobject and uses the performance counter Win32_PerfFormatttedData_PerfProc_Process We use the PowerShell.Create() method to create the Powershell instance and add a script using the .AddScript method. We then Invoke the Powershell instance, grab hold of the PsObject items and then readily accesses the Properties inside. We build up a Chart object with a chart series, having data points and setting up a nice formatting. When the Chart object is created, we let LinqPad display it for us in a tab pane. Now that was fun, wasn't it? Now go code some more :-)

Wednesday, 2 September 2015

EventLogDisplayer

EventLogDisplayer

EventLogDisplayer is a general-purpose tool to harvest and display contents from the Event Log in a simple dedicated web application implemented in ASP.NET MVC. To make it work, one must enable Remote Event Log on the target server, set up a powershell script as a scheduled task and then create a database to commit the Event Log items. Also make sure that the directory configured to write the scratch XML files to, already exists. The harvest script will harvest last 24 hours from the Event Log and write new items to the database. This can easily be adjusted. The script is usually set up to run once an hour, so retrieving the Event Log items can of course be reduced down to an hour. Regarding how often the Event Log is harvested, this must correspond to the intervals of the scheduled tasks that executes the script, so that all Event Logs items are retrieved. Only Event Log items of type Warning and Error/Exception is retrieved (Information event log type is skipped).

Harvesting the Event Log

Powershell script
Write-Host Starting the harvesting from EventLog ... 
#Setup the parameters of the script to harvest the eventlog here  
$username = "myusername"
$password = "mypassword"
$targetServer = "myserver.somedomain.no"
$logName = "MyLogName" 
$datestamp = Get-Date -Format ddMMyyyy
$outputFile = "C:\temp\EventLogs\EventsLogFile_" + $dateStamp + ".xml"
$daysBack = 1  
$secstr = New-Object -TypeName System.Security.SecureString
$password.ToCharArray() | ForEach-Object {$secstr.AppendChar($_)}
$cred = new-object -typename System.Management.Automation.PSCredential -argumentlist $username, $secstr
 
$yesterday = (Get-Date) - (New-TimeSpan -Day $daysBack)
 
#Write-Host $yesterday
 
$sb = New-Object -TypeName "System.Text.StringBuilder" 
$sb.AppendLine("<?xml version='1.0' ?>")
$sb.Append("<Events xml='http://schemas.microsoft.com/win/2004/08/events/event'>")
Get-WinEvent -ComputerName $targetServer -Credential $cred -LogName $logName | Where-Object { $_.TimeCreated -ge $yesterday -and $_.Level -ge 2 } | ForEach-Object {
 $eventXml =  $_.ToXml()
 $sb.AppendLine($eventXml) 
} 
$sb.AppendLine("</Events>")
$sb.ToString() | Out-File $outputFile
#Invoke-Item $outputFile

Link to EventLogDisplayer


Sample web solution
(Link is not active) This web site targets the server MYSERVER, Event Log name is set to MyLogName.

Screenshots of Event Log Displayer


It is easy to monitor another server, but note that the Remote Event Log feature must be added to the server.

Scheduling task to harvest the Event Log remotely
Sample task from Task Scheduler
The following task will set up a hourly schedule, harvesting event log from the remote computer.


<?xml version="1.0" encoding="UTF-16"?>
<Task version="1.2" xmlns="http://schemas.microsoft.com/windows/2004/02/mit/task">
  <RegistrationInfo>
    <Date>2015-08-28T20:02:29.8065626</Date>
    <Author>somedomain\someuser-he</Author>
  </RegistrationInfo>
  <Triggers>
    <CalendarTrigger>
      <Repetition>
        <Interval>PT1H</Interval>
        <StopAtDurationEnd>false</StopAtDurationEnd>
      </Repetition>
      <StartBoundary>2015-08-28T00:00:00</StartBoundary>
      <Enabled>true</Enabled>
      <ScheduleByDay>
        <DaysInterval>1</DaysInterval>
      </ScheduleByDay>
    </CalendarTrigger>
  </Triggers>
  <Principals>
    <Principal id="Author">
      <UserId>somedomain\someuser</UserId>
      <LogonType>InteractiveToken</LogonType>
      <RunLevel>LeastPrivilege</RunLevel>
    </Principal>
  </Principals>
  <Settings>
    <MultipleInstancesPolicy>IgnoreNew</MultipleInstancesPolicy>
    <DisallowStartIfOnBatteries>true</DisallowStartIfOnBatteries>
    <StopIfGoingOnBatteries>true</StopIfGoingOnBatteries>
    <AllowHardTerminate>true</AllowHardTerminate>
    <StartWhenAvailable>false</StartWhenAvailable>
    <RunOnlyIfNetworkAvailable>false</RunOnlyIfNetworkAvailable>
    <IdleSettings>
      <StopOnIdleEnd>true</StopOnIdleEnd>
      <RestartOnIdle>false</RestartOnIdle>
    </IdleSettings>
    <AllowStartOnDemand>true</AllowStartOnDemand>
    <Enabled>true</Enabled>
    <Hidden>false</Hidden>
    <RunOnlyIfIdle>false</RunOnlyIfIdle>
    <WakeToRun>false</WakeToRun>
    <ExecutionTimeLimit>P3D</ExecutionTimeLimit>
    <Priority>7</Priority>
  </Settings>
  <Actions Context="Author">
    <Exec>
      <Command>Powershell</Command>
      <Arguments>C:\Users\toaurs-he\Documents\Powershell\HarvestEventLog.ps1</Arguments>
    </Exec>
  </Actions>
</Task>



The task above defined in the XML can be saved to an XML file, adjusted as necessary and imported in Task Scheduler: The task can also be adjusted using the command line (as Administrator) with the command:

schtasks.exe /Create /XML task.xml /tn taskname

Enabling Remote Event Log feature on target server Remote Event Log Management is enabled in the Windows Firewall with Advanced Security as an Inbound Rule, predefined as Remote Event Log Management.

Tick off all the three choices here:



SQL Script

The following script creates the database required to persist data to the database.


USE [OpPlan4EventLog] GO /****** Object: Table [dbo].[Events] Script Date: 02.09.2015 20:03:14 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO CREATE TABLE [dbo].[Events]( [Id] [INT] NOT NULL, [Message] [nvarchar](MAX) NULL, [TimeCreated] [datetime] NULL, [Level] [INT] NULL, [Channel] [nvarchar](300) NULL, [Computer] [nvarchar](300) NULL, CONSTRAINT [PK_Events] PRIMARY KEY CLUSTERED ( [Id] ASC)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY] GO

Sample MVC web solution


The EventLogDisplayer is a MVC web solution and is available here. Available on OneDrive here:

Sample MVC web solution [40,15 MB | Zip-file | Visual Studio 2013 Solution ]