Snippets Collections
public static int DiceSum4(IEnumerable<object> values)
{
    var sum = 0;
    foreach (var item in values)
    {
        switch (item)
        {
            case 0:
                break;
            case int val:
                sum += val;
                break;
            case IEnumerable<object> subList when subList.Any():
                sum += DiceSum4(subList);
                break;
            case IEnumerable<object> subList:
                break;
            case null:
                break;
            default:
                throw new InvalidOperationException("unknown item type");
        }
    }
    return sum;
}
DataTable dtTable;

MySQLProcessor.DTTable(mysqlCommand, out dtTable);

// On all tables' rows
foreach (DataRow dtRow in dtTable.Rows)
{
    // On all tables' columns
    foreach(DataColumn dc in dtTable.Columns)
    {
      var field1 = dtRow[dc].ToString();
    }
}
String.Join(",", myArray.Where(s => !string.IsNullOrEmpty(s)))
protected override void OnExit(ExitEventArgs e) {
    base.OnExit(e); 
}
class Car
{
    ~Car()  // destructor
    {
        // cleanup statements...
    }
}

protected override void Finalize()
{
    try
    {
        // Cleanup statements...
    }
    finally
    {
        base.Finalize();
    }
}

using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;

namespace AppsensPro.Infrastructure.Threading
{
    public sealed class KeyedLock<TKey>
    {
        /// <summary>
        /// Simple wrapper to allow counting how many references an object has
        /// </summary>
        /// <typeparam name="T"></typeparam>
        private sealed class RefCounted<T>
        {
            public RefCounted(T value)
            {
                RefCount = 1;
                Value = value;
            }

            public int RefCount { get; set; }
            public T Value { get; private set; }
        }

        /// <summary>
        /// Internally maintained dictionary of <see cref="SemaphoreSlim"/>
        /// </summary>
        private readonly Dictionary<TKey, RefCounted<SemaphoreSlim>> _semaphoreSlims
            = new Dictionary<TKey, RefCounted<SemaphoreSlim>>();

        /// <summary>
        /// Atomically get or create a value, with the associated <see cref="RefCounted{T}"/> incremented
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        private SemaphoreSlim GetOrCreate(TKey key)
        {
            RefCounted<SemaphoreSlim> item;
            lock (_semaphoreSlims)
            {
                if (_semaphoreSlims.TryGetValue(key, out item))
                {
                    ++item.RefCount;
                }
                else
                {
                    item = new RefCounted<SemaphoreSlim>(new SemaphoreSlim(1, 1));
                    _semaphoreSlims[key] = item;
                }
            }
            return item.Value;
        }

        /// <summary>
        /// Lock with specified key, returning a disposable <see cref="Releaser"/>
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public IDisposable Lock(TKey key)
        {
            GetOrCreate(key).Wait();
            return new Releaser(key, _semaphoreSlims);
        }

        /// <summary>
        /// Asynchronously lock with specified key, returning a disposable <see cref="Releaser"/>
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public async Task<IDisposable> LockAsync(TKey key)
        {
            await GetOrCreate(key).WaitAsync().ConfigureAwait(false);
            return new Releaser(key, _semaphoreSlims);
        }

        /// <summary>
        /// The returned Disposable <see cref="Releaser"/>.
        /// The lock will only be removed from dictionary if exists no reference left
        /// </summary>
        private sealed class Releaser : IDisposable
        {
            private TKey _key;
            private readonly Dictionary<TKey, RefCounted<SemaphoreSlim>> _locks;

            public Releaser(TKey key, Dictionary<TKey, RefCounted<SemaphoreSlim>> locks)
            {
                _key = key;
                _locks = locks;
            }
            
