|
Here's a utility that formats a byte array segment into a pretty printed hex dump string, for example:
00000000 : 02 03 04 05 06 07 08 09 0A 0B 0C 0D 0E 0F 10 11
00000010 : 12 13 00 01 02 03 04 05 06 07 08 09 00 01 02 03
00000020 : 04 05 06 07 08 09 00 01 02 03 04 05 06 07 08 09
00000030 : 00 01 02 03 04 05 06 07 08 09 00 01 02 03 04 05
00000040 : 06 07 08 09 00 01 02 03 04 05 06 07 08 09 00 01
00000050 : 02 03 04 05 06 07 08 09 00 01 02 03 04 05 06 07
00000060 : 08 09
public static class Utils
{
public static string ToHexDump(ArraySegment<byte> data,int bytesPerLine = 16)
{
var sb = new StringBuilder();
for (int t = 0; t < data.Count; t += bytesPerLine)
{
sb.AppendFormat("{0:X8} : ", t);
for (int u = t; u < (t+bytesPerLine); u++)
{
if (u < data.Count)
{
sb.AppendFormat("{0:X2} ", data.Array[data.Offset + u]);
}
else
{
sb.Append(' ',3);
}
}
sb.AppendLine();
}
return sb.ToString();
}
}
|
|
|
|
|
public static int Log2(long n)
{
int result = 0;
if (n <= 0) throw new ArgumentOutOfRangeException("n","n must be > 0");
for (int k = 32; k > 0; k >>= 1)
{
if (n >= (1L << k)) { result += k; n >>= k; }
}
return result;
}
|
|
|
|
|
$credential = New-Object System.Management.Automation.PsCredential("systemname\jmikkers", (ConvertTo-SecureString "MyPassword" -AsPlainText -Force))
Start-Process $PsHome\powershell.exe -Credential $credential -Wait -ArgumentList "-File c:\users\jmikkers\desktop\credential2.ps1"
|
|
|
|
|
Hi jpmik;
found your posts about collection scripts are very helpful. I have a query regarding the same. When we execute a PS Query using the pipeline.InvokeAsync() method. It keeps running and returning 1 records.
What I need to do is to save these records in database. with all the properties of a record as column names. It is eating a lot of time. then I read your posts. I hope you already done this many time. If you can provide me your email ID so I can discuss it with you. that will be a big help for me.
I can run the Query as
pipeline.Invoke()
It returns the object with all values. and i can get the properties names and their respective data and save the full data successfully. but this is successful until i am running the scripts for very small amount of data.
my requirement is to get the property name with in pipeline.InvokeAsync(). so that i can update the database with each record retrived.
I hope you got my requirement. and Hope to get an answer very soon.
Thanks & Regards
Suresh Kharod
|
|
|
|
|
|
Hello mr. paul,
Thanks for the quick reply.
I have been using that code as well using this method (pipeline.InvokeAsync()),
But problem I am facing is
private void pipelineExecutor_OnDataReady(PipelineExecutor sender, ICollection<<psobject> data)
{
foreach (PSObject obj in data)
{
AppendLine(obj.ToString());
}
}
This is my OnDataReady Event. this is running for each values and returning a string like for a simple query of ;
Get-ChildItem c:\ | Out-String -stream
It will return
""
""
Directory: c:\
""
Mode LastWriteTime Length Name
---- ------------- ------ ----
d--- DateTime here inetpub
and in my scenario I need data like in each call I need to know the properties names and values so that i can insert data in a database or temporary table.
If I use the another function
pipeline.Invoke();
It return all the values and I can easily filter it as well but for heavy data it takes a lot of time and memory.
please suggest me a way to do it with
pipeline.InvokeAsync()
thanks
Suresh
|
|
|
|
|
I think I see the problem: you just have to make sure that your script doesn't output everything in one object, but as an enumerable. In your example, just remove the 'out-string' part, then your OnDataReady will be called multiple times. This prevents powershell from having to pull all results into memory.
|
|
|
|
|
int[] list = new int[]{ 2,5,3,1,6,7,2};
bool isSorted = list.Aggregate(
new { Sorted = true, Prev = int.MinValue },
(a, x) => new { Sorted = a.Sorted && (a.Prev <= x ), Prev = x },
a => a.Sorted);
|
|
|
|
|
Here's a System.Threading.Timer drop-in replacement (not all overloads are present, but you get the idea). It doesn't prevent the target from being garbage collected like the original does.
public class WeakTimer
{
private readonly Timer m_Timer;
private readonly WeakReference m_WeakTarget;
private readonly Action<object, object> m_Invoker;
public WeakTimer(TimerCallback tc, object state, int dueTime, int period)
{
if (tc.Method.IsStatic)
{
m_Timer = new Timer(tc, state, dueTime, period);
}
else
{
m_WeakTarget = new WeakReference(tc.Target);
m_Invoker = GenerateInvoker(tc.Method);
m_Timer = new Timer(MyCallback, state, dueTime, period);
}
}
private static Action<object,object> GenerateInvoker(MethodInfo method)
{
var instExpr = Expression.Parameter(typeof(object), "instance");
var paramExpr = Expression.Parameter(typeof(object), "state");
var invokeExpr = Expression.Call(Expression.Convert(instExpr, method.DeclaringType), method, paramExpr);
return Expression.Lambda<Action<object, object>>(invokeExpr, instExpr, paramExpr).Compile();
}
private void MyCallback(object state)
{
object handler = m_WeakTarget.Target;
if (handler != null)
{
m_Invoker(handler, state);
}
else
{
m_Timer.Change(Timeout.Infinite, Timeout.Infinite);
}
}
public void Change(int dueTime, int period)
{
m_Timer.Change(dueTime, period);
}
}
|
|
|
|
|
Here's a class that wraps any reference so it's safe to use as a key for a Dictionary of references, regardless whether the original object implemented its Equals() and GetHashCode() correctly.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.CompilerServices;
public class ReferenceWrap<T> : IEquatable<ReferenceWrap<T>>
{
private T inner;
public T Inner
{
get { return inner; }
}
public ReferenceWrap(T inner)
{
if (inner == null) throw new ArgumentException("inner reference can't be null", "inner");
this.inner = inner;
}
public override bool Equals(object obj)
{
return Equals(obj as ReferenceWrap<T>);
}
public override int GetHashCode()
{
return RuntimeHelpers.GetHashCode(inner);
}
public override string ToString()
{
return inner.ToString();
}
public bool Equals(ReferenceWrap<T> other)
{
return (other != null && object.ReferenceEquals(other.inner, inner));
}
}
|
|
|
|
|
|
public static T Clip<T>(this T value, T minValue, T maxValue) where T : IComparable<T>
{
T result;
if (value.CompareTo(minValue) < 0)
result = minValue;
else if (value.CompareTo(maxValue) > 0)
result = maxValue;
else
result = value;
return result;
}
|
|
|
|
|
The following code is a generic extension method that randomly shuffles the contents of a list. It uses a forward form of the Fisher-Yates shuffle algorithm.
public static IEnumerable<tsource> Shuffle<tsource>(this IEnumerable<tsource> source, Random rnd)
{
var shuffled = source.ToList();
for (int t = 0; t < shuffled.Count; t++)
{
int newpos = t + rnd.Next(shuffled.Count - t);
var tmp = shuffled[t];
shuffled[t] = shuffled[newpos];
shuffled[newpos] = tmp;
}
return shuffled;
}
</tsource></tsource></tsource>
|
|
|
|
|
If you want to have user-configurable colors and store them in the application settings, you'll notice that System.Drawing.Color doesn't serialize correctly. This is because it doesn't have setters for its public properties. The following class is a convenient wrapper around Color that does provide these and thus serializes correctly.
[Serializable()]
public struct SerializableColor
{
private Color m_Color;
public byte R
{
get
{
return m_Color.R;
}
set
{
m_Color = Color.FromArgb(m_Color.A, value, m_Color.G, m_Color.B);
}
}
public byte G
{
get
{
return m_Color.G;
}
set
{
m_Color = Color.FromArgb(m_Color.A, m_Color.R, value, m_Color.B);
}
}
public byte B
{
get
{
return m_Color.B;
}
set
{
m_Color = Color.FromArgb(m_Color.A, m_Color.R, m_Color.G, value);
}
}
public byte A
{
get
{
return m_Color.A;
}
set
{
m_Color = Color.FromArgb(value, m_Color.R, m_Color.G, m_Color.B);
}
}
public SerializableColor(int a, int r, int g, int b)
{
m_Color = Color.FromArgb(a, r, g, b);
}
public SerializableColor(Color c)
{
m_Color = c;
}
static public implicit operator SerializableColor(Color c)
{
return new SerializableColor(c);
}
static public implicit operator Color(SerializableColor c)
{
return c.m_Color;
}
}
|
|
|
|
|
public static double StandardVariance<T>(this IEnumerable<T> sequence, Func<T, double> selector)
{
return sequence.Select(selector).Aggregate(
new{ Count = 0, Q = 0.0, Average = 0.0 },
(a, x) =>
new
{
Count = a.Count + 1,
Q = a.Q + Math.Pow(x-a.Average,2.0) * a.Count / (a.Count+1),
Average = a.Average + (x-a.Average) / (a.Count+1)
}
,
a => a.Q / a.Count);
}
public static double StandardDeviation<T>(this IEnumerable<T> sequence, Func<T, double> selector)
{
return Math.Sqrt(sequence.StandardVariance(selector));
}
How to use:
double[] example = new double[]{ 3,4,7,23,5,2,5,212,5 };
Console.WriteLine("{0}", example.StandardDeviation(x => x));
|
|
|
|
|
The following code snippet demonstrates an extension method that allows you to convert a BitmapFrame to a GDI+ compatible image.
...
using System.Drawing;
using System.Windows.Media.Imaging;
...
public static class WICExtension
{
public static Image ToImage(this BitmapFrame bitmapFrame)
{
using (Stream s = new MemoryStream())
{
BitmapEncoder bitmapEncoder = new BmpBitmapEncoder();
bitmapEncoder.Frames.Add(bitmapFrame);
bitmapEncoder.Save(s);
s.Flush();
s.Seek(0, SeekOrigin.Begin);
return Bitmap.FromStream(s);
}
}
}
|
|
|
|
|