working on it ...

Filters

Explore Public Snippets

Sort by

Found 63 snippets

    public by cghersi modified Sep 7, 2018  188  1  3  0

    Retrieve BLOB From Azure Blob Storage

    Quick method to retrieve a set of BLOBs for Azure Blob Storage, given their names. Unfortunately the Azure REST APIs don't allow, yet, to BULK retrieve the content of several BLOBs in one single call, so we need to loop over each BLOB and retrieve the content one by one
    public static Dictionary<Guid, byte[]> GetBlobs(List<string> names)
    {
      Dictionary<string, byte[]> result = new Dictionary<string, byte[]>();
    
      // retrieve info about the interesting BLOBs:
      IEnumerable<CloudBlob> blobs = s_defaultContainer.ListBlobs().
        OfType<CloudBlob>().Where(c => names.Contains(c.Name));
      
      // loop over the retrieved BLOBs:
      foreach (CloudBlob b in blobs)
      {
      	b.FetchAttributes(); //otherwise we cannot query for Properties...
      	byte[] res = new byte[b.Properties.Length];
      	
      	// download the actual content:
      	b.DownloadToByteArray(res, 0); 
      	
      	result.Add(b.Name, res);
      }
      
      return result;
    }

    public by SpeedOfSpin modified Jan 23, 2017  2079  3  5  0

    SetTimeout Equivalent

    var cancellationTokenSource = new CancellationTokenSource();
    var cancellationToken = cancellationTokenSource.Token;
    
    Task.Delay(2000).ContinueWith(async (t) =>
    {
      //Do stuff
    }, cancellationToken);                      

    public by sTiLL-iLL modified Dec 1, 2015  2756  1  8  12

    C# Task extensions for yer pleasure

    helpful for c# TAP stuff.... ENJOI!
    // Task extensions
    
    public static class Extensions
    {
    
    	public static Task<T> Catch<T,TError> (this Task<T> task, Func<TError,T> onError) where TError : Exception
    	{
    		var tcs = new TaskCompletionSource<T> ();
    		task.ContinueWith (ant => {
    			if (task.IsFaulted && task.Exception.InnerException is TError)
                {
    				tcs.SetResult (onError ((TError) task.Exception.InnerException));
                }
    			else if (ant.IsCanceled)
                {
    				tcs.SetCanceled ();
                }
    			else if (task.IsFaulted)
                {
    				tcs.SetException (ant.Exception.InnerException);
                }
    			else
                {
    				tcs.SetResult (ant.Result);
                }
    		});
    		return tcs.Task;
    	}	
    /*	
    	public static Task<T> Catch<T,TError> (this Task<T> task, T onError) where TError : Exception
    	{
    		return task.Catch<T,TError> (ex => onError);
    	}
    	
    	public static Task<T> Catch<T,TError> (this Task task, T onError) where TError : Exception
    	{
    		return task.ToTaskOfT<T>().Catch<T,TError> (onError);
    	}
    
    	public static Task Catch (this Task task)
    	{
    		return task.Catch<object,Exception> (null);
    	}
    	
    	public static Task<T> Catch<T> (this Task<T> task, T valueIfError = default(T))
    	{
    		return task.Catch<T,Exception> (valueIfError);
    	}
    */
    	public async static Task<T> ToTaskOfT<T> (this Task t)
    	{
    		await t;
    		return default(T);
    	}
    	
    	public static async Task Then(this Task task, Func<Task> continuation)
    	{
    		await task;
    		await continuation();
    	}
    	
    	public static async Task<TNewResult> Then<TNewResult>(this Task task, Func<Task<TNewResult>> continuation)
    	{
    		await task;
    		return await continuation();
    	}
    	
    	public static async Task Then<TResult>(this Task<TResult> task, Func<TResult,Task> continuation)
    	{
    		await continuation(await task);
    	}
    	
    	public static async Task<TNewResult> Then<TResult, TNewResult>(this Task<TResult> task, Func<TResult, Task<TNewResult>> continuation)
    	{
    		return await continuation(await task);
    	}
    }            

    public by sTiLL-iLL modified Dec 1, 2015  2550  1  8  13

    Managed Interval! Timer Alchemy with concurrent kueue executes tasks on the b bb b bbeat

    check files, ping a server, download a receipt... if you can list it this can execute it, neat and tidy. its like a gold watch of timer structs (use my non-bloking kueue with this)
    using System;
    using System.IO;
    using System.Linq;
    using System.Threading;
    using System.Threading.Tasks;
    
    
    void Main()
    {
    	var dct = new DownCount(5);
    	new Thread (() =>
    	{
    		for (int i = 0; i < 5; i++)
    		{
    			Thread.Sleep(1000);
    			dct.Signal();
    			Console.WriteLine ("Signal " + i);
    		}
    	}).Start();
    	
    	Console.WriteLine ("Wait for it...");
    	dc.Wait();
    	Console.WriteLine ("ahhhhhh......");
    }
    
    public class DownCount
    {
      int val;
    	object loka = new object ();
    	public DownCount() { }
    	
    	public DownCount (int cnt1)
    	{
    	  val = cnt1;
    	}
    	
    	public void Signal()
    	{
    	  DCnt1 (-1);
    	}
    	
    	public void DCnt1 (int totl)
    	{
    		lock (loka) 
    		{ 
    			val += totl;
    			if (val <= 0)
    			{
    			  Monitor.PulseAll (loka);
    			}
    		}
    	}
    	
    	public void Wait()
    	{
    		lock (loka)
    		{
    			while (val > 0)
    			{
    				Monitor.Wait (loka);
    			}
    		}
    	}
    }
    
    //////////////////////////////////////////////////////////
    
    public class betterInterval
    {
      static void Tik(long t)
      {
        this.onTik.Invoke(t);
      }
      
      static IObservable<long> Interval(TimeSpan period)
      {
          return Observable.Create<long> (observer => {
    	    long i = 0;
    	    object sync = new object();
    	        return new Timer (_ => {
                      lock (sync) observer.OnNext (i++);
              }, Tik(i), period, period);
        });
      }
      
      static IObservable<long> kreate(TimeSpan period)
      {
        return Interval (TimeSpan.FromSeconds(period)).Subscribe(onTik);
      }
      
      static async void onTik(t)
      {
        Console.WriteLine(t);
      }
    }
    
    void Main()
    {
        IObservable<long> bi = betterInterval.kreate(TimeSpan.FromSeconds(5));
        bi.Subscribe(Console.WriteLine(t);
    }
    
    
    ///////////////////////////////////////////////////////////////////////
    
    public class KInterval
    {
        public delegate void Signal (object signal);
        public event Signal Received;
    
        static long tcnt = 0;
        long dly = 0;
        long prd = 0;
        KQue kq = new KQue(5);
        Timer tmr;
    
        public KInterval (long delay = 5000, long period = 3000, int workersCount = 3)
        {
            dly = delay;
            prd = period;
            if (workersCount > 0)
            {
                kq = new KQue(workersCount);
            }
        }
    
        public void Begin ( )
        {
            kq.NQItem(( ) => tmr = new Timer(Signaled, tcnt, dly, prd));
        }
    
        public void Kill ( )
        {
            tmr.Dispose();
            kq.ShutdownKQ(true);
        }
    
        private void Signaled (object signal)
        {
            var sig = (long) signal;
            var st = sig;
            this.Received += KInterval_Received;
            this.Received.Invoke(sig);
            this.Received -= KInterval_Received;
        }
    
        void KInterval_Received (object signal)
        {      }
    }                        

    public by sTiLL-iLL @ SniPitz-KND modified Dec 1, 2015  2519  1  8  14

    ANonyMUs inLINe WERKuh C#

    ILYNe exeKutin oF wutteva INda BaKGRownD.. SwEET
    
    //run a worker like an anonymous function
    
    public class AnonWorker
    {
        private BackgroundWorker bw = new BackgroundWorker();
        private AnonWorker(){   }
     
        public static AnonWorker Create
        {
            get { return new AnonWorker(); }
        }
     
        public void Execute(DoWorkEventHandler begin, 
              RunWorkerCompletedEventHandler completed = null,
                     ProgressChangedEventHandler progress = null)
        {
            bw.DoWork += begin;
            (completed != null) ? addComplete() : noop();
            (progress != null) ? addProgress() : noop();
            bw.RunWorkerAsync();
        }
        
        private void noop()
        {  // nada...  }
        
        private void addComplete()
        {
          bw.RunWorkerCompleted += completed;
        }
        
        private void addProgress()
        {
          bw.ProgressChanged += progress;
        }
    }
    
    
    
          // Now.....  run it like this and its gonna be on a separate thread
    
      AnonWorker.Create.Execute((sender, data) => {
          // work here ....
      }, 
      (sender, data) => {
          // all done
      });
     
     
      
          // Old Skool.....
    
      AnonWorker.Create.Execute(delegate {
          // work
      },
      delegate {
          // done
      });                        

    public by sTiLL-iLL @ SniPitz-KND modified Dec 1, 2015  3748  0  8  12

    BakGRoWnd ThREDiNG WrapAH ObSR.va.BuLL- onny

    
    using System;
    using System.Collections.Generic;
    using System.Threading;
    using System.Threading.Tasks;
    
    public class BGrounda
    {
    	Thread bgThrd;
    
    	public int Progress
    	{
    		get;
    		set;
    	}
    
    	public object Result
    	{
    		get;
    		set;
    	}
    
    	public bool IsActive
    	{
    		get
    		{
    			if (bgThrd != null)
    			{
    				return bgThrd.IsAlive;
    			}
    
    			return false;
    		}
    	}
    
    	public delegate void OnWorkDone(ref int progress, ref object rzlt, params object[] args);
    	public event OnWorkDone jobComplete;
    	List<Task> subscribers = new List<Task>();
    
    	public void RunIT(params object[] arguments)
    	{
    
    			foreach(Task t in subscribers)
    			{
    				bgThrd = new Thread(() => {
    					Task.Factory.StartNew(() => {
    						Task.FromResult(t);
    						this.DoWork.Invoke(ref prog, ref rzlt, arguments);
    						this.jobComplete(100, ref rzlt, "workComplete");
    					});
    				}).Start();
    			}
    
    	}
    
            public void Subscribe(Task obj)
            {
                members.Add(obj);
                return OnWorkHandler;
            }
    
    }                    

    public by sTiLL-iLL @ SniPitz-KND modified Dec 1, 2015  3576  2  7  13

    ZipStich.cs !!! dont be a dip, ZIP n STITCH!!! NO 3rd party dependancy! .Net 3.5 and greater

    archive just a file or a whole directory. YEAH!
    using System;
    
    // usage demo....
    	public class Program
    	{
    		static void Main(string[] args)
    		{
    			ZipShitz zip = new ZipShitz(@"c:\test.zip", @"c:\TestFolder\");
    			zip.OnZipDone += zip_OnZipDone;
    			zip.ZipShitAsync(new Action(sayIt));
    		}
    
    		static void zip_OnZipDone(System.IO.Packaging.Package pakage, Action callbak)
    		{
    			callbak.Invoke();
    		}
    
    		static void sayIt()
    		{
    			Console.WriteLine("");
    			Console.WriteLine(">> All Files Zipped and Complete! <<");
    			Console.Read();
    		}
    	}
    	
    // end demo....
    	
    	
    	
    // using System;
    using System.IO;
    using System.IO.Packaging;
    using System.Text;
    using System.Threading.Tasks;
    
    
    public class ZipShitz
    {
    
    	public delegate void ZipCompleteHandler(Package pakage, Action callbak);
    	public event ZipCompleteHandler OnZipDone;
    
    
    	public string ZipName
    	{
    		get;
    		set;
    	}
    
    
    
    	public string TargetFolder
    	{
    		get;
    		set;
    	}
    
    
    
    	public ZipShitz(string zName, string trgt)
    	{
    		OnZipDone += ZipShitz_OnZipDone;
    		ZipName = zName;
    		TargetFolder = trgt;
    	}
    
    
    
    	public ZipShitz()
    	{
    		OnZipDone += ZipShitz_OnZipDone;
    	}
    
    
    
    	void ZipShitz_OnZipDone(Package pakg, Action cbak)
    	{
    		if (!cbak.Equals(null))
    		{
    			cbak.DynamicInvoke();
    		}
    
    		OnZipDone -= ZipShitz_OnZipDone;
    	}
    
    
    
    	public void ZipShit()
    	{
    		using (var pkg = ZipPackage.Open(ZipName, FileMode.Create))
    		{
    			foreach (var fila in Directory.GetFiles(TargetFolder, "*.*", SearchOption.AllDirectories))
    			{
    				try
    				{
    					Console.WriteLine("Packing " + fila);
    					Uri relUri = MapRelativePath(fila);
    
    					var pkgPart = pkg.CreatePart(relUri, System.Net.Mime.MediaTypeNames.Application.Octet, CompressionOption.Maximum);
    					using (var fstrm = new FileStream(fila, FileMode.Open, FileAccess.Read))
    					{
    						StreamClone(fstrm, pkgPart.GetStream());
    					}
    				}
    				catch (Exception x)
    				{
    					throw x;
    				}
    			}
    		}
    	}
    
    
    
    	public void ZipShitAsync(Action assbak = null)
    	{
    		Package pkg = null;
    		Task.Factory.StartNew(() =>
    		{
    			using (pkg = ZipPackage.Open(ZipName, FileMode.Create))
    			{
    				foreach (string fila in Directory.GetFiles(TargetFolder, "*.*", SearchOption.AllDirectories))
    				{
    					try
    					{
    						Console.WriteLine("Packing " + fila);
    						Uri relUri = MapRelativePath(fila);
    						var pkgPart = pkg.CreatePart(relUri, System.Net.Mime.MediaTypeNames.Application.Octet, CompressionOption.Maximum);
    						using (FileStream fstrm = new FileStream(fila, FileMode.Open, FileAccess.Read))
    						{
    							StreamClone(fstrm, pkgPart.GetStream());
    						}
    					}
    					catch (Exception x)
    					{
    						x = null;
    					}
    				}
    			}
    		}).Wait();
    
    		if (!OnZipDone.Equals(null))
    		{
    			this.OnZipDone.DynamicInvoke(pkg, assbak);
    		}
    	}
    
    
    
    	void StreamClone(Stream src, Stream tgt)
    	{
    		try
    		{
    			const int bufLen = 16384;
    			byte[] buf = new byte[bufLen];
    			int bytz = 0;
    			while ((bytz = src.Read(buf, 0, bufLen)) > 0)
    			{
    				tgt.Write(buf, 0, bytz);
    			}
    		}
    		catch (Exception x)
    		{
    			throw x;
    		}
    	}
    
    
    
    	Uri MapRelativePath(string fil)
    	{
    		Uri pth2 = null;
    
    		try
    		{
    			var rlPth = fil.Substring(fil.IndexOf('\\')).Replace('\\', '/').Replace(' ', '_');
    			pth2 = new Uri(CleanString(rlPth), UriKind.Relative);
    		}
    		catch (Exception x)
    		{
    			throw x;
    		}
    
    		return pth2;
    	}
    
    
    
    	string CleanString(string argz)
    	{
    		byte[] bytz = null;
    
    		try
    		{
    			string nrmz = argz.Normalize(NormalizationForm.FormKD);
    			Encoding ecdr = Encoding.GetEncoding(Encoding.ASCII.CodePage, new EncoderReplacementFallback(""), new DecoderReplacementFallback(""));
    			bytz = ecdr.GetBytes(nrmz);
    		}
    		catch (Exception x)
    		{
    			throw x;
    		}
    
    		return Encoding.ASCII.GetString(bytz);
    	}
    }
    
                                                                

    public by sTiLL-iLL @ SniPitz-KND modified Sep 8, 2015  3646  3  7  10

    kKlient.cs

    an experiment in async task-based http methods C#!!!!
    using System;
    using System.Net;
    using System.Web;
    using System.Net.Cache;
    using System.Threading;
    using System.Threading.Tasks;
    
    public class kKlient
    {
        public string Base
        {
            get;
            set;
        }
        public RequestCachePolicy CachPol
        {
            get;
            set;
        }
        public bool UseDef
        {
            get;
            set;
        }
        public ICredentials Credz
        {
            get;
            set;
        }
        public WebHeaderCollection Headz
        {
            get;
            set;
        }
        public IWebProxy Prxy
        {
            get;
            set;
        }
    
        public kKlient (object[] argz)
        {
            new HTTPAction(argz);
        }
    
        public async Task<string> FetchString (string uri, CancellationToken cToken = default (CancellationToken),
            IProgress<DownloadProgressChangedEventArgs> progress = null)
        {
            return await Task.Run(( ) => GetClient(cToken, progress).DownloadStringTaskAsync(uri));
        }
    
        public async Task<byte[]> FetchData (string uri, CancellationToken cToken = default (CancellationToken),
            IProgress<DownloadProgressChangedEventArgs> progress = null)
        {
            return await Task.Run(( ) => GetClient(cToken, progress).DownloadDataTaskAsync(uri));
        }
    
        public async Task FetchFile (string uri, string fileName, CancellationToken cToken = default (CancellationToken),
            IProgress<DownloadProgressChangedEventArgs> progress = null)
        {
            await Task.Run(( ) => GetClient(cToken, progress).DownloadFileTaskAsync(uri, fileName));
        }
    
    
        internal class HTTPAction
             : WebClient
        {
            public HTTPAction ( )
                : base()
            {
            }
    
            public HTTPAction (string url)
                : base()
            {
            }
        }
    
        private HTTPAction GetClient (CancellationToken cancelToken, IProgress<DownloadProgressChangedEventArgs> progress)
        {
            HTTPAction hta = new HTTPAction()
            {
                BaseAddress = Base,
                CachePolicy = CachPol,
                UseDefaultCredentials = UseDef,
                Credentials = Credz,
                Headers = Headz,
                Proxy = Prxy,
            };
    
            if (cancelToken != CancellationToken.None) cancelToken.Register(( ) => hta.CancelAsync());
            if (progress != null)
            {
                hta.DownloadProgressChanged += (sender, args) => progress.Report(args);
            }
    
            return hta;
        }
    }           

    public by sTiLL-iLL modified Sep 8, 2015  2353  2  7  10

    CSEmitter.cs

    an "Event-Emitter" in C#..... pretty kewel
    using System;
    using System.Collections.Generic;
    
    
    public class CSEmitter
    {
        public delegate void PropChangedHandler (object sender, EventArgs e = null);
        public event PropChangedHandler propChanged;
        public List<Delegate> subscibers = new List<Delegate>();
        private bool pol = false;
    
        public bool Polarization
        {
            get
            {
                return pol;
            }
    
            set
            {
                if (pol != value)
                {
                    pol = value;
                    this.propChanged.Invoke(this.Polarization, new EventArgs());
                }
            }
        }
    
        public CSEmitter ( )
        {
            propChanged += CSEmitter_propChanged;
        }
    
        void CSEmitter_propChanged (object s, EventArgs e = null)
        {
            this.triggerAsync(s);
        }
    
        public PropChangedHandler create (Delegate callBack)
        {
            if (propChanged == null)
            {
                propChanged += CSEmitter_propChanged;    
            }
    
            Subscribe(callBack);
            return propChanged;
        }
    
        void triggerAsync (object state)
        {
            foreach (Delegate d in subscibers)
            {
                d.DynamicInvoke(state);
            }
        }
    
        void Subscribe (Delegate callBk)
        {
            subscibers.Add(callBk);
        }
    }           

    public by sTiLL-iLL @ SniPitz-KND modified Jun 27, 2015  2959  5  8  12

    EKOING C# WebSokETS server Thangy

    it might work
    using System;
    using System.Web;
    using System.Net.WebSockets;
    using System.Web.WebSockets;
    using System.Runtime.InteropServices;
    using System.Text;
    using System.Threading;
    using System.Threading.Tasks;
    
    public class EKOSocket : IHttpHandler {
        private const int MaxBuffer = 64 * 1024;
    
        public void OnRequest (HttpContext cntxt)
        {
            try
            {
                cntxt.AcceptWebSocketRequest(async wsContext => {
                    try
                    {
                        WebSocket skt = wsContext.WebSocket;
                        byte[] received = new byte[MaxBuffer];
                        ArraySegment<byte> buff = new ArraySegment<byte>(receive);
                        
                        string clientMsg;
    
                        if (skt.State == WebSocketState.Open)
                        {
                            var announce = "Connection @ : " + DateTime.Now.ToString();
                            ArraySegment<byte> output2 = new ArraySegment<byte>(Encoding.UTF8.GetBytes(announce));
                            await skt.SendAsync(output2, WebSocketMessageType.Text, true, CancellationToken.None);
                        }
    
                        while (skt.State == WebSocketState.Open)
                        {
                            WebSocketReceiveResult receive = await skt.ReceiveAsync(buff, CancellationToken.None);
    
                            if (receive.MessageType == WebSocketMessageType.Close)
                            {
                                // EKO back
                                await skt.CloseAsync(
                                    receive.CloseStatus.GetValueOrDefault(), 
                                    receive.CloseStatusDescription, CancellationToken.None);
                                return;
                            }
    
                            int offset = receive.Count;
                            while (receive.EndOfMessage == false)
                            {
                                receive = await skt.ReceiveAsync(new ArraySegment<byte>(received, offset,
                                MaxBuffer - offset),CancellationToken.None);
                                offset += received.Count;
                            }
    
                            if (receive.MessageType == WebSocketMessageType.Text)
                            {
                                string cmd = Encoding.UTF8.GetString(received, 0, offset);
                                clientMsg = cmd;
                                clientMsg = "EKO: \"" + clientMsg + "\"";
    
                                ArraySegment<byte> output = new ArraySegment<byte>(Encoding.UTF8.GetBytes(userString));
                                await skt.SendAsync(outputBuffer, WebSocketMessageType.Text, true, CancellationToken.None);
                            }
                            else if (receive.MessageType == WebSocketMessageType.Binary)
                            {
                                clientMsg = String.Format("binary message received, size={0} bytes", receiveResult.Count);
                                ArraySegment<byte> output = new ArraySegment<byte>(Encoding.UTF8.GetBytes(userString));
                                await skt.SendAsync(output, WebSocketMessageType.Text, true, CancellationToken.None);
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        // do something with the exception
                    }
                });
            }
            catch (Exception ex)
            {
                cntxt.Response.StatusCode = 500;
                cntxt.Response.StatusDescription = ex.Message;
                cntxt.Response.End();
            }
        }
    
        public bool canRecycle
        {
            get
            {
                return false;
            }
        }
    }
               
    • Public Snippets
    • Channels Snippets