            public void Dispose()
            {
                RefCounted<SemaphoreSlim> item;
                lock (_locks)
                {
                    item = _locks[_key];
                    --item.RefCount;
                    if (item.RefCount == 0)
                        _locks.Remove(_key);
                }
                item.Value.Release();
            }
        }
    }
}
List<MyType> listName = dataTableName.AsEnumerable().Select(m => new MyType()
{
   ID = m.Field<string>("ID"),
   Description = m.Field<string>("Description"),
   Balance = m.Field<double>("Balance"),
}).ToList()
if(!String.IsNullOrEmpty(richTextBox_MWE.Text) && richTextBox_MWE.Text.Trim().Contains(textBox1.Text.Trim()))
{
  label5.BackColor = Color.Green;
}
    private void timer1_Tick_1(object sender, EventArgs e)
    {
        int x = panel2.Size.Width;
        int y = panel2.Size.Height;
        panel2.Size = new Size(x + 10, y);
        panel2.Location = new Point(panel2.Location.X - 10, panel2.Location.Y);
        if (x>150)
        {
            timer1.Stop();
        }
    }
private void btnChoose_Click(object sender, EventArgs e)
{

    MouseEventArgs b = new MouseEventArgs(System.Windows.Forms.MouseButtons.Left, 2, 
        MousePosition.X, MousePosition.Y, 0);
    DataGridViewCellMouseEventArgs a = new DataGridViewCellMouseEventArgs(0, 0, 
        MousePosition.X, MousePosition.Y, b);
    dataGridView1_CellMouseDoubleClick(sender, a);
}
    private void button6_Click(object sender, EventArgs e)
    {

        ListDataGridView_CellDoubleClick(this.ListDataGridView, new DataGridViewCellEventArgs(this.ListDataGridView.CurrentCell.ColumnIndex,this.ListDataGridView.CurrentRow.Index));

    }
var query = dTable.AsEnumerable().Where(r => r.Field<string>("col1") == "ali");

foreach(var row in query.ToList())
   row.Delete();
(new System.Diagnostics.StackTrace()).GetFrame(1).GetMethod().Name
string projectName = Assembly.GetCallingAssembly().GetName().Name;
(new System.Diagnostics.StackTrace()).GetFrame(1).GetMethod().Name
FileInfo oFileInfo = new FileInfo(strFilename);

if (oFileInfo != null || oFileInfo.Length == 0)
{
   MessageBox.Show("My File's Name: \"" + oFileInfo.Name + "\"");
   // For calculating the size of files it holds.
   MessageBox.Show("myFile total Size: " + oFileInfo.Length.ToString());
}
  using System.Linq;

  ...

  int[] y = File
    .ReadAllText(@"F:/C#/graph/graph/bin/Debug/y.txt")
    .Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries)
    .Select(item => int.Parse(item))
    .ToArray();

  string[] x = File
    .ReadAllText(@"F:/C#/graph/graph/bin/Debug/x.txt")
    .Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries)
    .ToArray();
   using(System.IO.StreamReader sr = new System.IO.StreamReader("F:/C#/graph/graph/bin/Debug/x.txt"))
    {
        string line;
        while((line = sr.ReadLine()) != null)
        {
            string[] x = line.Split(' ');
        }
    }

   using(System.IO.StreamReader sr = new System.IO.StreamReader("F:/C#/graph/graph/bin/Debug/y.txt"))
    {
        string line;
        while((line = sr.ReadLine()) != null)
        {
            string[] yString = line.Split(' ');
        }
        int[] y = Array.ConvertAll(yString , s => int.Parse(s));

    }
