Category: C#

How to cancel Parallel.ForEach

static void Main(string[] args) { List<RandomWait> waiters = new List<RandomWait>(); for (int i = 0; i < 1000; i++) { waiters.Add(new RandomWait()); } int counter = 0; ParallelOptions options = new ParallelOptions(); CancellationTokenSource cancelToken = new CancellationTokenSource(); options.MaxDegreeOfParallelism = 15; options.CancellationToken = cancelToken.Token; Task.Factory.StartNew(() => { Parallel.ForEach(waiters, options, (waiter) => { counter++; Console.WriteLine(counter); waiter.Pause(); counter–; Console.WriteLine(counter); }); }); Console.ReadLine(); cancelToken.Cancel();… Read more →

How to run code from sql server in c#

How to run code from sql server in c# SqlCommand cmd = new SqlCommand(“select Developer from Stackoverflow where UserID=’786′ and Developer=’Sufiyan'”, con); if (con.State == ConnectionState.Closed) { con.Open(); } SqlDataReader reader = cmd.ExecuteReader(); if (reader.Read()) { string codeSnippet = reader[“CodeSnippet”].ToString(); dynamic script = CSScript.LoadCode(@” using System; using System.Windows.Forms; using System.Collections.Generic; using System.Data; using System.Windows.Forms; using System.Data.SqlClient; public class RunFromSqlServer {… Read more →

OData Paging

Usage: using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Net.Http; using System.Web.Http; using System.Web.Http.OData.Query; namespace WebApiTest.Controllers { public class ValuesController : ApiController { private const int PAGESIZE = 25; // GET api/values [ActionName(“Default”)] public PageOfResults Get(ODataQueryOptions queryOptions) { var data = new Poco[] { new Poco() { id = 1, name = “one”, type = “a” }, new Poco()… Read more →

type safe enum extensions for MVC

extension method public static class EnumSelectList { public static IEnumerable GetList(this T thing) where T : IEnumerable { var result = from i in thing select new SelectListItem { Text = i.Value }; return result; } } new method on the type public static IEnumerable GetAll() { var list = ( from i in _instances select i.Value) .Cast(); return list;… Read more →

Deserialize this / Deserialize inside of the instance

Type type = this.GetType(); PropertyInfo[] properties = type.GetProperties(); reader.Read(); while (reader.Read()) { PropertyInfo property = properties.GetPropertyByXmlElement(reader.Name); if (property != null) { property.SetValue(this, reader.ReadElementContentAs(property.PropertyType, null)); } } this is the extension method `GetPropertyByXmlElement(string)` public static PropertyInfo GetPropertyByXmlElement(this PropertyInfo[] properties, string name) { XmlElementAttribute attr = new XmlElementAttribute(name); PropertyInfo property = ( from p in properties where p.GetCustomAttributes().Any(a => a.Equals(attr)) select p)… Read more →