working on it ...

Filters

Explore Public Snippets

Sort by

Found 256 snippets matching: dotnet

    public by sTiLL-iLL @ SniPitz-KND  550009  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 sTiLL-iLL @ SniPitz-KND  3650  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  2616  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
      });                        

    external by Kevin Adistambha  6  0  2  0

    Small example of using MongoDB dotnet driver (dotnet-core, MongoDB.Driver 2.4.1)

    Small example of using MongoDB dotnet driver (dotnet-core, MongoDB.Driver 2.4.1): MongoDotnetDriver.cs
    using System;
    using System.Linq;
    using MongoDB.Bson;
    using MongoDB.Driver;
    
    namespace ConsoleApplication
    {
    
        public class Person {
            public ObjectId Id { get; set; }
            public string Name { get; set; }
            public int Age { get; set; }
            public override string ToString() {
                return "Person Name: " + Name + ", Age: " + Age;
            }
        }
    
        public class MongoDotnetDriver
        {
            public static void ListDatabases(MongoClient client) {
                Console.WriteLine("\n=== Databases ===");
                foreach(var db in client.ListDatabases().ToEnumerable()) {
                    Console.WriteLine(" - " + db);
                }
            }
    
            public static void ListCollections(MongoClient client) {
                Console.WriteLine("\n=== Collections ===");
                var database = client.GetDatabase("test");
                foreach(var coll in database.ListCollections().ToEnumerable()) {
                    Console.WriteLine(" - " + coll);
                }
            }
    
            public static void InsertDocuments(MongoClient client) {
                Console.WriteLine("\n=== Insert documents ===");
                var database = client.GetDatabase("test");
                var collection = database.GetCollection<BsonDocument>("dotnet");
    
                /* Drop collection */
                database.DropCollection("dotnet");
    
                /* Insert one document */
                var document = new BsonDocument
                {
                    {"name", "MongoDB"},
                    {"type", "database"},
                    {"info", new BsonDocument
                        {{"x", 123}, {"y", 456}}
                    }
                };
                Console.WriteLine("> " + document);
                collection.InsertOne(document);
    
                /* Insert many documents */
                var documents = Enumerable.Range(0,5).Select(i => new BsonDocument("a", i));
                foreach(var row in documents) {
                    Console.WriteLine("> " + row);
                }
                collection.InsertMany(documents);
            }
    
            public static void FindDocuments(IMongoCollection<BsonDocument> collection) {
                Console.WriteLine("\n=== Find ===");
    
                /* Query all documents */
                Console.WriteLine("--- all ---");
                var docs = collection.Find(new BsonDocument()).ToEnumerable();
                foreach(var doc in docs) {
                    Console.WriteLine("<< " + doc);
                }
    
                /* Query with filter */
                Console.WriteLine("--- with filter ---");
                var param = BsonDocument.Parse("{a: {$gt: 2}}");
                Console.WriteLine(param);
                foreach(var doc in collection.Find(param).ToEnumerable()) {
                    Console.WriteLine("<< " + doc);
                }
            }
    
            public static void AggregateDocuments(IMongoCollection<BsonDocument> collection) {
                Console.WriteLine("\n=== Aggregate ===");
    
                var agg = collection.Aggregate()
                    .Match(new BsonDocument { {"a", new BsonDocument {{"$gt", 0}}} })
                    .Group(BsonDocument.Parse("{_id: null, total: {$sum: '$a'}, avg: {$avg: '$a'}}"));
                foreach(var doc in agg.ToEnumerable()) {
                    Console.WriteLine(doc);
                }
            }
    
            public static void InsertObject(MongoClient client) {
                Console.WriteLine("\n=== Insert object ===");
    
                var database = client.GetDatabase("test");
                var collection = database.GetCollection<Person>("Persons");
    
                database.DropCollection("Persons");
    
                var person1 = new Person { Name = "John Rambo", Age = 30 };
                var person2 = new Person { Name = "Stephen Seagal", Age = 40 };
                var persons = new [] {
                    new Person { Name = "Jet Li", Age = 20 },
                    new Person { Name = "Chuck Norris", Age = 31 },
                    new Person { Name = "John McClane", Age = 25 }
                };
                collection.InsertOne(person1);
                collection.InsertOne(person2);
                collection.InsertMany(persons);
    
                Console.WriteLine("--- All persons ---");
                foreach(var person in collection.Find(new BsonDocument()).ToEnumerable()) {
                    Console.WriteLine("<< " + person);
                }
    
                Console.WriteLine("--- 30 and older ---");
                foreach(var person in collection.Find(BsonDocument.Parse("{Age: {$gte: 30}}")).ToEnumerable()) {
                    Console.WriteLine("<< " + person);
                }
    
                Console.WriteLine("--- 30 and older (LINQ) ---");
                var query1 = from person in collection.AsQueryable()
                             where person.Age >= 30
                             select person;
                foreach(var p in query1.AsEnumerable()) {
                    Console.WriteLine(p);
                }
                var query2 = collection.AsQueryable().Where(p => p.Age >= 30).Select(p => p.Age);
                Console.WriteLine("Aggregation: " + query2);
                Console.WriteLine("Total age: " + query2.Sum());
                Console.WriteLine("Avg age: " + query2.Average());
            }
    
            public static void Main(string[] args)
            {
                /* Connection */
                var client = new MongoClient("mongodb://localhost:27017");
                var database = client.GetDatabase("test");
                var collection = database.GetCollection<BsonDocument>("dotnet");
    
                MongoDotnetDriver.ListDatabases(client);
                MongoDotnetDriver.ListCollections(client);
                MongoDotnetDriver.InsertDocuments(client);
                MongoDotnetDriver.FindDocuments(collection);
                MongoDotnetDriver.AggregateDocuments(collection);
                MongoDotnetDriver.InsertObject(client);
            }
        }
    }
    
    
    

    external by Garrett Serack  79  0  1  0

    Installing dotnet cli tools on BashOnWindows (WSL)

    Installing dotnet cli tools on BashOnWindows (WSL): Install-dotnet.sh
    # do some upgrades
    sudo apt-get install libstdc++6
    sudo add-apt-repository ppa:ubuntu-toolchain-r/test 
    sudo apt-get update
    sudo apt-get upgrade
    sudo apt-get dist-upgrade
    
    # install dotnet RTM and Preview 2 bits
    sudo apt-get install curl libunwind8 gettext
    curl -sSL -o dotnet.tar.gz https://go.microsoft.com/fwlink/?LinkID=809130
    sudo mkdir -p /opt/dotnet && sudo tar zxf dotnet.tar.gz -C /opt/dotnet
    sudo ln -s /opt/dotnet/dotnet /usr/local/bin
    
    
    
    

    external by Oliver Jones  410  38  3  0

    Dotnet decryption of SAML assertion

    Dotnet decryption of SAML assertion: decrypt.cs
    /// <summary>
    /// decrypt a document with the specified key
    /// </summary>
    /// <param name="docin">encrypted document</param>
    /// <param name="key">the key pair</param>
    /// <returns>the decrypted document</returns>
    public static XmlDocument DecryptDocument(this XmlDocument docin, X509Certificate2 key, StringBuilder log = null)
    {
        /* first step: make sure encrypted xml contains all these items.
         * EncryptedKey                (present in many documents)
         *   EncryptionMethod          (present in many documents)
         *     KeyInfo                 (absent in some documents)
         *       X509Data                 ditto
         *         X509Certificate        ditto with x.509 cert in Base4
         *  
         * because that's the way dotnet EncryptedXML figures out
         * under the covers which key to use to decode the document,
         * bless its pointed little head.  */
    
        var encryptedKey = docin.LookForNode(@"EncryptedKey");
        if (null == encryptedKey)
        {
            /* not an encrypted document, give it right back. */
            return docin;
        }
        /* leave the input document unchanged, manipulate a copy */
        var doc = (XmlDocument) docin.Clone();
    
        encryptedKey = doc.LookForNode(@"EncryptedKey");
        if (null == encryptedKey)
        {
            if (null != log) log.Append("No encryption key in document").AppendLine();
            return docin;
        }
    
        var encryptionMethod = encryptedKey.LookForNode(@"EncryptionMethod");
        if (null == encryptionMethod)
        {
            if (null != log) log.Append("No key encryption method in document").AppendLine();
            return docin;
        }
    
        /*create required stanza of XML based on our public key */
        const string keynamespace = SignedXml.XmlDsigNamespaceUrl;
        XmlNode ki = doc.CreateElement(null, @"KeyInfo", keynamespace);
        XmlNode xd = doc.CreateElement(null, @"X509Data", keynamespace);
        XmlNode xc = doc.CreateElement(null, @"X509Certificate", keynamespace); /* has public key cert in it */
        xc.InnerText = Convert.ToBase64String(key.Export(X509ContentType.Cert));
    
        /* insert it into the received document */
        xd.AppendChild(xc);
        ki.AppendChild(xd);
        encryptedKey.InsertAfter(ki, encryptionMethod);
        if (null != log) log.Append("Adding KeyInfo data to encrypted document").AppendLine();
    
        /* handle the decrypt */
        try
        {
            var exml = new EncryptedXml(doc);
            exml.DecryptDocument();
        }
        catch (CryptographicException cre)
        {
            if (null != log) log.Append(cre.Message).AppendLine();
        }
        return doc;
    }
    
    
    
    

    external by shairozan  34  0  1  0

    Dotnet Startup Script

    Dotnet Startup Script: start.sh
    #!/bin/bash
    ROOT_DIR=/dotnet
    #Check to see if the Environment Variable for $APPNAME is set
    
    usage(){
    echo "$0 -a <AppName>"
    echo
    echo "AppName is required as it instructs the shell as to which directory to descend into for running the restore and launch commands"
    exit 1
    }
    
    
    while getopts ":a:" opt ; do
            case "$opt" in
            a)
                    APPNAME=${OPTARG}
                    ;;
            *)
                    usage
                    ;;
            esac
    done
    
    #If no APPNAME variable is instantiated, print usage
    if [ -z $APPNAME ] ;
    then
            usage
    fi
    
    
    #Locate the directory with project.json
    PROJECT_PATH=`find $ROOT_DIR -name project.json | grep $APPNAME | sed 's/^\.//g'`
    PROJECT_DIRECTORY=`dirname $PROJECT_PATH`
    
    cd PROJECT_DIRECTORY
    dotnet restore
    dotnet run
    
    
    

    external by GuardRex  1061  1  3  0

    VS Code Tasks file to work with dotnet cli

    VS Code Tasks file to work with dotnet cli: tasks.json
    // Available variables which can be used inside of strings.
    // ${workspaceRoot}: the root folder of the team
    // ${file}: the current opened file
    // ${fileBasename}: the current opened file's basename
    // ${fileDirname}: the current opened file's dirname
    // ${fileExtname}: the current opened file's extension
    // ${cwd}: the current working directory of the spawned process
    //     watch
    {
        "version": "0.1.0",
        "command": "cmd",
        "isShellCommand": true,
        "showOutput": "silent",
        "args": [
            "/c"
        ],
        "tasks": [
            {
                "taskName": "restore",
                "suppressTaskName": true,
                "args" : ["dotnet", "restore"],
                "showOutput": "always",
                "problemMatcher": "$msCompile"
            },
            {
                "taskName": "publish",
                "suppressTaskName": true,
                "args" : ["dotnet", "publish"],
                "showOutput": "always",
                "isBuildCommand": true,
                "problemMatcher": "$msCompile"
            },
            {
                "taskName": "processcss",
                "suppressTaskName": true,
                "args" : ["gulp", "processCSS"]
            },
            {
                "taskName": "processindexcss",
                "suppressTaskName": true,
                "args" : ["gulp", "processIndexCSS"]
            },
            {
                "taskName": "processsjs",
                "suppressTaskName": true,
                "args" : ["gulp", "processJS"],
                "problemMatcher": "$jshint"
            },
            {
                "taskName": "processindexjs",
                "suppressTaskName": true,
                "args" : ["gulp", "processIndexJS"],
                "problemMatcher": "$jshint"
            },
            {
                "taskName": "processfonts",
                "suppressTaskName": true,
                "args" : ["gulp", "processFonts"]
            },
            {
                "taskName": "processviewswwwroot",
                "suppressTaskName": true,
                "args" : ["gulp", "processViewsWwwroot"]
            },
            {
                "taskName": "watch",
                "suppressTaskName": true,
                "args" : ["gulp", "watch"]
            },
            {
                "taskName": "unittest",
                "suppressTaskName": true,
                "args" : ["dotnet", "test"],
                "isTestCommand": true,
                "showOutput": "always"
            }
        ]
    }
    
    
    
    

    external by Ross  279  7  3  0

    Using dotNet "System.Diagnostics.Process" for a better DOSCommand in Maxscript.

    Using dotNet "System.Diagnostics.Process" for a better DOSCommand in Maxscript.: Dos_Command.ms
    global Dos_Command
    struct DOSCMD (
        fn run exe_path arg_array:undefined as_string:false =
        (
            local process = dotNetObject "System.Diagnostics.Process"
    
            process.StartInfo.UseShellExecute = false
            process.StartInfo.RedirectStandardOutput = true
            process.StartInfo.RedirectStandardError = true
    
            process.StartInfo.FileName = exe_path
            process.StartInfo.Arguments = ""
            if arg_array != undefined then
            (
            	for arg in arg_array do ( process.StartInfo.Arguments += (" " + arg as string) )
            )
    
            process.Start()
            process.WaitForExit()
    
            local _output = process.StandardOutput.ReadToEnd()
            local _error = process.StandardError.ReadToEnd()
    
    
            if _error == "" then
            (
                process.Close()
                process.Dispose()
                if as_string then return ( trimRight _output "\r\n" )
                else return ( filterString _output "\r\n" splitEmptyTokens:false )
            )
            else
            (
                process.Close()
                process.Dispose()
                if as_string then return ( trimRight _output "\r\n" )
                else return ( filterString _error "\r\n" splitEmptyTokens:false )
            )
        )
    )
    if Dos_Command == undefined then Dos_Command = DOSCMD()
    
    

    external by Robert Friberg  737  0  3  0

    Just discovered the dotnet BigInteger type. Nice use of implicit type conversion and operator overloading.

    Just discovered the dotnet BigInteger type. Nice use of implicit type conversion and operator overloading.: gistfile1.cs gistfile2.cs
    /// <summary>
    /// Primality test of mersenne prime using the lucas-lehmer test
    /// </summary>
    /// <param name="p">A prime number</param>
    /// <returns>true if 2^p-1 is prime, otherwise false</returns>
    public static bool IsMersennePrime(int p)
    {
        BigInteger mp = BigInteger.Pow(2, p) - 1;
        BigInteger n = 4;
        for (int i = 1; i < p - 1; i++)
        {
    		  n = (n * n - 2) % mp;
    	  }
        return n == 0;
    }
    
    
    public static void Main(String[] args)
    {
        Console.WriteLine(IsMersennePrime(2));
        Console.WriteLine(IsMersennePrime(3));
        Console.WriteLine(IsMersennePrime(5));
        Console.WriteLine(IsMersennePrime(7));
        Console.WriteLine(IsMersennePrime(11));
        Console.WriteLine(IsMersennePrime(13));
        Console.WriteLine(IsMersennePrime(17));
        Console.WriteLine(IsMersennePrime(19));
        Console.WriteLine(IsMersennePrime(23));
        Console.WriteLine(IsMersennePrime(29));
        Console.WriteLine(IsMersennePrime(31));
        Console.WriteLine(IsMersennePrime(37));
        Console.WriteLine(IsMersennePrime(41));
        Console.WriteLine(IsMersennePrime(43));
        Console.WriteLine(IsMersennePrime(47));
        Console.WriteLine(IsMersennePrime(53));
        Console.WriteLine(IsMersennePrime(59));
        Console.WriteLine(IsMersennePrime(61));
        Console.WriteLine(IsMersennePrime(67));
        Console.WriteLine(IsMersennePrime(71));
        Console.WriteLine(IsMersennePrime(83));
        Console.WriteLine(IsMersennePrime(89));
        Console.WriteLine(IsMersennePrime(107));
        Console.WriteLine(IsMersennePrime(127));
        Console.WriteLine(IsMersennePrime(521));
        Console.WriteLine(IsMersennePrime(607));
        Console.WriteLine(IsMersennePrime(1279));
        Console.WriteLine(IsMersennePrime(4253));
        Console.WriteLine(IsMersennePrime(19937));
        Console.WriteLine(IsMersennePrime(23209));
        Console.WriteLine(IsMersennePrime(86243));
    }
    
    
    • Public Snippets
    • Channels Snippets