ucProducto uc = new ucProducto(this);
//resto codigo
Panel1.Controls.Add(uc);
public Image Base64ToImage(string base64String)
{
   // Convert Base64 String to byte[]
    byte[] imageBytes = Convert.FromBase64String(base64String);
    MemoryStream ms = new MemoryStream(imageBytes, 0, imageBytes.Length);

    // Convert byte[] to Image
    ms.Write(imageBytes, 0, imageBytes.Length);
    Image image = Image.FromStream(ms, true);

    return image;
}
var query1 = dtClone.AsEnumerable().Select(row => row.Field<string>("department")).Distinct().OrderBy(s => s);
Process myProcess = new Process(); 
Process.Start("notepad++.exe", "\"c:\\file name for test.txt\"");
private void openLog() {
            try {
                // see if notepad++ is installed on user's machine
                var nppDir = (string)Registry.GetValue("HKEY_LOCAL_MACHINE\\SOFTWARE\\Notepad++", null, null);
                if (nppDir != null) {
                    var nppExePath = Path.Combine(nppDir, "Notepad++.exe");
                    var nppReadmePath = Path.Combine(yourDirectory,fileName );
                    var line = 20;
                    var sb = new StringBuilder();
                    sb.AppendFormat("\"{0}\" -n{1}", nppReadmePath, lineNo);
                    Process.Start(nppExePath, sb.ToString());
                } else {
                    string newPath = @"\\mySharedDrive\notpad++\bin\notepad++.exe";
                    Process.Start(newPath, @"\\" + filePath + " -n" + lineNo); // take exe from my shared drive
                }
            } catch (Exception e) {
                Process.Start(@"\\" + FilePath); // open using notepad
            }
        }
using System.Runtime.InteropServices;

public const int WM_NCLBUTTONDOWN = 0xA1;
public const int HT_CAPTION = 0x2;

[DllImportAttribute("user32.dll")]
public static extern int SendMessage(IntPtr hWnd, int Msg, int wParam, int lParam);
[DllImportAttribute("user32.dll")]
public static extern bool ReleaseCapture();

private void Form1_MouseDown(object sender, System.Windows.Forms.MouseEventArgs e)
{     
    if (e.Button == MouseButtons.Left)
    {
        ReleaseCapture();
        SendMessage(Handle, WM_NCLBUTTONDOWN, HT_CAPTION, 0);
    }
}
public bool? IsActive { get; set; }

public string IsActiveDescriptor => IsActive.HasValue && IsActive ? "Yes" : "NO";
<div class="chart-wrapper">
@(Html.Kendo().Chart<ChartExample.Models.ChartModel>()
    .Name("chart")
    .Title("Example Column Chart")
    .Legend(legend => legend
        .Position(ChartLegendPosition.Top)
    )
    .DataSource(ds => ds.Read(read => read.Action("GetChartData", "Charts")))
    .Series(series => {
        series.Column(model => model.Val2).Name("Val2");
        series.Column(model => model.Val3).Name("Val3");
    })
    .CategoryAxis(axis => axis
        .Categories(model => model.Year)
        .Labels(labels => labels.Rotation(-90))
    )
    .ValueAxis(axis => axis.Numeric()
        .Labels(labels => labels.Format("{0:N0}"))
        .MajorUnit(10000)
    )
) 
</div>
public static MemoryStream GenerateStreamFromString(string value)
{
    return new MemoryStream(Encoding.UTF8.GetBytes(value ?? ""));
}
using System;
using System.Collections.Generic;

public class Program
{
    public static IEnumerable<int> GetRangeWithInverse( int count ) {
        for (var i = count; i > 0; i--) {
            yield return i;
            if (i > 1) {
                yield return count - i + 1;
            }
        }
    }

    public static void Main()
    {
        Console.WriteLine(string.Join( ',', GetRangeWithInverse( 10 ) ) );
    }
}
C:\Program Files\dotnet\sdk\1.0.0\NuGet.targets(97,5): error : Unable to load the service index for source https://{myaccount}.pkgs.visualstudio.com/_packaging/{myfeed}/nuget/v3/index.json.\r `[C:\Users\test\dotnet\dotnet.csproj]
C:\Program Files\dotnet\sdk\1.0.0\NuGet.targets(97,5): error :   Response status code does not indicate success: 401 (Unauthorized). [C:\Users\test\dotnet\dotnet.csproj]
<!DOCTYPE html>
<html>
<head>
<title>Font Awesome Icons</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
</head>
<body>

<h1>fa fa-heart</h1>

