working on it ...

Filters

snippets
8,182
followers
338
Published by snip2code

CSharp

This channel collects useful snippets for CSharp language
Sort by

Found 8,182 snippets

    public by guantalamo56  91  0  4  -2

    UWP: Get an image from local resources

    Build an Image object from local resources. The image should be stored as content in the Assets folder of the project.
    public static Image ImageFromName(this string imageName)
    {
    	if (imageName == null)
    		return null;
    	if (!imageName.StartsWith("ms-appx:///Assets/"))
    		imageName = "ms-appx:///Assets/" + imageName;
    	return new Image
    	{
    		Source = new BitmapImage(new Uri(imageName, UriKind.RelativeOrAbsolute))
    	};
    }				

    public by cicero81  102  0  5  0

    Find line number and member name via reflection

    This method allows to know the line number and the method name of the caller
    using System.Reflection;
    using System.Runtime.CompilerServices;
    
    public static void Fail(this object testClass, string message = "",
    			[CallerLineNumber] int lineNumber = 0,
    			[CallerMemberName] string caller = null)
    {
    	throw new FailTestException(string.Format("{0}.{1} failed at line {2} {3}", 
    		testClass.GetType().FullName, caller, lineNumber, message));
    }				

    public by cicero81  109  1  4  0

    Create your own test suite to run

    This set of methods allow to run a test suite without unit test frameworks like XUnit etc. It can be used across all the C# applications, e.g. UWP
        public static async Task<List<TestResult>> RunTests()
    		{
    			List<TestResult> res = new List<TestResult>();
    
    			// Consider the namespace of the tests:
    			IEnumerable<Type> typelist = GetTypesInNamespace(Assembly.GetExecutingAssembly(), "LiquidTextUWP.Tests");
    			foreach (Type testClass in typelist)
    			{
    				// Get all the test methods in the class:
    				foreach (MethodInfo method in testClass.GetMethods())
    				{
    					LTTestAttribute testAttr = method.GetCustomAttributes<LTTestAttribute>().FirstOrDefault();
    					if (testAttr == null)
    						continue;
    					object instance = Activator.CreateInstance(testClass);
    					try
    					{
    						if (testAttr.IsAsync)
    							await (Task) method.Invoke(instance, null);
    						else
    							method.Invoke(instance, null);
    						res.Add(new TestResult(true));
    					}
    					catch (Exception e)
    					{
    						res.Add(new TestResult(false, string.Format("{0} - {1}", e.Message, e.InnerException?.Message)));
    					}
    				}
    			}
    
    			return res;
    		}
    
    		private static IEnumerable<Type> GetTypesInNamespace(Assembly assembly, string nameSpace)
    		{
    			return assembly.GetTypes().Where(t => (t.Namespace != null) && t.Namespace.StartsWith(nameSpace));
    		}
    		
    		public struct TestResult
    	{
    		public bool Success { get; set; }
    		public string ErrorMsg { get; set; }
    
    		public TestResult(bool success, string msg = "")
    		{
    			Success = success;
    			ErrorMsg = msg;
    		}
    	}
    
    	[AttributeUsage(AttributeTargets.Method)]
    	public class LTTestAttribute : Attribute
    	{
    		public bool IsAsync { get; set; } = false;
    	}

    public by marceloviana  128  0  3  0

    Acessando sub linhas de um json

    String json_resultado = "{\"hasErrors\":true,\"errors\":[{\"reference\":\"AcordoApplication\",\"message\":\"18 - Não existem dívidas pendentes.\"}]}";
            
           var jObject = Newtonsoft.Json.Linq.JObject.Parse(json_resultado.ToString());
    
           foreach (var itens in jObject["errors"]) {
    
               String resultado = itens["message"].ToString();
    
           };
    

    public by marceloviana  526  1  4  0

    Percorrer json

    foreach (var keyvalue in context_id)
            {
    
                
                text = text + "</br><b>" + keyvalue.Name + "</b>  " + keyvalue.Value;
            }

    public by snip2code  656  3  4  0

    First Snippet: How to play with Snip2Code

    This is the first example of a snippet: - the title represents in few words which is the exact issue the snippet resolves; it can be something like the name of a method; - the description (this field) is an optional field where you can add interesting information regarding the snippet; something like the comment on the head of a method; - the c
    /* place here the actual content of your snippet. 
       It should be code or pseudo-code. 
       The less dependencies from external stuff, the better! */

    public by sjschmalfeld  319  1  4  0

    Get a list of installed printers

    get a list of the installed printers on machine
    private void PopulateInstalledPrintersCombo()
    {
        // Add list of installed printers found to the combo box.
        // The pkInstalledPrinters string will be used to provide the display string.
        String pkInstalledPrinters;
        for (int i = 0; i < PrinterSettings.InstalledPrinters.Count; i++)
        {
            pkInstalledPrinters = PrinterSettings.InstalledPrinters[i];
            comboInstalledPrinters.Items.Add(pkInstalledPrinters);
        }
    }					
    

    public by marceloviana  420  2  4  0

    Chamando função assincrona via console

    static void Main()
    {
        RunAsync().Wait();
    }
    
    private static async Task RunAsync()
    {
        …
    }

    public by marceloviana  926  0  4  0

    Converte string em UFT-8

    byte[] bytes = Encoding.Default.GetBytes(myString);
    myString = Encoding.UTF8.GetString(bytes);
    

    public by waxmiguel  2770  0  5  1

    tortouise

    # TortoiseGit 
    
    $Global:TortoiseGitSettings = new-object PSObject -Property @{
      TortoiseGitPath = "C:\Program Files\TortoiseGit\bin\TortoiseProc.exe"
    }
    
    function tgit {
       if($args) {
        if($args[0] -eq "help") {
          # Replace the built-in help behaviour with just a list of commands
          $tortoiseGitCommands
          return    
        }
    
        $newArgs = @()
        $newArgs += "/command:" + $args[0]
        
        $cmd = $args[0]
        
        if($args.length -gt 1) {
          $args[1..$args.length] | % { $newArgs += $_ }
        }
          
        & $Global:TortoiseGitSettings.TortoiseGitPath $newArgs
      }
    }
    
    $tortoiseGitCommands = @(
    "about",
    "log",
    "commit",
    "add",
    "revert",
    "cleanup" ,
    "resolve",
    "switch",
    "export",
    "merge",
    "settings",
    "remove",
    "rename",
    "diff",
    "conflicteditor",
    "help",
    "ignore",
    "blame",
    "cat",
    "createpatch",
    "pull",
    "push",
    "rebase",
    "stashsave",
    "stashapply",
    "subadd",
    "subupdate",
    "subsync",
    "reflog",
    "refbrowse",
    "sync"
    ) | sort
    
    • Public Snippets
    • Channels Snippets