working on it ...

Filters

snippets
13k
followers
12
Published by msdn

MSDN Samples

Microsoft official library of examples for .NET languages
Sort by

Found 13k snippets

    public by sTiLL-iLL @ SniPitz-KND  5152  4  9  42

    Vanilla KemPlates... MVC in stiches....

    real kwik model view controller example made with 100% vanilla JS
    
    ///  MY "SIGNALS" EVENT SYSTEM ////////////////
    
    //   this solution Uses my signals.js module
    
    ////////  styles  ///////////
    
    
    body {
    	font-family: Calibri;
    	width: 220px;
    }
    
    .container {
        border: 1px solid black;
        padding: 10px;
        width: 232px;
        margin: 50px auto 50px 350px;
    	border-radius: 7px;
    	background: lightgray;
    }
    
    fieldset {
    	width: 205px;
    	margin: 0 auto 3px 3px;
    	margin-right: auto;
    	margin-bottom: 6px;
    	padding: 10px;
    }
    
    h1 {
    	margin-left: 55px;
    	margin-right: auto;
    }
    
    span {
    	margin: 3px;
    }
    
    input {
    	margin-top: 2px;
    	margin-bottom: 8px;
    	width: 168px;
    	padding-left: 3px;
    }
    
    ul {
    	padding-left: 20px;
    	list-style: none;
    	color: navy;
    	overflow-x: hidden;
    }
    
    li {
    	max-width: 180px
    }
    
    
    
    /////////  Model(s)   ////////////////////////
    
    // this is the user model object
    
    var user1 = {
        name1: "Richard",
        name2: "Longwood",
        occupation: "Software Engineer",
        age: "40",
        title: 'Skillz Yo!',
        subTitle: "add a skill...",
        showSkills: true,
        skills: []
    };
    
    
    
    function UserModel (usr) {
        this.user = usr;
        this.get = function(k) {
            if (k) {
                var u = this.user;
                return u[k];
            } 
            else {
                var u = this.user;
                return u;
            }
        };
    };
    
    
    
    var User = new UserModel (user1);
    User.prototype = Signals;
    User.constructor = User;
    
    User.on = function(v, cbk) {
        this.prototype.receive(v, function(d) {
            cbk.call(this.user, d);
        });
    };
    User.emit = function(v) {
        this.prototype.signal("change", v);
    };
    User.off = function(v) {
        this.prototype.dropReceivers(v);
    };
    User.set = function(k, v) {
        if (v && v !== this.user[k]) {
            if (k == "skills") {
                this.user[k].push(v);
            } else {
                this.user[k] = v;
            }
            this.prototype.signal("change", this.user);
        }
    };
    
    
    
    // array for template strings, 
    // our template engine, and an array of target Ids.
    
    var kList = [], 
        TPE = new TPEngine(), 
        Nodz = ["t1", "t2", "t3", "t4", "t5", "t6"];
    
    
    
    // this template string is pretty bulky, 
    // so Ill keep it stashed as a string, 
    // then inject it into its target when its time.
    
    var template6 = '~>{ if(User.get("showSkills")) { :}' + 
            '~>{ for(var index in User.get("skills")) { :}' + 
            '<li><a href="#"> ~>{ User.get("skills")[index] :}' + 
            '</a></li> ~>{ } :}' + '~>{ } else { :}' + 
            '<li>none</li>' + '~>{ } :}';
    
    
    
    // this array holds the template strings.
    // the innerText is where I extract them from the mark-up
    // notice how #5 is already defined
    
    var Templates = [
        template1 = t1.innerText, 
        template2 = t2.innerText, 
        template3 = t3.innerText, 
        template4 = t4.innerText,
        template5 = t5.innerText, 
        template6
    ];
    
    
    // Now I iterate over the list of nodes and templates,
    // pull each one out per the array position and plug
    // them into the kompiler along with the property of the node that 
    // the content is assigned to, then komile into a "kPlate" template.
    // each one of these kPlates is then put into another array: "kList"
    
    Nodz.forEach(function(tmpltNd) {
        var seed = Templates.shift();
        kPlt = TPE.Template(tmpltNd, "innerHTML", seed);
        kList.push(kPlt);
    });
    
    
    
    // Here, we set up the 2-way bindings
    
    var bb = document.getElementById("btn"), 
        tgl = document.getElementById("tgl"),
        updateDom = function (d) {
            kList.forEach(function(itm) {
                TPE.BindSet(itm, d);
            });
        },
        updateModel = function (d) {
            User.set("skills", tgl.value);
            tgl.value = "";
        };
    
    
    // When the button is pressed, this handler
    // in the controller hears it, grabs the new value
    // and updates the model.
    
    bb.addEventListener("click", updateModel);
    
    
    // When the model's value is changed, it fires a change event.
    // The handler here in the controller hears it,
    // grabs the new value, and then updates the dom
     
    User.on("change", updateDom);
    
    
    // This part basicly is what runs on window ready.
    // Now that everything is all set up..
    // we iterate over the array of kPlates that we stored earlier,
    // calling BindSet on each one. This renders the mark-up
    // to the dom at lightening speed, and there ya go!
    
    kList.forEach(function(itm) {
        TPE.BindSet(itm, User);
    });
    
    
    
    
    
    
    //////////// Template kompiler (controller)  //////////////////////////////////////
    
    this.TPEngine = function() {
        var kompiler = function(templateString, model) {
            var rgx = /~>{([^:]+)?:}/g, 
            rgex = /(^( )?(if|for|else|switch|case|break|{|}))(.*)?/g, 
            segment = 'var r=[];\n', position = 0, 
            kompile = function(chunk, ixjs) {
                ixjs ? (segment += chunk.match(rgex) ? chunk + '\n' : 'r.push(' + chunk + ');\n') : 
                (segment += chunk != '' ? 'r.push("' + chunk.replace(/"/g, '\\"') + '");\n' : '');
                return kompile;
            };
            while (match = rgx.exec(templateString)) {
                kompile(templateString.slice(position, match.index))(match[1], true);
                position = (match.index + match[0].length);
            }
            ;
            kompile(templateString.substr(position, templateString.length - position));
            segment += 'return r.join("");';
            return new Function(segment.replace(/[\r\t\n]/g, '')).apply(model);
        }, 
        template = function(elementID, prop, templateString) {
            var c = {
                tStr: templateString,
                tProp: prop,
                tVal: document.getElementById(elementID)
            };
            return c;
        }, 
        applyBind = function(temp, model) {
            if (temp.tVal.id && temp.tStr && model) {
                template = temp;
                var el = document.getElementById(template.tVal.id);
                el[template.tProp] = kompiler(template.tStr, model);
                template.tVal = el;
            }
        };
        return {
            Template: template,
            BindSet: applyBind
        };
    };
    
    
    ///////// VIEW  //////////////////////////
    
    <!DOCTYPE html>
    <html>
    <head>
    	<title>MY MVC</title>
    </head>
      	<meta charset="utf-8" />
    	<link rel="stylesheet" href="css/stylz.css" />
    	<script src="js/signals.js"></script>
    	<script src="js/myTPlates.js"></script>
    <body>
    	<div class="container">
    		<h1 id="t1">
    			~>{ User.get("title") :} 
    		</h1>
    		<fieldset>
    			<legend id="t2">
    				~>{ User.get("subTitle") :}
    			</legend>
    			<input id="tgl" type="text" placeholder="skills"></input>
            	<button id="btn">+</button>
    			<hr><b>
    			  Name:
    			  <span id="t3">
    					~>{ User.get("name1") +" "+ User.get("name2") :}
    			  </span>
    			  </br>
    			  Age: 
    			  <span id="t4">
    					~>{ User.get("age") :}
    			 </span>
    			 </br>
    			  Dept: 
    			  <span id="t5">
    					~>{ User.get("occupation") :}
    			 </span>
    			 <hr>
    			  Skills List: 
    			 <ul id="t6">
    					~>{ User.get("skills") :}
    			 </ul></b>	
    			<hr>
    		</fieldset>
    	</div>
    </body>
    <script src="js/script1.js"></script>
    </html>
    
    
                                                                                                                

    public by sTiLL-iLL @ SniPitz-KND  3708  0  8  22

    Lazy Loaded...... Lazy.js

    load your images on demand...
    // another lazy  image loader thang.....
    
    var lazy=(function() {
        this.load=function(elem, res) {
          if (document.querySelectorAll) {
              res=document.querySelectorAll(elem);
          } else {
            var dok=document, 
              sheet=dok.styleSheets[0] ||
              dok.createStyleSheet();
              sheet.addRule(elem,'foo:idx');
            for(var ln=dok.all,idx=0,lst=[],f=l.length;idx<foo;idx++) {
              (ln[isx].currentStyle.foo&&lst.push(ln[idx]));
            }
            sheet.removeRule(0);
            res=clst;
          }
          return res;
        }; 
        var receive=function(evt,func) {
          window.addEventListener?this.addEventListener(evt,func,false) :
            (window.attachEvent)?this.attachEvent('on'+evt,func):
            (this['on'+evt]=func);
        };
        var itHaz=function(k,object) {
          return Object.prototype.hasOwnProperty.call(k,object);
        };
        this.getLoaded=function(elem,func) {
          var img=new Image(),
          prnt=elem.parent;
          img.src=elem.getAttribute('data-src');
          img.addEventListener("load",function(evt) {
          if (!elem.parent) {
            prnt.replaceChild(img, elem)
          } else {
            elem.src=src;
          }
          (func)?func(): null;
        });
        img.src=src;
      };
      function inView(elem){
        var r=elem.getBoundingClientRect();
        return(r.top>=0&&r.left>=0&&
          r.top<=(window.innerHeight||
            document.documentElement.clientHeight)
          );
      }
      function cBak(pix, idx){
        return (pix.splice(idx,idx));
      }
      var pix=[],qry=layzee('img.lazy');
      this.doWork=function(){
        for (var idx=0;idx<images.length;idx++) {
          if (inView(pix[idx])){
            return getLoaded(pix[idx],cBak(pix,idx));
          }
        }
      };
      for (var idx=0;idx<qry.length;idx++) {
        pix.push(qry[idx]);
      }
      doWork();
      receive('scroll',dowork);
    }(this));                      

    public by sTiLL-iLL  2608  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  2612  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  3814  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  3044  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 by sTiLL-iLL @ SniPitz-KND  2729  6  7  14

    C# Non Blocking, Multithreaded, Maker/Taker Queue

    effn sweet....
    public class KQue
    {
      readonly object synk = new object();
      Thread[] wrkrz;
      Queue<Action> itmQ = new Queue<Action>();
    
      public KQue (int workerCount)
      {
        wrkrz = new Thread [workerCount];
        for (int i = 0; i < workerCount; i++)
        {
          (wrkrz[i] = new Thread(konsume)).Start();
        }
      }
    
    
      public void Shutdown (bool waitingFor)
      {
        foreach (var thd in wrkrz)
        {
          NQItem (null);
        }
        if (waitingFor)
        {
          foreach (var thd in wrkrz)
          {
            thd.Join();
          }
        }
      }
    
      public void NQItem (Action itm)
      {
        lock (synk)
        {
          itmQ.Enqueue (itm);       
          Monitor.Pulse (synk);         
        }
      }
    
      private void konsume()
      {
        while (true)     
        {                               
          Action itm;
          lock (synk)
          {
            while (itmQ.Count == 0)
            {
                Monitor.Wait (synk);
            }
            itm = itmQ.Dequeue();
          }
    
          if (itm == null)  
          {
              return;
          }
    
          itm();   
        }
      }
    }
    
                

    public by sTiLL-iLL @ SniPitz-KND  550003  5  8  16

    Async Queue in C#

    using System;
    using System.Net;
    using System.Threading;
    using System.Threading.Tasks;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    
    
    public class ParalyzKue
    {
    	readonly object _locker = new object();
    	Task _tail = Task.FromResult (true);
    	
    	public Task Enqueue (Action action)
    	{
    		lock (_locker)
    			return _tail = _tail.ContinueWith (ant => action());
    	}
    
    	public Task<TResult> Enqueue<TResult> (Func<TResult> func)
    	{
    		lock (_locker)
    			return (Task<TResult>) (_tail = _tail.ContinueWith (ant => func()));
    	}
    
    	public Task Enqueue (Func<Task> action)
    	{
    		lock (_locker)
    			return _tail = _tail.Catch().Then (action);
    	}	
    
    	public Task<TResult> Enqueue<TResult> (Func<Task<TResult>> func)
    	{
    		lock (_locker)
    			return (Task<TResult>) (_tail = _tail.Catch().Then (func));
    	}
    }
    
    
    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 void doKue()
    {
    	var pcQ = new ParaKue();
    	
      pcQ.Enqueue (() => AsyncMethod1 ("http://www.rotten.com/")).Dump ("Task 1");
    	pcQ.Enqueue (() => AsyncMethod1 ("https://youtube.com/")).Dump ("Task 2");
    	pcQ.Enqueue (() => AsyncMethod1 ("https://yahoo.com/search?q=the cube")).Dump ("Task 3");
      pcQ.Enqueue (() => AsyncMethod1 ("http://www.rotten.com/")).Dump ("Task 4");
    	pcQ.Enqueue (() => AsyncMethod1 ("https://youtube.com/")).Dump ("Task 5");
    	pcQ.Enqueue (() => AsyncMethod1 ("https://www.google.com/search?q=web scrapers")).Dump ("Task 6");
      pcQ.Enqueue (() => AsyncMethod1 ("http://www.rotten.com/")).Dump ("Task 7");
    	pcQ.Enqueue (() => AsyncMethod1 ("https://youtube.com/")).Dump ("Task 8");
    	pcQ.Enqueue (() => AsyncMethod1 ("https://youtube.com/search?q=aliens gods")).Dump ("Task 9");
      pcQ.Enqueue (() => AsyncMethod ("http://www.rotten.com/")).Dump ("Task 10");
    	pcQ.Enqueue (() => AsyncMethod ("https://youtube.com/")).Dump ("Task 11");
    	pcQ.Enqueue (() => AsyncMethod ("https://www.google.com/search?q=javascript")).Dump ("Task 12");
      pcQ.Enqueue (() => AsyncMethod ("http://www.rotten.com/")).Dump ("Task 13");
    	pcQ.Enqueue (() => AsyncMethod ("https://youtube.com/search?q=aliens")).Dump ("Task 14");
      pcQ.Enqueue (() => AsyncMethod ("https://www.yahoo.com/")).Dump ("Task 15");
    	pcQ.Enqueue (() => AsyncMethod ("https://youtube.com/")).Dump ("Task 16");
    	pcQ.Enqueue (() => AsyncMethod ("https://www.google.com/search?q=aliens disclosure")).Dump ("Task 17");
    }
    
    string SyncMethod (string uri)
    {
        var x = new System.Net.WebClient();
        var y = x.DownloadString(uri);
        return y;
    }
    
    async Task<string> AsyncMethod (string uri)
    {
       return await Task.Run(() => new System.Net.WebClient().DownloadStringTaskAsync(uri).Dump());
    }
    
    
    async Task<string> AsyncMethod1 (string uri)
    {
       var x = await new System.Net.WebClient().DownloadStringTaskAsync(uri);
       return x;
    }
    
    */

    public by msdn  2089  0  6  0

    Main: Hosts the service.

    Hosts the service.
    /// <summary>
    /// Hosts the service.
    /// </summary>
    public static void Main()
    {
       var serviceEndPointAddress = new Uri("https://localhost:3040/servicemodelsamples/service.svc");
       var host = new ServiceHost(typeof(CalculatorService), serviceEndPointAddress);
    
       var binding = new WSHttpBinding();
       binding.Security.Mode = SecurityMode.Transport;
       binding.Security.Transport.ClientCredentialType = HttpClientCredentialType.None;
       binding.Security.Message.NegotiateServiceCredential = true;
       binding.ReceiveTimeout = new TimeSpan(1, 0, 0);
       binding.MaxReceivedMessageSize = int.MaxValue;
       binding.ReliableSession.InactivityTimeout = new TimeSpan(1, 0, 0);
    
       host.Credentials.ServiceCertificate.SetCertificate(
          StoreLocation.LocalMachine,
          StoreName.My,
          X509FindType.FindBySubjectDistinguishedName,
          "CN=WCFServer");
    
       host.AddServiceEndpoint(typeof(ICalculator), binding, serviceEndPointAddress);
       host.Open();
    
       Console.WriteLine("Service started successfully at {0}", serviceEndPointAddress);
       Console.WriteLine("Enter any key to stop the service");
       Console.Read();
    }

    public by msdn  1745  0  7  0

    Enact

    using System;
    using System.ServiceModel;
    using System.Security.Cryptography.X509Certificates;
    using System.Net;
    
    static PermissiveCertificatePolicy currentPolicy;
    
    public static void Enact(string subjectName)
    {
       currentPolicy = new PermissiveCertificatePolicy(subjectName);
    }
    • Public Snippets
    • Channels Snippets