<i class="fa fa-heart"></i>
<i class="fa fa-heart" style="font-size:24px"></i>
<i class="fa fa-heart" style="font-size:36px;"></i>
<i class="fa fa-heart" style="font-size:48px;color:red"></i>
<br>

<p>Used on a button:</p>
<button style="font-size:24px">Button <i class="fa fa-heart"></i></button>

<p>Unicode:</p>
<i style="font-size:24px" class="fa">&#xf004;</i>

</body>
</html> 
public class MyClass : INotifyPropertyChanged
{
    private string imageFullPath;

    protected void OnPropertyChanged(PropertyChangedEventArgs e)
    {
        PropertyChangedEventHandler handler = PropertyChanged;
        if (handler != null)
            handler(this, e);
    }

    protected void OnPropertyChanged(string propertyName)
    {
        OnPropertyChanged(new PropertyChangedEventArgs(propertyName));
    }

    public string ImageFullPath
    {
        get { return imageFullPath; }
        set
        {
            if (value != imageFullPath)
            {
                imageFullPath = value;
                OnPropertyChanged("ImageFullPath");
            }
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;
}
string assemblyPath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
star

Thu Aug 04 2022 11:36:18 GMT+0000 (UTC) https://stackoverflow.com/questions/14252293/add-a-additional-condition-to-case-statement-in-switch

#cs #javascript
star

Fri Jul 22 2022 04:52:17 GMT+0000 (UTC) https://stackoverflow.com/questions/7939146/how-to-foreach-a-column-in-a-datatable-using-c

#cs
star

Mon Jul 11 2022 02:46:09 GMT+0000 (UTC) https://stackoverflow.com/questions/16325995/string-join-method-that-ignores-empty-strings

#cs
star

Sun Jul 03 2022 23:13:06 GMT+0000 (UTC) https://stackoverflow.com/questions/12977924/how-do-i-properly-exit-a-c-sharp-application

#cs
star

Tue Jun 28 2022 14:41:06 GMT+0000 (UTC) https://stackoverflow.com/questions/13988334/difference-between-destructor-dispose-and-finalize-method

#cs
star

Fri Jun 10 2022 04:36:02 GMT+0000 (UTC) https://stackoverflow.com/questions/55283882/an-asyncduplicatelock-that-can-be-locked-on-all-keys

#cs
star

Fri May 20 2022 20:17:17 GMT+0000 (UTC) https://stackoverflow.com/questions/1427484/convert-datatable-to-listt

#cs
star

Thu May 12 2022 21:09:22 GMT+0000 (UTC) https://stackoverflow.com/questions/24327330/using-like-operator-in-if-operator-in-c-sharp

#cs
star

Thu May 12 2022 15:25:20 GMT+0000 (UTC) https://stackoverflow.com/questions/45868364/change-panel-size-dynamically-from-right-to-left

#cs
star

Wed May 11 2022 15:28:13 GMT+0000 (UTC) https://stackoverflow.com/questions/39015557/how-to-call-datagridview-cell-double-click-event-from-a-button

#cs
star

Wed May 11 2022 15:24:30 GMT+0000 (UTC) https://stackoverflow.com/questions/39015557/how-to-call-datagridview-cell-double-click-event-from-a-button

#cs
star

Mon May 02 2022 18:55:02 GMT+0000 (UTC) https://stackoverflow.com/questions/18854395/how-to-delete-rows-from-datatable-with-linq

#cs
star

Mon May 02 2022 14:37:51 GMT+0000 (UTC) https://stackoverflow.com/questions/171970/how-can-i-find-the-method-that-called-the-current-method

#cs
star

Mon May 02 2022 14:37:44 GMT+0000 (UTC) https://stackoverflow.com/questions/18316683/how-to-get-the-current-project-name-in-c-sharp-code

#cs
star

Mon May 02 2022 14:37:27 GMT+0000 (UTC) https://stackoverflow.com/questions/171970/how-can-i-find-the-method-that-called-the-current-method

#cs
star

Thu Apr 28 2022 07:32:22 GMT+0000 (UTC) https://docs.telerik.com/devtools/winforms/knowledge-base/how-to-embed-chrome-browser-in-a-winforms-application

#cs
star

Wed Apr 27 2022 19:07:42 GMT+0000 (UTC) https://stackoverflow.com/questions/7861886/how-to-get-file-properties

#cs
star

Wed Apr 27 2022 19:05:24 GMT+0000 (UTC) https://stackoverflow.com/questions/54461489/i-want-to-replace-the-data-in-a-text-file-with-an-array-and-store-it-in-a-variab

#cs
star

Wed Apr 27 2022 18:59:55 GMT+0000 (UTC) https://stackoverflow.com/questions/54461489/i-want-to-replace-the-data-in-a-text-file-with-an-array-and-store-it-in-a-variab

#cs
star

Wed Apr 27 2022 18:59:17 GMT+0000 (UTC) https://stackoverflow.com/questions/20499878/how-to-open-a-url-in-new-window-using-webbrowser-control-in-c-sharp-windows-form

#cs
star

Wed Apr 27 2022 16:10:11 GMT+0000 (UTC) https://es.stackoverflow.com/questions/18133/como-puedo-tener-acceso-a-un-control-desde-un-formulario-hijo

#cs
star

Sat Apr 16 2022 03:07:08 GMT+0000 (UTC) https://stackoverflow.com/questions/18827081/c-sharp-base64-string-to-jpeg-image

#cs
star

Tue Mar 22 2022 01:23:17 GMT+0000 (UTC) https://stackoverflow.com/questions/56590444/unable-to-cast-object-of-type-grouping-to-datarow-after-i-grouped-datatable-with

#cs
star

Mon Mar 14 2022 20:05:22 GMT+0000 (UTC) https://stackoverflow.com/questions/38247311/open-file-for-reading-with-notepad-in-c-sharp

#cs
star

Mon Mar 14 2022 20:04:49 GMT+0000 (UTC) https://stackoverflow.com/questions/13755233/how-to-launch-a-process-which-will-open-a-text-file-in-any-editor-and-automatica

#cs
star

Fri Mar 11 2022 20:00:58 GMT+0000 (UTC) https://stackoverflow.com/questions/7286837/how-to-move-form-in-c-net

#cs
star

Wed Feb 23 2022 10:52:38 GMT+0000 (UTC) https://stackoverflow.com/questions/20338154/mvc-model-boolean-display-yes-or-no

#cs
star

Fri Jan 28 2022 22:54:28 GMT+0000 (UTC) https://stackoverflow.com/questions/11885183/kendoui-charts-with-asp-net-mvc

#cs
star

Tue Jan 19 2021 22:32:47 GMT+0000 (UTC) https://stackoverflow.com/questions/1879395/how-do-i-generate-a-stream-from-a-string

#cs
star

Thu Nov 12 2020 23:44:51 GMT+0000 (UTC) https://stackoverflow.com/questions/64813297/printing-number-with-for-loops-in-c-sharp

#cs
star

Wed Oct 07 2020 13:45:16 GMT+0000 (UTC) https://stackoverflow.com/questions/43098017/dotnet-restore-failing-when-mixing-private-nuget-feed-and-nest

#cs
star

Mon Aug 10 2020 11:03:32 GMT+0000 (UTC) https://www.w3schools.com/icons/tryit.asp?filename=tryicons_fa-heart

#html #cs #heart
star

Wed Jul 22 2020 21:22:57 GMT+0000 (UTC) https://stackoverflow.com/questions/2246777/raise-an-event-whenever-a-propertys-value-changed

#cs
star

Sun Jun 21 2020 06:50:46 GMT+0000 (UTC) https://stackoverflow.com/questions/38071639/c-sharp-get-assembly-executable-directory

#cs

Save snippets that work with our extensions

Available in the Chrome Web Store Get Firefox Add-on Get VS Code extension