28369998	28369762	c# WPF How to change only the content?	void OnBtnClick(...)\n{\n    List<Control> ctrls = new List<Control>(Controls); \n\n    Controls.Clear();\n\n    foreach(Control ctrl in ctrls )\n         ctrl.Dispose();\n\n    Controls.Add(new yourContrl());\n}	0
9680561	9680231	Session in a class	public class JobApplicantSession\n{\n    public JobApplication Application \n    {\n        get\n        {\n            return (JobApplication)HttpContext.Current.Session["Application"];\n        }\n        set\n        {\n            HttpContext.Current.Session["Application"] = value;\n        }\n    }\n}	0
17789920	17789663	select item listbox c#	var mySender = (ListBox)sender;\nswtich(((ListBoxItem)mySender.SelectedItem).Content.ToString()){\n\n  case "name 1":\n            MessageBox.Show("X");\n            break;\n  case "name 2":\n            MessageBox.Show("X");\n            break;\n  default:\n            break;\n}	0
1594608	1594600	How to easily display double quotes in strings in C#?	file.WriteLine("<controls:FormField Name=\"Strasse\" LabelText=\"Strasse\">");\nfile.WriteLine(@"<controls:FormField Name=""Strasse"" LabelText=""Strasse"">");	0
29270209	29016769	C# Instance Name to Use For Network Interface Performance Counter	PerformanceCounterCategory category = new PerformanceCounterCategory("Network Interface");\n    String[] instancename = category.GetInstanceNames();\n\n    foreach (string name in instancename)\n    {\n        Console.WriteLine(name);\n    }	0
20227269	20227078	How to Access the Undo Stack in Excel from C# via Office Interop?	Application.Undo	0
6349861	6349818	Search arraylist for keyword	string[] matches = arrayList.Cast<string>()\n                            .Where(i => i.StartsWith(searchTerm)).ToArray();	0
15895081	15894934	How to filter two DataTables in C#?	DataView dv = table1.AsDataView();\ndv.RowFilter = fexpression; // for example "MyID = 3"\nDataTable table2 = dv.ToTable();\n\n// If you want typed datatable, you can do it like this (although there are other ways):\nMyTypedDataTable table2 = new MyTypedDataTable();\nDataTable tempTable = dv.ToTable();\ntable2.Merge(tempTable);	0
3679071	3679049	"Store" a type parameter for later use in C#?	public void Set<T>(Tuple<string,T> key, T value) { /* stuff */ }	0
27702246	27702032	How to show different contextmenustrip in datagridview using c#	private void dataGridView1_MouseUp(object sender, MouseEventArgs e) {\n        if (e.Button != MouseButtons.Right) return;\n        var dgv = (DataGridView)sender;\n        ContextMenuStrip cms = null;\n        var hit = dgv.HitTest(e.X, e.Y);\n        switch (hit.Type) {\n            case DataGridViewHitTestType.ColumnHeader: cms = contextMenuStrip1; break;\n            case DataGridViewHitTestType.Cell: cms = contextMenuStrip2; break;\n        }\n        if (cms != null) cms.Show(dgv, e.Location);\n    }	0
10791046	10562051	How to "render" HTML without WebBrowser control	var sourceVal = webView.ExecuteJavascriptWithResult( "document.getElementsByTagName('html')[0].outerHTML;" );\n\nif ( sourceVal != null )\n{\n    using ( sourceVal )\n    {\n        html = sourceVal.ToString();\n    }\n}	0
1228818	1228783	RegEx Match Sequence of 5 characters	bool IsInSequence(string str, string sequence)\n{\n    return str != null && str.Length >= 5 && sequence.Contains(str);\n}	0
6023794	6023565	ARGB to YUV && Color Spaces in .NET	MemoryStream stream = new MemoryStream();\nbitmap.Save(stream, ImageFormat.Bmp);\nbyte[] data = stream.ToArray();	0
20203862	20201484	How can I replace an empty or null val with a default "base" value?	id = obj.Value<string>("Id") ?? "";\npackSize = obj.Value<short?>("PackSize") ?? (short)0;\nvar description = obj.Value<string>("Description") ?? "";\nvar deptSubdept = obj.Value<double?>("DeptDotSubdept") ?? 0.0;\nvar unitCost = obj.Value<double?>("Unit_Cost") ?? 0.0;\n...\nvar crvId = obj.Value<int>("CRV_Id") ?? 0;	0
1093713	1093393	Updating list with partial results of the search run in another thread	public void LoadDataAsync()\n    {\n        ...\n        BackgroundWorker bw = new BackgroundWorker();\n        bw.WorkerReportsProgress = true;\n        bw.DoWork += LoadChunk;\n        bw.ProgressChanged += new ProgressChangedEventHandler(ChunkLoaded);\n        bw.RunWorkerAsync();\n    }\n\n    void ChunkLoaded(object sender, ProgressChangedEventArgs e)\n    {\n       PopulateDataToUI();\n    }\n\n    private void LoadChunk(object sender, DoWorkEventArgs e)\n    {\n        int chunkNum = 0;\n        BackgroundWorker bw = (BackgroundWorker)sender;\n        bw.ReportProgress(chunkNum++);\n        while (true)\n        {\n           ...   \n           bw.ReportProgress(chunkNum++);\n           if (done) then break;\n        }\n    }	0
25745828	25745657	What is self hosting ? Can it be used with webapi to communicate with devices?	var config = new HttpSelfHostConfiguration("http://localhost:8080");\n\nconfig.Routes.MapHttpRoute(\n    "API Default", "api/{controller}/{id}", \n    new { id = RouteParameter.Optional });\n\nusing (HttpSelfHostServer server = new HttpSelfHostServer(config))\n{\n    server.OpenAsync().Wait();\n    Console.WriteLine("Running on port 8080 - Press Enter to quit.");\n    Console.ReadLine();\n}	0
34067195	34066852	WCF REST Service hosted in Console Application minimum example	[OperationContract]\n    [WebInvoke(Method = "GET", ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Bare, UriTemplate = "/Products/")]\n    List <Product> getProductList();\n\n    [OperationContract]\n    [WebInvoke(Method = "GET", ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Bare, UriTemplate = "/Product/{id}/")]\n    Product getProduct(string id);	0
705813	705767	Add property to LINQ that is combination of multiple tables?	public partial class Course\n{\n   public Category Category\n   {\n      get { return this.CourseCategories.SingleOrDefault().Category; }\n   }\n}	0
1665573	1664577	What is the best way to get a proper type name from a C# keyword?	private static Type GetTypeByFullNameOrAlias(string typeName)\n{\n  Type type = Type.GetType(typeName);\n\n  if (type == null)\n  {\n    using (var provider = new CSharpCodeProvider())\n    {\n      var compiler = provider.CompileAssemblyFromSource(\n        new CompilerParameters\n          {GenerateInMemory = true, GenerateExecutable = false, IncludeDebugInformation = false},\n        "public class A { public " + typeName + " B; }");\n\n      type = ((FieldInfo)compiler.CompiledAssembly.GetType("A").GetMember("B")[0]).FieldType;\n    }\n  }\n\n  return type;\n}	0
18954750	18949254	change cursor over a pictureBox	private void pictureBox1_MouseEnter(object sender, EventArgs e)\n    {\n        pictureBox1.SizeMode = PictureBoxSizeMode.StretchImage;\n        pictureBox1.Cursor = Cursors.Hand;\n    }\n\n    private void pictureBox1_MouseLeave(object sender, EventArgs e)\n    {\n        pictureBox1.SizeMode = PictureBoxSizeMode.Zoom;\n        pictureBox1.Cursor = Cursors.Default;\n    }	0
929086	929062	Problem accessing a MySQL database over ODBC	q.Read(); \nthis.Author = q.GetString(6);	0
8647764	8647703	C# multi-threading program with WebRequest	foreach (Record tmp in list)\n{\n  Record prov = tmp;\n? XMLResult.AppendText("Type: " + prov.Type + Environment.NewLine);\n\n? Thread t = new Thread(() => Send(prov, c)); ? ? ? ? ? ? ? ? ? ? ?	0
22939469	22939327	Accessing protected members in a different assembly	// In DLL 1\npublic class Class3 : class2\n{\n    public void ShowSample()\n    {\n        Console.WriteLine(sample);\n    }\n}	0
3839144	3839112	Why JSON empty string deserializes to null at the server side?	{ "var" : "" }	0
1686305	1686177	Leading Zero is dropped when converting a csv file to data table using oledb	char(4)	0
26267178	26265672	Get the combobox from data template in WPF DataGrid	FrameworkElement elmtTest = grdTest.Columns[7].GetCellContent(e.Row);\nComboBox myComboBox = FindVisualChild<ComboBox>(elmtTest);	0
6790133	6789960	Creating a file in Windows CE 5.0 in C#	private void saveFile()\n{\n    // If the File does not exist, create it!\n\n    if (! File.Exists("date.txt") ) // may have to specify path here!\n    {\n        // may have to specify path here!\n        File.Create("date.txt").Close();\n    }\n\n    // may have to specify path here!\n    StreamWriter swFile =\n                 new StreamWriter(\n                    new FileStream("date.txt",\n                                   FileMode.Truncate),\n                    Encoding.ASCII);\n\n    swFile.Write("some text");\n\n    swFile.Close();\n\n}	0
12569544	12569489	How to translate it into a ViewModel?	public class WrapperObject\n{\n   public String Name { get;set;}\n   public List<Options> {get;set;}\n}\n\npublic class Options\n{\n   public int Id { get; set;}\n   public String DisplayName { get; set; }\n}	0
27819156	27819102	Find Number of Characters in a specific line in text file	var file = new StreamReader(@"D:\ValidFile.txt");\nstring line = null;\nint lineNumber = 0;\nwhile((line = file.ReadLine()) != null)\n{\n   Console.WriteLine("Line " + (lineNumber++) + ": " + line.Length);\n}	0
26992938	26992698	Deserialize nested JSON Response with JSON.NET	public class PocoCourse\n{\n    public bool Success { get; set; }\n    public string Message { get; set; }\n    public List<PocoCourseType> Types { get; set; }\n}\n\npublic class PocoCourseType\n{\n    public string Name { get; set; }\n    public string Title { get; set; }\n    public string ClassroomDeliveryMethod { get; set; }\n    public PocoCourseTypeDescriptionContainer Descriptions { get; set; }\n    public DateTime LastModified { get; set; }\n    public DateTime Created { get; set; }\n}\n\npublic class PocoCourseTypeDescription\n{\n    public string Description { get; set; }\n    public string Overview { get; set; }\n    public string Abstract { get; set; }\n    public string Prerequisits { get; set; }\n    public string Objective { get; set; }\n    public string Topic { get; set; }\n}\npublic class PocoCourseTypeDescriptionContainer\n{\n    public PocoCourseTypeDescription EN { get; set; }\n    public PocoCourseTypeDescription DE { get; set; }\n}	0
20393976	20393265	A route named 'DefaultApi' is already in the route collection	config.Routes.MapHttpRoute(\n            name: "DefaultApi",\n            routeTemplate: "rest/{controller}/{id}",\n            defaults: new { id = RouteParameter.Optional }\n        );	0
31842990	31842353	Accessing a text file in a WPF project	var uri = new Uri("pack://application:,,,/Subfolder/TextFile.txt");\nvar resourceStream = Application.GetResourceStream(uri);\n\nusing (var reader = new StreamReader(resourceStream.Stream))\n{\n    var text = reader.ReadToEnd();\n    ...\n}	0
16671473	16658713	How to notify about changing property of ListBox item?	var foundItem = shoppingList.FirstOrDefault(p => p.ean == item.ean);\n            if (foundItem != null)\n            {\n                foundItem.Amount += 1;\n                item.Amount = foundItem.Amount;\n            }	0
4095342	4095283	Custom Combining 4 dictionaries	var keys = dict1.Keys.Union(dict2.Keys).Union(dict3.Keys).Union(dict4.Keys);\nvar result = new Dictionary<string,List<string>>();\nforeach(var key in keys) {\n    List<string> list = new List<string>();\n    list.Add(dict1.ContainsKey(key) ? dict1[key] : "");\n    list.Add(dict2.ContainsKey(key) ? dict2[key] : "");\n    list.Add(dict3.ContainsKey(key) ? dict3[key] : "");\n    list.Add(dict4.ContainsKey(key) ? dict4[key] : "");\n    result.Add(key, list);\n}	0
3492857	3492840	Find the largest value smaller than x in a sorted array	int[] arr = { 1, 23, 57, 59, 120 };\nint index = Array.BinarySearch(arr, 109);\nif (index < 0)\n{\n    index = ~index - 1;\n}\nif (index >= 0)\n{\n    var result = arr[index];\n}	0
3688111	3688052	XML Doc - null handling	for (int i = 0; i < ds.Tables[0].Columns.Count; i++ )\n{\n    DataColumn col = ds.Tables[0].Columns[i] != null ? ds.Tables[0].Columns[i] : "<some default value>";\n    if (col != "<some default value>")\n                    // do something\n}	0
7651312	7650994	How to get out of repetitive if statements?	public string DataField(int id, string fieldName)\n    {\n        var data = _dataRepository.Find(id);\n\n        List<string> props = new List<string>();\n        props.Add("A");\n        props.Add("B");\n        props.Add("C");\n\n        if (data != null)\n        {\n            Type t = typeof(data).GetType();\n            foreach (String entry in props) {\n                PropertyInfo pi = t.GetProperty(entry);\n                if (pi.GetValue(data) == null) {\n                    pi.SetValue(data, fieldName);\n                    _dataRepository.InsertOrUpdate(data);\n                    return entry;\n                }\n            }\n        }\n    }	0
9335808	9335600	Is there a way to duplicate or make another copy of an XmlNodeList in C#?	var xd = new XmlDocument();\n    xd.LoadXml("<root><nodes><node>1</node><node>2</node></nodes></root>");\n    var xnl = xd.SelectSingleNode("/root/nodes").Clone();\n\n    foreach (XmlNode n in xnl)\n    {\n        n.InnerText = "x";\n    }\n\n    Console.Out.WriteLine(xd.OuterXml);\n    Console.Out.WriteLine("--------------");\n    Console.Out.WriteLine(xnl.OuterXml);	0
4772320	4772301	Removing \r from lines read from file	fileOutput.Replace("\r","")	0
27254929	27252327	Pass POST variables with Windows Phone App	using (var client = new HttpClient())\n            {\n                client.BaseAddress = new Uri("baseUrl.net");\n                var content = new FormUrlEncodedContent(new[]\n            {\n                new KeyValuePair<string, string>("Title", "test")\n            });\n\n                var result = await client.PostAsync("/insert.php", content);\n                string resultContent = "result: "+result.Content.ReadAsStringAsync().Result;	0
13729010	13728797	Custom Sort of ObservableCollection<T> with base type	var result = Children.OfType<ItemA>().OrderBy(a => a.ItemAName).Cast<Base>()\n    .Concat(Children.OfType<ItemB>().OrderBy(b => b.ItemBName));	0
23616058	23614893	SQL to LINQ Statement including Group By and Order By	var resultList = Table2\n            .Where(x => x.DateTime > begDate && x.DateTime < endDate)\n            .Join(Table1, t2 => t2.AccountId, t1 => t1.Id,\n                (t2, t1) => new { t2.AccountId, t1.Description })\n            .GroupBy(x => x.AccountId)\n            .Select(g => new { Group = g, Charges = g.Count() })\n            .OrderByDescending(g => g.Charges)\n            .SelectMany(g => g.Group.Select(x => new { x.Description, x.AccountId, g.Charges }))\n            .ToList();	0
21106756	21089792	Access Resource File Content in ASP.NET	var assembly = Assembly.GetExecutingAssembly();\nstring resourceName = (string)HttpContext.GetGlobalResourceObject("Resource1", "MyTemplate");\nstring mystring = "";\nmystring = resourceName;\nmystring = mystring.Replace("$$Member$$", name);\nmystring = mystring.Replace("$$Subject$$", TxtSubject.Text);\nreturn mystring;	0
2325381	2325192	what's the purpose of wraping a generic interface?	IMapper<T, TViewModel>	0
14054642	14054622	'+' gets stored as '%2b' in sql server	var decoded = HttpUtility.UrlDecode(input);	0
14446307	14445781	How can I decode text?	Regex regex = new Regex(@"\\u([a-f0-9]{4})", RegexOptions.IgnoreCase);\nString result = regex.Replace(result, match => ((Char)Int32.Parse(match.Value.Substring(2), NumberStyles.HexNumber)).ToString());	0
16181659	16051922	Sending an Email asynchronously via ActionMailer	string url = baseUrl + "/api/Entry/SendEmail?emailId=" + emailId;\nWebRequest req = WebRequest.Create(url);\nreq.Method = "GET";\nreq.BeginGetResponse(null, null);	0
10190842	10157336	Solver Foundation Optimization - 1D Bin Packing	Model[ \n  Parameters[Sets,Items,Bins], \n  Parameters[Integers,OrderWidth[Items],BinWidth[Bins]], \n\n  Decisions[Integers[0,1],x[Items,Bins]], \n  Decisions[Integers[0,1],y[Bins]], \n\n  Constraints[    \n    Foreach[{i,Items},Sum[{j,Bins}, x[i,j]]==1 ], \n    Foreach[{j,Bins}, Sum[{i,Items}, OrderWidth[i]*x[i,j]] <= BinWidth[j]], \n    Foreach[{i,Items},{j,Bins}, y[j] >= x[i,j]] \n  ], \n\n  Goals[Minimize[UsedBins->Sum[{j,Bins},y[j]]]] \n]	0
27040413	27031778	Unity, C# | How do I have a wait time between methods?	using UnityEngine;\nusing System.Collections;\n\npublic class SnailMove : MonoBehaviour\n{\n    public float speed = 1f;\n    int direction = 0;\n    void Start()\n    {\n        StartCoroutine(ChangeDirection());\n    }\n\n    void Update () \n    {\n        if (direction == 1) \n        {\n            transform.Translate(Vector3.left * speed * Time.deltaTime);\n            transform.eulerAngles = new Vector2(0,180);\n        }\n        else if (direction == -1)\n        {\n            transform.Translate(Vector3.left * speed * Time.deltaTime);\n            transform.eulerAngles = new Vector2(0,0);\n        }\n    }\n\n    IEnumerator ChangeDirection()\n    {\n        while(true)\n        {\n            yield return new WaitForSeconds (5);\n            direction = Random.Range(-1, 2); // returns "-1", "0" or "1"\n        }\n    }\n}	0
34014372	33153277	How to design inheritance for multilevel composition classes	public abstract class A { };\n    public class A1 : A { };\n    public class A2 : A { };\n\n    public abstract class B<T> where T : A {\n        public T A_obj { get; set; }\n    };\n    public class B1 : B<A1>\n    { \n    };\n\n    public class B2 : B<A2>\n    {\n    };\n\n    public abstract class C<T, U> where T : B<U> where U : A\n    {\n        public List<T> B_objs { get; private set; }\n\n        public C() {\n            B_objs = new List<T>();\n        }\n    };\n\n    public class C1 : C<B1, A1>\n    {\n    };\n\n    public class C2 : C<B2, A2>\n    {\n    };\n\n    public static void Test()\n    {\n        A1 a1 = new A1();\n        B1 b1 = new B1();\n        b1.A_obj = a1;\n\n        A2 a2 = new A2();\n        B2 b2 = new B2();\n        b2.A_obj = a2;\n\n        // The following line fails: cannot implicitly convert A1 to A2\n        //b2.A_obj = a1;\n\n        C1 c1 = new C1();\n        c1.B_objs.Add(b1);\n\n        // The following fails:\n        // c1.B_objs.Add(b2);\n    }	0
21864286	21863587	Button Click Event doesn't fire when clicking same button twice in a row	private void uxNumber_MouseDown(object sender, MouseButtonEventArgs e)\n{\n    if (e.LeftButton == MouseButtonState.Pressed)\n    {\n            int num = Convert.ToInt32(((GradientButton)sender).Text);\n\n        if (this.uxPIN.Text.Length < 4)\n            uxPIN.Text += num;    \n        else\n        SystemSounds.Beep.Play();\n    }\n\n}	0
17402624	17402383	Control Characters in Resource files C#	&#x200e;	0
26210239	26210134	Having trouble with IgnoreCase	string UserInput = Console.ReadLine().ToLowerInvariant();\n\n...\n\nif (Arr[row, column].ToLowerInvariant().Contains(UserInput))	0
18864715	18864125	Fetching EMail Based on From Address or Subject	public void check()\n    {\n        string sub;\n        string result,from;\n        int i = 1;\n        do\n        {\n            ImapClient ic = new ImapClient("imap.mail.yahoo.com", "user@yahoo.com", "password", ImapClient.AuthMethods.Login, 993, true);\n            ic.SelectMailbox("INBOX");\n            int n = ic.GetMessageCount();\n\n            MailMessage mail = ic.GetMessage(n - i);\n            ic.Dispose();\n            sub = mail.Subject;\n            from = mail.From.ToString();\n            result = mail.Raw;\n\n            i++;\n        } while (sub != "subject" || from == "person@example.com");\n        string mailmsg = result;\n    }	0
23562660	23561637	Update a single row in DataTable	void Main()\n{\n    DataTable tableOld = new DataTable();\n    tableOld.Columns.Add("ID", typeof(int));\n    tableOld.Columns.Add("Name", typeof(string));\n\n    tableOld.Rows.Add(1, "1");\n    tableOld.Rows.Add(2, "2");\n    tableOld.Rows.Add(3, "3");\n\n    DataTable tableNew = new DataTable();\n    tableNew.Columns.Add("ID", typeof(int));\n    tableNew.Columns.Add("Name", typeof(string));\n\n    tableNew.Rows.Add(1, "1");\n    tableNew.Rows.Add(2, "2");\n    tableNew.Rows.Add(3, "33");\n\n    tableOld.Rows[2].ItemArray = tableNew.Rows[2].ItemArray; //update specific row of tableOld with new values\n\n    //tableOld.Dump();\n}	0
18601211	18600924	Web API hide field from consumer of service	[JsonIgnore]\n    [XmlIgnore]\n    public string InternalID { get; set; }	0
31339696	31339304	Custom indent for default xmlns attribute wile writing through XmlWriter	var sb = new StringBuilder();\nvar writer = XmlWriter.Create(sb, new XmlWriterSettings\n{\n    OmitXmlDeclaration = true,\n});\n\nusing (writer)\n{\n    writer.WriteStartElement("x", "node", "uri:special-x");\n    writer.WriteAttributeString("xmlns", "uri:default");\n    writer.Flush();\n    sb.Append("\n" + new string(' ', 7));\n    writer.WriteAttributeString("xmlns", "x", null, "uri:special-x");\n    writer.Flush();\n    sb.Append("\n" + new string(' ', 7));\n    writer.WriteAttributeString("xmlns", "y", null, "uri:special-y");\n    writer.Flush();\n    sb.Append("\n" + new string(' ', 7));\n    writer.WriteAttributeString("name", "uri:special-y", "vd");\n    writer.Flush();\n    sb.Append("\n" + new string(' ', 7));\n    writer.WriteAttributeString("SomeOtherAttr", "ok");            \n    writer.WriteEndElement();\n}	0
21864061	21414309	Sprache: parse signed integer	from op in Parse.Optional(Parse.Char('-').Token())\nfrom num in Parse.Decimal\nfrom trailingSpaces in Parse.Char(' ').Many()\nselect decimal.Parse(num) * (op.IsDefined ? -1 : 1);	0
19740448	19740406	c# - deserialization of specific JSON	var jsonValues = JsonConvert.DeserializeObject(someJsonString);\nvar pocoValue = JsonConvert.DeserializeObject<YourClass>(someJsonString);\n// or as a dictionary:\nvar dictionary = JsonConvert.DeserializeObject<Dictionary<MyClass>>(someJsonString);	0
31485571	31485380	Disable a group of buttons' Interactable state by Tag	public void HandleActiveKeySet (bool keySet)\n{\n    if(keySet == true)\n    {\n        GameObject alphaGroup = GameObject.FindGameObjectWithTag("AlphaGroup");\n        alphaGroup.GetComponent<CanvasGroup>().interactable = true;\n        alphaGroup.GetComponent<CanvasGroup>().blocksRaycasts = true;\n\n        GameObject symbolGroup = GameObject.FindGameObjectWithTag("SymbolGroup");\n        symbolGroup.GetComponent<CanvasGroup>().interactable = false;\n        symbolGroup.GetComponent<CanvasGroup>().blocksRaycasts = false;\n    }\n    else\n    {\n        GameObject alphaGroup = GameObject.FindGameObjectWithTag("AlphaGroup");\n        alphaGroup.GetComponent<CanvasGroup>().interactable = false;\n        alphaGroup.GetComponent<CanvasGroup>().blocksRaycasts = false;\n\n        GameObject symbolGroup = GameObject.FindGameObjectWithTag("SymbolGroup");\n        symbolGroup.GetComponent<CanvasGroup>().interactable = true;\n        symbolGroup.GetComponent<CanvasGroup>().blocksRaycasts = true;\n    }\n}	0
15807703	15807191	C# How to get data into an array within an array	for (int j = 0; j < MAX_SONG; j++)\n            {\n                if (Songs[i] == null)\n                {\n                    index = i;\n                    break;\n                }\n            }	0
18758562	18757982	Windows Phone navigate to new instance of same page	NavigationService.Navigate(new Uri("/MainPage.xaml?ID="+ a.MyID, UriKind.Relative));\na.MyID++;	0
20966736	20966635	how to select values from listview column	private void button1_Click(object sender, EventArgs e)\n    {\n        int totalPrice = 0;\n        for(int i=0;i<listView1.Items.Count;i++)\n        {\n            totalPrice += Convert.ToInt32(listView1.Items[i].SubItems[2].Text);\n        }\n\n    }	0
390349	390326	C# calling overridden subclass methods without knowledge that it's a subclass instance	class Foo \n{\n    public virtual void virtualPrintMe()\n    {\n        nonVirtualPrintMe();\n    }\n\n    public void nonVirtualPrintMe()\n    {\n        Console.Writeline("FOO");\n    }\n}\n\nclass Bar : Foo \n{\n    public override void virtualPrintMe()\n    {\n        Console.Writeline("BAR");\n    }\n}\n\nList<Foo> list = new List<Foo>();\n// then populate this list with various 'Bar' and other overriden Foos\n\nforeach (Foo foo in list) \n{\n    foo.virtualPrintMe(); // prints BAR or FOO\n    foo.nonVirtualPrintMe(); // always prints FOO\n}	0
12005918	12005719	c# set ListBox to RTL	private void listBox1_DrawItem(object sender, DrawItemEventArgs e)\n{\n    MyListBoxItem item = listBox1.Items[e.Index] as MyListBoxItem; // Get the current item and cast it to MyListBoxItem\n    if (item != null)\n    {\n        e.Graphics.DrawString( // Draw the appropriate text in the ListBox\n                   item.Message, // The message linked to the item\n                   listBox1.Font, // Take the font from the listbox\n                   new SolidBrush(item.ItemColor), // Set the color \n                   width - 4, // X pixel coordinate\n                   e.Index * listBox1.ItemHeight,\n                   new StringFormat(StringFormatFlags.DirectionRightToLeft)); // Y pixel coordinate.  Multiply the index by the ItemHeight defined in the listbox.                \n    }\n    else\n    {\n        // The item isn't a MyListBoxItem, do something about it\n    }\n}	0
10931763	10931642	How can I make sure a url provided by the user is not a local path?	new Uri(@"http://stackoverflow.com").IsLoopback\nnew Uri(@"http://localhost/").IsLoopback\nnew Uri(@"c:\windows\").IsLoopback	0
5572060	5571963	How to get DataGridView cell value in messagebox?	MessageBox.Show(dataGridView1.SelectedCells[0].Value.ToString());	0
2509314	2508930	Creating a custom TabPage control in C#	// form scoped variable to hold a referece to the current UserControl\n    private UserControl1 currentUserControl;\n\n    private void Form1_Load(object sender, EventArgs e)\n    {\n        foreach(TabPage theTabPage in tabControl1.TabPages)\n        {\n            currentUserControl = new UserControl1();\n\n            theTabPage.Margin = new Padding(0);\n            theTabPage.Padding = new Padding(0);\n\n            theTabPage.Controls.Add(currentUserControl);\n\n            currentUserControl.Location = new Point(0,0);\n\n            currentUserControl.Dock = DockStyle.Fill;\n\n            currentUserControl.SendToBack();\n        }\n    }	0
27537422	27537399	Exclude the number zero from modolus in an if statement	if ( r == 0){...}	0
11856934	11856868	Parsing XML data into RichTextBox but Only One Item Appeared in Result	XmlDocument xmlDoc = new XmlDocument(); //* create an xml document object.\n        xmlDoc.Load("tsco.xml"); //* load the XML document from the specified file.\n\n        richComResults.Text = string.Empty;\n\n        XmlElement root = xmlDoc.DocumentElement;\n        XmlNodeList nodes = root.SelectNodes("item"); // You can also use XPath here\n        StringBuilder sb = new StringBuilder();\n\n        foreach (XmlNode node in nodes)\n        {                \n            foreach (XmlNode child in node.ChildNodes)\n                sb.AppendLine(string.Format("{0}:\t{1}", child.Name,  child.FirstChild == null ? string.Empty : child.FirstChild.Value));                \n        }\n        richComResults.Text = sb.ToString();	0
435137	435049	There is a way to pass-by-reference using variable parameters in C#?	using System;\n\nnamespace unsafeTest\n{\n    class MainClass\n    {\n        public static void Main(string[] args)\n        {\n            Console.WriteLine("Hello World!");\n            unsafe \n            {   \n                int x = 0;\n                int y = 0;\n                int z = 0;\n                bar(&x, &y, &z);\n                Console.WriteLine(x);\n                Console.WriteLine(y);\n                Console.WriteLine(z);\n            }\n        }\n\n        unsafe static void bar(params int *[] pInts)\n        {\n            int i = 0;\n            foreach (var pInt in pInts)\n            {\n            *pInt = i++;\n            }\n        }\n    }\n}	0
15048507	15044419	HTMLAgilityPack and marshaling clicked signal	HtmlDocument doc= new HtmlDocument();\n\ndoc.Load(@"C:\..\page.html");\n\nHtmlNodeCollection nodes = doc.DocumentNode.SelectNodes("//a");\n\nforeach (HtmlNode node in nodes)\n{\n    if(node.OuterHtml.Contains("href"))\n        Console.WriteLine(node.Attributes["href"].Value);\n}	0
11463800	11463734	Split a List into smaller lists of N size	public static List<List<float[]>> splitList(List <float[]> locations, int nSize=30)  \n{        \n    var list = new List<List<float[]>>(); \n\n    for (int i=0; i < locations.Count; i+= nSize) \n    { \n        list.Add(locations.GetRange(i, Math.Min(nSize, locations.Count - i))); \n    } \n\n    return list; \n}	0
16016230	16016065	Skipping compilation of a method depending on operating system or framework	#if CE\n ....\n#else\n ...\n#endif	0
6374002	6373908	How do you insert multiple records at once in LINQ to SQL while calling a sequence retrieval function on every insert	var db = new StoreDataContext();\nusing(var scope = new TransactionScope()){        \n    foreach(var p in payments){\n        db.payments.Insert(new payment \n                          {    order_fk = p.order_fk, \n                               line_no = DbMethods.GetNextLine(p.order_fk),     \n                                amount = p.amount\n                          });\n        db.SubmitChanges(ConflictMode.FailOnFirstConflict);\n    }\n    scope.Complete();\n}	0
27744943	27744901	How to get the index out from the string	var x = "FundList[10].Amount";\nint xIndex = Convert.ToInt32(Regex.Match(x,@"\d+").Value); //10	0
20004168	19929274	How to get Particular cell value from Previous row to Current Row in Gridview ?? Winforms Devexpress	object Value = MyGridView.GetRowCellValue("ColumnName", MyGridView.FocusedRowHandle - 1);	0
7412328	7357407	Input string not in correct format SPSite	string site_Str= "http://<serverName>:<PortNumber>";\nSPSite site=new SPSite(site_Str);	0
25143913	25143518	Temporary lock windows (re)size in WPF	this.ResizeMode = System.Windows.ResizeMode.NoResize;	0
19104227	19103796	How to add multiple markers in leaflet via codebehind	StringBuilder startupScript = new StringBuilder();\nstartupScript.Append(@"<script language=""Javascript"">");\nfor (int i = 0; i < lat.Length; i++)\n{\n    startupScript.AppendFormat(@"addMarker('{0}','{1}'); ", lat[i], lng[i]);\n}\nstartupScript.Append(@"</script>");\nPage.ClientScript.RegisterStartupScript(this.GetType(), "onMapClick", startupScript.ToString());	0
12961334	12961250	Issue with rendering control on Async postback	var prm = Sys.WebForms.PageRequestManager.getInstance();\nprm.add_endRequest(onEndRequest);\n\nfunction onEndRequest(sender, args){    \n   demoGauge1.init();       \n}	0
9306156	9306082	Convert a DataTable to a Dictionary<T1,T2> using Generics and extension methods	public static class Extensions\n        {\n            public static Dictionary<TKey, TRow> TableToDictionary<TKey,TRow>(\n                this DataTable table,\n                Func<DataRow, TKey> getKey,\n                Func<DataRow, TRow> getRow)\n            {\n                return table\n                    .Rows\n                    .OfType<DataRow>()\n                    .ToDictionary(getKey, getRow);\n            }\n        }\n\n\n\n        public static void SampleUsage()\n        {\n            DataTable t = new DataTable();\n\n            var dictionary = t.TableToDictionary(\n                row => row.Field<int>("ID"),\n                row => new {\n                    Age = row.Field<int>("Age"),\n                    Name = row.Field<string>("Name"),\n                    Address = row.Field<string>("Address"),\n                });\n        }	0
16450435	16450391	A lambda expression with a statement body cannot be converted to an expression tree	System.Linq.Expressions	0
13868223	13717189	Show series value over any point on chart using tooltip c#	private void chData_MouseMove(object sender, MouseEventArgs e)\n    {\n        try\n        {   \n            int cursorX = Convert.ToInt32(chData.ChartAreas[0].AxisX.PixelPositionToValue(e.Location.X));\n\n            tipInfo = "Bat 1: " + ch1Array[cursorX].ToString("0.00") + Environment.NewLine + "Bat 2: " + ch2Array[cursorX].ToString("0.00") + Environment.NewLine;\n\n            tooltip.SetToolTip(chData, tipInfo);\n\n        }\n        catch { }\n    }	0
6464269	6457143	How to Set Properties in Sharepoint dynamically?	Controls.Add(control)	0
22251917	22251057	How to add more than one list box in windows phone 7	ScrollViewer.VerticalScrollBarVisibility="Disabled"	0
25448820	25446517	Refresh template custom control after clearing and re-adding MergedDictionaries	Try messageBar.ApplyTemplate() before calling GetChildOfType	0
11254725	11254609	Trying to get a string that represents a class heirachy	public class Class1 { }\n    public class Class2 : Class1 { }\n    public class Class3 : Class2 { }\n\n    private void button1_Click(object sender, EventArgs e)\n    {\n        Class3 c3 = new Class3();\n        Console.WriteLine(TypeToString(c3.GetType()));\n    }\n\n    private string TypeToString(Type t)\n    {\n        if (t == null)\n            return "";\n        if ((t.BaseType == null) || (t.BaseType == typeof(object)))\n            return t.Name;\n        return TypeToString(t.BaseType) + "." + t.Name;\n    }	0
1072207	1072158	Validate XML Syntax Only in C#	XElement.Load()	0
13781133	13781099	Parameter constraints without generics	public ISomeInterface GetDefaultValue(ISomeInterface theObject)\n{\n  ...\n}	0
2250506	2250490	Mark users coming to website from my application	string url = "http://mysite/somepage?source=myApplication";\nSystem.Diagnostics.Process.Start(url);	0
13645809	13645703	How search for HTML elements in StreamReader or String	HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();\ndoc.LoadHtml(htmlText);\n\nvar div = doc.DocumentNode.SelectSingleNode("//div[@id='bodyDiv']");\nif(div!=null)\n{\n    var yourtext = div.InnerText;\n}	0
11179315	11178917	Securing access to editing user details	public interface IUserAdapter\n{\n    IPrincipal GetUserPrincipal();\n    void SetAuthenticationCookie(IUser user);\n    void SignOut();\n}\n\n// my business logic representation of a user\npublic interface IUser\n{\n    int Id { get; set; }\n    string Name { get; set; }\n}\n\npublic class WebUserAdapter : IUserAdapter\n{\n    public IPrincipal GetUserPrincipal()\n    {\n        return HttpContext.Current.User;\n    }\n\n    public void SetAuthenticationCookie(IUser user)\n    {\n        FormsAuthentication.SetAuthCookie(user.Id.ToString(), false);\n    }\n\n    public void SignOut()\n    {\n        FormsAuthentication.SignOut();\n    }\n}	0
17588908	17588713	How to add multiple bytes and get a byte array?	byte checksum;\nforeach (var b in someBytes)\n{\n    checksum = (byte)((checksum + b) & 0xff);\n}	0
5562543	5556296	IsSetData in gridcontrol is never true when clicking on checkEdit item	private void gridView1_CustomUnboundColumnData(object sender, CustomColumnDataEventArgs e) {\n            GridView gridView = sender as GridView;\n            DataView dv = gridView.DataSource;\n            object c = DataView[e.ListSourceRowIndex]["Category"];\n            string itemKey = c == null ? "" : c.ToString();\n            if (e.IsGetData) {\n                if(AddressDoc == itemKey)\n                    e.Value = true;\n                else \n                    e.Value = false;\n            }\n            if(e.IsSetData)\n                AddressDoc = itemKey;\n        }	0
685334	512553	Is there a way to measure the the amount of a string that will fit into a printed area without using the graphics object?	Size size = TextRenderer.MeasureString(this.Text, this.Font);	0
25131479	25131356	Entity Framework Eager load only a subset of other tables	var result = _context.Set<Document>()\n    .Where(d => d.IsActive)\n    .Select(d =>\n    new\n    {\n        Document = d,\n        Sections = d.Sections.Where(s => s.IsActive)\n    })\n    .ToArray().Select(anonymous => anonymous.Document).ToArray();	0
1896310	1896296	How to make sure a POST is requested from specific domain?	Request.ServerVariables["HTTP_REFERER"]	0
15584442	15584410	c# Set the value of combobox and texbox in the same foreach loop	var StringInput = new Control[] { preInput1, preInput5, postInput1, postInput5};\nint stringCount1 = 0;\nint toto = (ArrayCount + StringInput.Length);\n\nforeach (var c in StringInput)\n{\n  c.Text = Convert.ToString(energyCalculation.Cells[place[xCSV]].Value);\n  xCSV++;\n  //stringCount1++;\n  ArrayCount++;\n}	0
2456597	2456581	vs2003: identify first row in DataRow[]	bool isFirst = true;\n\nforeach(DataRow row in myrows)\n{\n    if (isFirst)\n    {\n        isFirst = false;\n        ...do this...\n    }\n    else\n    {\n        ....process other than first rows..\n    }\n}	0
26224255	26223870	Ordering entities based on other entity content	var query = conversations.OrderByDescending(c => c.Messages.Max(m => n.CreationDate))	0
10858268	10858103	Deserialize arbitrary JSON object with JSON.NET	yourString = yourString.Replace("\"list\":[]", "\"list\":{}");	0
925268	925034	Using SqlServer uniqueidentifier/updated date columns with Linq to Sql - Best Approach	partial void InsertTest(Test instance)\n{\n    instance.idCol = System.Guid.NewGuid();\n    this.ExecuteDynamicInsert(instance);\n}\n\npartial void UpdateTest(Test instance)\n{\n    instance.changeDate = DateTime.Now;\n    this.ExecuteDynamicUpdate(instance);\n}	0
27673262	27672628	How can i get value from SQL functions on c#	var con = new SqlConnection("Data Source=.;Initial Catalog=Project;Integrated Security=true;");\nvar cmd =new SqlCommand();\ncmd.Connection = con;\n\ncmd.CommandType = CommandType.Text;\ncmd.CommandText = "select dbo.[EnPahaliYemek](@yemekk);";    \ncmd.Parameters.AddWithValue("@yemekk", "whatever");\n\ncon.Open();\nlabel1.Text = cmd.ExecuteScalar().ToString();\ncon.Close();	0
19639760	19639577	Regex for substring between two known tags that might appear more than once	var match = Regex.Match(myStr, @"/([^/]+)\.stream\b");\nstring extracted = match.Groups[1].Value;\nConsole.WriteLine(extracted); // "unreachable"	0
30732537	30731528	Unauthorised access to folders when creating xml file	DirectoryInfo info = Directory.CreateDirectory(myPath);	0
1930206	1930196	What's the easiest way to generate a List<int> of ordered numbers in C#?	List<int> steporders = Enumerable.Range(1, 10).ToList();	0
13819213	13817300	Retrieve Xml attribute using XElement	var xml = @"<d:Answer xmlns:d=""http://www.test.com"" d:title=""abcd"">\n  <d:question id=""2.1"" answer=""test""  />\n  <d:question id=""2.2"" answer=""test""  />\n  <d:question id=""2.3"" answer=""Yes""  />\n</d:Answer>";\n\nXNamespace ns = "http://www.test.com";\nvar doc = XDocument.Parse(xml);\nvar question = doc.Descendants(ns + "question")\n                  .FirstOrDefault(x => (string)x.Attribute("id") == "2.1");	0
6672767	6670580	mapping multiple tables to a single entity class in entity framework	modelBuilder.Entity<TestResult>()\n    .Map(m =>\n      {\n        m.Properties(t => new { t.Name, t.Text, t.Units /*other props*/ });\n        m.ToTable("Result");\n      })\n    .Map(m =>\n      {\n        m.Properties(t => new { t.Status, t.Analysis /*other props*/});\n        m.ToTable("Test");\n      });	0
21602709	21602499	running a couple of SQL statement with 1 click	string sPath = @"D:\script.sql";\nif (File.Exists(sPath) == false)\n    return;\nstring sServer = "SQL SERVER INSTANCE NAME";\nstring sUserID = "sa";\nstring sPassword = "password"; \n\nProcess p = new Process();\np.StartInfo.UseShellExecute = false;                        \np.StartInfo.RedirectStandardOutput = true;\np.StartInfo.CreateNoWindow = true;\np.StartInfo.FileName = "sqlcmd";\np.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;\n\nif (sPassword == "")\n    p.StartInfo.Arguments = string.Format("-S {0} -i {1} ", sServer, sPath);\nelse\n    p.StartInfo.Arguments = string.Format("-S {0} -U {1} -P {2} -i " + Convert.ToChar(34) + "{3}" + Convert.ToChar(34), sServer, sUserID, sPassword, sPath);\n\nbool started = p.Start();\n\nstring output = p.StandardOutput.ReadToEnd();\n\np.WaitForExit();	0
31003779	31001739	Modify Build process parameter by TFS API in C#	string argumentName = "TestDirectory";\nvar process = Microsoft.TeamFoundation.Build.Workflow.WorkflowHelpers.DeserializeProcessParameters(BuildDefinition.ProcessParameters);\n\nif (process.ContainsKey(argumentName))                             \n{\n    process.Remove(argumentName);\n    process.Add(argumentName, attributeValue);\n    BuildDefinition.ProcessParameters = WorkflowHelpers.SerializeProcessParameters(process);\n    BuildDefinition.Save();\n}	0
22777265	22777112	How generate chart from Excel sheet using c# interop?	// Add chart.\nvar charts = worksheet.ChartObjects() as\n    Microsoft.Office.Interop.Excel.ChartObjects;\nvar chartObject = charts.Add(60, 10, 300, 300) as\n    Microsoft.Office.Interop.Excel.ChartObject;\nvar chart = chartObject.Chart;\n\n// Set chart range.\nvar range = worksheet.get_Range(topLeft, bottomRight);\nchart.SetSourceData(range);\n\n// Set chart properties.\nchart.ChartType = Microsoft.Office.Interop.Excel.XlChartType.xlLine;\nchart.ChartWizard(Source: range,\n    Title: graphTitle,\n    CategoryTitle: xAxis,\n    ValueTitle: yAxis);	0
13901295	13899883	I want to detect if the DataGridView cell leaves the event only in selecting mode	private void dataGridView2_CellValidating(object sender, DataGridViewCellValidatingEventArgs e)\n    {\n        if (dataGridView2.IsCurrentCellDirty)\n            if (e.ColumnIndex == 0)\n            {\n                if (string.IsNullOrWhiteSpace(dataGridView2[e.ColumnIndex, e.RowIndex].EditedFormattedValue.ToString()))\n                {\n                    e.Cancel = true;\n                    MessageBox.Show("Please enter some text before you leave.");\n                }\n                else if (dataGridView2[e.ColumnIndex, e.RowIndex].EditedFormattedValue.ToString() != "S")\n                {\n                    e.Cancel = true;\n                    MessageBox.Show("You have to enter S");\n                }\n            }\n    }\n}	0
23212718	23210538	newline for Arabic or urdu string	char rleChar = (char)0x202B;// RLE embedding \ntext = rleChar + text;	0
13524229	9110331	get i frame source using HtmlAgilityPack	HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();\n\nHtmlNodeCollection nodes = doc.DocumentNode.SelectNodes("//iframe[@src]");\n\n\nforeach(var node in nodes){\n    HtmlAttribute attr = node.Attributes["src"];\n    Console.WriteLine(attr.Value);\n}	0
5138342	5138323	How can i fix this kind of exception? ArgumentOutOfRangeException	date_tax.Day - index	0
4095470	4095315	Other ways of 'disabling' a textbox against user input	TextBox1.Attributes.Add("readonly", "readonly")	0
28980618	28979680	How to Send an attachment with email using MVC webapi	type: "POST",         // Type of request to be send, called as method\ndata: new FormData(this), // Data sent to server, a set of key/value pairs  \ncontentType: false,   // The content type used when sending data to the server.\ncache: false,         // To unable request pages to be cached\nprocessData:false, // To send DOMDocument or non processed data file it is set to false\nsuccess: function(data)   // A function to be called if request succeeds	0
16286653	16286581	Use nullable value if it HasValue	return number ?? 6;	0
32067441	32066761	How to allow null to be added to database	Cost = sectionGroup.Cost == null ? DBNull.Value : (double)sectionGroup.Cost	0
6836859	6836701	Remove current row from ObservableCollection	myCollection.Remove(Listbox1.Selecteditem)	0
32443083	32440235	Upload local image to deviantsart	var client = new RestClient("http://deviantsart.com");\nvar request = new RestRequest("upload.php", Method.POST);\nrequest.AddFile("pathtofileondisk.jpg");\n\nvar response = client.Execute(request);	0
10319799	10301838	Upload files to SQL from a csv	private void SaveFiles(List<string[]> files)\n     {\n        foreach (string[] attachment in files)\n        {\n            using (DataClasses1DataContext db = new DataClasses1DataContext())\n            {\n                string path = attachment[1].ToString();\n                byte[] fileBytes = File.ReadAllBytes(path);\n\n                ApplicantAttachment aa1 = new ApplicantAttachment();\n                aa1.Filename = attachment[0].ToString();\n                aa1.FileType = MIMEType.GetType(attachment[1].ToString());\n                aa1.Attachment = fileBytes;\n                db.ApplicantAttachments.InsertOnSubmit(aa1);\n                db.SubmitChanges();\n\n            }\n        }\n     }	0
11096830	11096546	How to change binary to string	string data = "0A0B0C0F1102"; // example data\nif (data.Length % 2 != 0) { data = "0" + data; } \n\nbyte[] result = new byte[data.Length / 2];\nfor (int i = 0; i < data.Length; i += 2) {\n    result[i/2] = Convert.ToByte(data.Substring(i, 2), 16);\n}\nBinary image = result;	0
28031064	28010788	how to set custom date format for specific column in datagridview? - c#	this.dataGridView1.Columns["YourDateCol"].DefaultCellStyle.Format = "dd/MM/yyyy";	0
2950614	2950321	Adding a Design time Panel to a TabPage at run time	panel2.Dock = DockStyle.Fill;	0
15100023	15099952	How to fill a string with ordered elements via LINQ?	var equations = elements.Distinct().OrderBy(e => e.Id).Select(e => e.Equation);\nvar asString = string.Join(", ", equations);	0
1528886	1528508	Uncompress data file with DeflateStream	public static long Decompress(Stream inp, Stream outp)\n    {\n    byte[]  buf = new byte[BUF_SIZE];\n    long    nBytes = 0;  \n\n    // Decompress the contents of the input file\n    using (inp = new DeflateStream(inp, CompressionMode.Decompress))\n    {\n    int len;\n    while ((len = inp.Read(buf, 0, buf.Length)) > 0)\n    {\n    // Write the data block to the decompressed output stream\n    outp.Write(buf, 0, len);\n    nBytes += len;\n    }  \n    }\n    // Done\n    return nBytes;\n    }	0
18825647	18825187	how to to request the Task to stop working?	CancellationTokenSource cts;\nprivate Task[] tasks;\n\nvoid Start()\n{\n    cts = new CancellationTokenSource();\n    tasks = new Task[1];\n    tasks [0] = Task.Run(() => SomeWork(cts.Token), cts.Token);\n}\n\nvoid SomeWork(CancellationToken cancellationToken)\n{\n    while (true)\n    {\n        // some work\n        cancellationToken.ThrowIfCancellationRequested();\n    }\n}\n\nvoid Cancel()\n{\n    cts.Cancel();\n    Task.WaitAll(tasks);\n}	0
5822312	5811241	using findcontrol for dropdownlist in a multiview	foreach (RepeaterItem item in edit_program.Items)\n{\n    var ddl = (DropDownList)item.FindControl("p_status");\n    ddl.Items.Add(new ListItem("Green", "Green"));\n}	0
7905224	7905100	Make a DataMember in a DataContract use implicit cast to string operator	[DataContract]\npublic class Root\n{\n    [DataMember]\n    public string MemberString { get{ return (string)this.Member; } set{this.Member=(Element)value;} }\n\n    public Element Member { get; set; }\n}	0
7438120	7437952	Map string column in Entity Framework to Enum	public virtual string StatusString\n{\n    get { return Status.ToString(); }\n    set { OrderStatus newValue; \n          if (Enum.TryParse(value, out newValue))\n          { Status = newValue; }\n        }\n}\n\npublic virtual OrderStatus Status { get; set; }	0
29354109	29354074	Multi-Dimensional Array - Array of arrays?	string[][]	0
23424849	23421267	How to get and set text editor value in selenium	IJavaScriptExecutor js = (IJavaScriptExecutor)driver;\n        js.ExecuteScript("document.getElementsByClassName('cke_wysiwyg_frame')[0].contentDocument.getElementsByClassName('cke_editable_themed')[0].innerHTML='dfjkbgdk';");	0
6328939	6327412	DynamicResource With Static Parameter in C#?	this.Width = System.Windows.SystemParameters.MaximizedPrimaryScreenWidth;\nthis.Height = System.Windows.SystemParameters.MaximizedPrimaryScreenHeight;	0
24894397	24892783	Custom data annotation attribute not being validated	TryValidateObject(object instance, ValidationContext validationContext, ICollection<ValidationResult> validationResults, bool validateAllProperties)	0
12979381	12978894	Change Windows 7 app taskbar icon color	// This will highlight the icon in red\nTaskbarManager.Instance.SetProgressState(TaskbarProgressBarState.Error);\n// to highlight the entire icon\nTaskbarManager.Instance.SetProgressValue(100,100);	0
10417100	10416808	Find catch statements re-thrown that don't have the inner exception set via RegEx	catch\((([^)]|\n|\r)*)\)\s*{(([^}]|\n|\r)*?)Exception\(([^,](?!\n))+?\);(([^}]|\n|\r)*)}	0
7675117	7674955	Found minimum and maximum value from dataset containing multiple tables	int minAccountLevel = int.MaxValue;\nint maxAccountLevel = int.MinValue;\n\nfor (int i = 0; i < 3; i++)\n{\nvar table = ds.Tables[i];\nforeach (DataRow dr in table.Rows)\n{\n    int accountLevel = dr.Field<int>("AccountLevel");\n    minAccountLevel = Math.Min(minAccountLevel, accountLevel);\n    maxAccountLevel = Math.Max(maxAccountLevel, accountLevel);\n}\n}	0
5128437	5128421	How to stop the execution and make a redirect to the login page	FormsAuthentication.SignOut();\nResponse.Redirect("URLToLoginPage");	0
28180679	28143062	get raw xml response from amazon mws api	runtime-src	0
20858332	20848815	WP8/XAML - Measure string length in pixels	public int TextWidth(string text)\n    {\n        TextBlock t = new TextBlock();\n        t.Text = text;\n        //Height and Width are depending on font settings\n        //t.FontFaimily=...\n        //t.FontSize=...\n        //etc.\n        return (int)Math.Ceiling(t.ActualWidth);\n    }	0
24223363	24223344	C# Dictionary add entry with wrong order	List<Route> routes;\nRoute route = routes[key];	0
226775	226572	XPath in C# code behind of WPF	XPathDocument doc = new XPathDocument(@"c:\filepath\doc.xml");\nXPathNavigator nav = doc.CreateNavigator();\nXPathNodeIterator iter = nav.Select("/xpath/query/here");\n\nwhile(iter->MoveNext)\n{\n  //Do something with node here.\n}	0
9916576	9915160	How to display text in a WPF GridView that contains carriage returns	public string TextBlockText { get { return "one line \r\ntwo line"; } }\n\n <TextBlock Height="Auto" Width="100" HorizontalAlignment="Left" Text="{Binding Path=TextBlockText}" />	0
7460174	7460129	ASP.NET SqlDataSource parameter declaration in code behind	sqlDataSource.SelectParameters.Add(new Parameter("One", System.TypeCode.Int32, recordNo))	0
9208364	9208158	Application design, global image collection	public static class Foo\n{\n    public static int Bar()\n    {\n        return 1;\n    }\n\n    public static void AddImage(Image img, String key){...}\n    public static Image GetImage(String key){...}\n}	0
11966823	11966128	Linq outer join syntax	var query = \n  from moduleStrings in _Context.ModuleStrings  \n  join strings in _Context.Strings on moduleStrings.SID equals strings.SID \n  join stringTexts1 in _Context.StringTexts.Where(x=>x.LID==LID) on strings.SID equals stringTexts.SID into stringsEmpty \n  from stringTexts in stringsEmpty.DefaultIfEmpty() \n  where moduleStrings.MID == MID \n  select new GridData6S()  \n  {  \n      Name = strings.Name, \n      Text = stringTexts != null ? stringTexts.Text : "" \n  };	0
26095572	26065260	Validation of Docbook 5.0 XML via XSD with C# .Net	private Boolean m_success = true;\nprivate void ValidationCallBack(object sender, ValidationEventArgs args)\n{\n    m_success = false;\n    Console.WriteLine("\r\n\tValidation error: " + args.Message);\n}\n\n\n\npublic void validate(string xmlfile, string ns, string xsdfile)\n{\n\n    m_success = true;\n    XmlReaderSettings settings = new XmlReaderSettings();\n    XmlSchemaSet sc = new XmlSchemaSet();\n    sc.Add(ns, xsdfile);\n    settings.ValidationType = ValidationType.Schema;\n    settings.Schemas = sc;\n    settings.ValidationEventHandler += new ValidationEventHandler(ValidationCallBack);\n\n    XmlReader reader = XmlReader.Create(xmlfile, settings);\n    // Parse the file. \n    while (reader.Read()) ;\n    Console.WriteLine("Validation finished. Validation {0}", (m_success == true ? "successful!" : "failed."));\n    reader.Close();\n}	0
15219150	15205237	VSTO Outlook: Get selected attachment	public void DoSomething(Office.IRibbonControl control)\n{\n    var window = plugin.Application.ActiveWindow();\n    var attachsel = window.AttachmentSelection();\n\n    int? index = null;\n    if (attachsel.count > 0)\n    {\n        var attachment = attachsel[1];\n        index = attachment.Index;\n    }\n\n    var explorer = plugin.Application.ActiveExplorer();\n    var selection = explorer.Selection;\n\n    if ((selection.Count > 0) && (index != null))   \n    {\n        object selectedItem = selection[1];\n        var mailItem = selectedItem as Outlook.MailItem;\n        foreach (Outlook.Attachment attach in mailItem.Attachments)\n        {\n            if (attach.Index == index)\n            {\n                attach.SaveAsFile(Path.Combine(@"c:\temp\", attach.FileName));\n            }\n        }\n\n    }\n}	0
7981396	7981301	Generate white noise image in C#	foreach(var pixel in image)\n{\n    pixel = rand()>0.5 ? white : black;\n}	0
8439773	8439757	how to run batch queries in sql ce?	SqlCeCommand oCommand = conn.CreateCommand();\noCommand.CommandText = "insert into contacts(name, emails) values(?, ?)";\n// I can't remember if the param names need @ or not\noCommand.Parameters.Add("@name", SqlDbType.VarChar);\noCommand.Parameters.Add("@email", SqlDbType.VarChar);\n\nSqlCeTransaction oTrans = conn.BeginTransaction();\ntry {\n  foreach (KeyValuePair<string, string> key in list) {\n     oCommand.Parameters[0].Value = key.Key;\n     oCommand.Parameters[1].Value = key.Value;\n     oCommand.ExecuteNonQuery();\n  }\n  oTrans.Commit();\n} catch (Exception ex) {\n  oTrans.Rollback();\n}	0
9017567	9017498	Calculating how many minutes there are between two times	DateTime startTime = varValue\n\nDateTime endTime = varTime\n\nTimeSpan span = endTime.Subtract ( startTime );\nConsole.WriteLine( "Time Difference (seconds): " + span.Seconds );\nConsole.WriteLine( "Time Difference (minutes): " + span.Minutes );\nConsole.WriteLine( "Time Difference (hours): " + span.Hours );\nConsole.WriteLine( "Time Difference (days): " + span.Days );	0
5157520	5157408	One-To-Many mapping fluent NHibernate	HasMany(x => x.UserCourses).KeyColumn("UserId")	0
25870817	25869699	Pass parameter into action	IterateProperties(element, ele => ResetSomeProperty(ele, externalDictionary));	0
3208634	3208573	How to specify pattern that should not match	var input = "Hello";\nvar regEx = new Regex("World");\nreturn !regEx.IsMatch(input);	0
4725434	4725391	C# WPF Convert a byte array into video file?	File.WriteAllBytes	0
24150915	24150675	Search substring in text file	int theNumber;\nstring[] lines = System.IO.File.ReadAllLines("c:\\the file.txt");\nfor( int i = 0; i < lines.Length; i++ )\n{\n    if( lines[i].Contains( "Total no. of objects processed successfully" ) )\n    {\n        theNumber = Convert.ToInt32( lines[i].Substring( lines[i].LastIndexOf('-') + 2 ) );\n    }\n}	0
7014763	7014393	Manipulate XML XDocument XmlDocument C#	var doc = XDocument.Load(...);\nXNamespace envNs = "http://schemas.xmlsoap.org/soap/envelope/";\nvar fromUri = doc.Root\n       .Element(envNs + "Header")\n       .Element("Authorization")\n       .Element("FromURI");\nfromUri.Value = "http://trst";\ndoc.Save(...);	0
25955118	25942733	Abort reading from serial to start writing?	int datalen = serialPort1.BytesToRead;\nlabel1.Text="Readexisting";\nif (datalen >=10)\n{\n    string data = serialPort1.ReadExisting();\n    label1.Text=data;\n}	0
23715473	23715423	c# compare two numbers got from two files	void CompareVersions()\n{\n    WebClient client = new WebClient();\n    var serverVersion = client.DownloadString("http://yourwebsite.com/version.txt");\n\n    using (StreamReader sr = new StreamReader("file.txt"))\n    {\n        if (Convert.ToInt32(serverVersion) > Convert.ToInt32(sr.ReadLine()))\n        {\n            // server version bigger\n        }\n        else\n        {\n            // up to date\n        }\n    }\n}	0
31605385	31605293	Designing interface for tree-like structure	public interface ITreeNode<T> where T : ITreeNode<T>\n{\n    T ParentNode { get; set; }\n    ICollection<T> ChildNodes { get; set; }\n}\n\npublic class FooNode : ITreeNode<FooNode>\n{\n    public FooNode ParentNode { get; set; }\n    public ICollection<FooNode> ChildNodes { get; set; }\n}	0
22632085	22631851	Simple regex matching issue, what's my mistake?	String matched = filesProgressMatch.Groups[0].Value.Replace(" files checked", "");	0
20375746	20375582	How can I add a attribute to Root node of my XmlDocument() in C#	document.DocumentElement.Attributes.Append(document.CreateAttribute("uuid")).Value = "12345"	0
24532998	24532595	Binding datagrid comboboxcolumn WPF	DataTable material= ds.Tables["Material"];\nDataTable units= ds.Tables["Units"];\n\nvar query =\n    from m in material.AsEnumerable()\n    join u in units.AsEnumerable()\n    on m.Field<int>("Column1") equals\n        u.Field<int>("Column1")\nselect new\n    {\n        Text =\n            u.Field<string>("EnglishName"),\n        Value =\n            m.Field<int>("MaterialID")\n    };\n\ncmb.ItemsSource = query.ToList();\n\ncmb.DisplayMemberPath = "Text";\ncmb.SelectedValuePath = "Value"	0
10893262	10893220	Anonymous type with counter for each result	var counter = 0;\nvar results =\n    from foo in bar\n    select new { foo.ID, foo.Name, Counter = ++counter };	0
30080759	30080678	How to find a right click event on MouseUp anywhere on the form?	this.MouseUp += new MouseEventHandler(this.form_MouseUpToGetHelpText);\n\n\nprivate void form_MouseUpToGetHelpText(object sender, MouseEventArgs e)\n{\n  if (e.Button == System.Windows.Forms.MouseButtons.Right)\n  {\n      // Logic here\n  }\n}	0
14192681	14154113	Working with legacy databases and SchemaAction in Fluent NHibernate	using (var file = new StreamWriter("SchemaUpdateScript.txt"))\n{\n    new SchemaUpdate(config).Execute(file.WriteLine, false);\n}	0
30791519	30791255	How to give a child window bounds to not go outside the MainWindow in WPF	public MainWindow()\n  {\n   InitializeComponent();     \n   LocationChanged += new EventHandler(Window_LocationChanged);\n  }\n\n\nChildWindow win = new ChildWindow();\n   win.Owner = this;\n   win.Show();\n\nprivate void Window_LocationChanged(object sender, EventArgs e)\n  {\n   Console.WriteLine("LocationChanged - ({0},{1})", this.Top, this.Left);\n   foreach (Window win in this.OwnedWindows)\n   {\n    win.Top = this.Top + 100;\n    win.Left = this.Left + 100;\n   }\n  }	0
13958908	13958249	Using public proxy server in HTTP client	using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing System.Net;\nusing System.IO;\n\nnamespace ConsoleApplication1\n{\n    class Program\n    {\n        static void Main(string[] args)\n        {\n            string url = "http://stackoverflow.com";\n            HttpWebRequest HttpWRequest = (HttpWebRequest)WebRequest.Create(url);\n            HttpWRequest.Method = "GET";\n\n            WebProxy myProxy = new WebProxy();\n\n            //United States proxy, from http://www.hidemyass.com/proxy-list/\n            myProxy.Address = new Uri("http://72.64.146.136:8080");\n            HttpWRequest.Proxy = myProxy;\n\n            HttpWebResponse HttpWResponse = (HttpWebResponse)HttpWRequest.GetResponse();\n            StreamReader sr = new StreamReader(HttpWResponse.GetResponseStream(), true);\n            var rawHTML = sr.ReadToEnd();\n            sr.Close();\n\n            Console.Out.WriteLine(rawHTML);\n            Console.ReadKey();\n        }\n    }\n}	0
23062152	23061788	Problems with Session for Sorting my GridView	protected void Page_Load(object sender, EventArgs e)\n    {\n        if (Session["a"]==null)\n        {\n            Response.Write("Session is empty");\n        }\n        else\n        {\n            Response.Write("Session is not empty");\n            Response.Write(Session["a"].ToString());\n        }\n        if (!Page.IsPostBack)\n        {\n            Session["a"] = "Jalpesh";\n        }\n    }	0
21207964	21206321	ISampleGrabberCB declaration & implementation in C#	[ComImport, System.Security.SuppressUnmanagedCodeSecurity,\nGuid("0579154A-2B53-4994-B0D0-E773148EFF85"),\nInterfaceType(ComInterfaceType.InterfaceIsIUnknown)]\npublic interface ISampleGrabberCB\n{\n    /// <summary>\n    /// When called, callee must release pSample\n    /// </summary>\n    [PreserveSig]\n    int SampleCB(double SampleTime, IMediaSample pSample);\n\n    [PreserveSig]\n    int BufferCB(double SampleTime, IntPtr pBuffer, int BufferLen);\n}	0
10034778	10034715	Using a method with generic parameters as a callback	public class SomeClass<TParam, TReturn>\n{\n    private Func<TParam, TReturn> _callback;\n\n    public class SomeClass(Func<TParam, TReturn> callback)\n    {\n        _callback = callback;\n    }\n}	0
11042833	11042688	WPF Binding a List to a DataGrid	public List<ComputerRecord> GridInventory\n{\n    get { return _gridInventory; }\n    set \n    { _gridInventory = value; \n      RaisePropertyChanged("GridInventory");\n    }\n}	0
20326887	20324977	how to get the distinct item from listview in windows application	// take only the last character which is a letter (A, B, ...)\nvar letterList = list.Select(i => i.Last());\n// group the letters and select those which are present more than once\nvar dups = letterList.GroupBy(i => i)\n                     .Where(i => i.Count() > 1)\n                     .Select(i => i.Key);\n// take the resulting letter and join them with the ',' character\nvar result = string.Join(",", dups); // or textBox.Text = ...	0
14878913	14878871	Design: List storing objects; access information associated with that object	theList.Where(x => x.address == "999 Candy Lane").First();	0
18209060	18208846	Microsoft Speech in windows service	Private Sub CreateSpeechRecoginationEngine(culture As String)\n    Dim _culture As CultureInfo\n    For Each recognizer In SpeechRecognitionEngine.InstalledRecognizers\n        If recognizer.Culture.Name.Equals(culture) Then\n            _culture = recognizer.Culture\n            Exit For\n        End If\n    Next\n    If _culture Is Nothing Then _culture = SpeechRecognitionEngine.InstalledRecognizers()(0).Culture\n    SpeechRecognitionEngine speechRecoginationEngine = New SpeechRecognitionEngine(_culture)\nEnd Sub	0
4152181	4151772	Passing string as PChar from CSharp to Delphi DLL	DllImport(\n            "DLLTest.dll", \n            CallingConvention = CallingConvention.StdCall,\n            CharSet = CharSet.Ansi,\n            EntryPoint = "DLL_Message"\n        )]\n        public static extern void DLL_Message(\n            [MarshalAs(UnmanagedType.LPStr)] string Location,\n            int AIntValue\n        );	0
18135111	18112762	Setting up dynamic connection string for log4net	//connectionString is the Web.config's connectionString, which I wanted to share.\n public static void SetUpDbConnection(string connectionString, string logConfig)\n    {\n        //update connection string for log4net dynamically\n        var hier = LogManager.GetRepository() as Hierarchy;\n        log4net.Config.XmlConfigurator.ConfigureAndWatch(new FileInfo(logConfig));\n        if (hier != null)\n        {\n            var adoNetAppenders = hier.GetAppenders().OfType<AdoNetAppender>();\n            foreach (var adoNetAppender in adoNetAppenders)\n            {\n                adoNetAppender.ConnectionString = connectionString;\n                adoNetAppender.ActivateOptions();\n            }\n        }\n    }	0
17963159	17963117	How to fill a region with transparency in windows forms application	Color.FromArgb(0...255, r, g, b)	0
30608570	30608504	Display variable in textbox	if (Page.IsPostBack == false)\n        {\n\n}	0
18032247	18030415	Split a Datatable into multiple Datatables based on a list of column names	var dt = new DataTable();\nvar res = new List<DataTable>();\n\ndt.Columns.Add("ID", typeof(int));\ndt.Columns.Add("Country", typeof(string));\ndt.Columns.Add("Supplier", typeof(string));\ndt.Rows.Add(515, "DE", "A");\ndt.Rows.Add(515, "CH", "A");  \ndt.Rows.Add(515, "FR", "A");\ndt.Rows.Add(516, "DE", "B");\ndt.Rows.Add(516, "FR", "B");\ndt.Rows.Add(517, "DE", "C");\ndt.Rows.Add(517, "IT", "C");\n\nvar fields = new List<string>() { "Supplier", "Country"};\nvar qfields = string.Join(", ", fields.Select(x => "it[\"" + x + "\"] as " + x));\n// qfields = "it[\"Supplier\"] as Supplier, it[\"Country\"] as Country"\n\nvar q = dt\n    .AsEnumerable()\n    .AsQueryable()\n    .GroupBy("new(" + qfields + ")", "it")\n    .Select("new (it as Data)");\nforeach (dynamic d in q)\n{\n    var dtemp = dt.Clone();\n\n    foreach (var row in d.Data)\n        dtemp.Rows.Add(row.ItemArray);\n\n    res.Add(dtemp);\n}	0
18657124	18654307	windows store app page blank when navigating to it	Style="{StaticResource    ListViewStyle1}"	0
14567081	14566376	How save photo capture windows 8 c# metro app?	FileSavePicker savePicker = new FileSavePicker();\n  savePicker.SuggestedStartLocation = PickerLocationId.PicturesLibrary;\n  savePicker.FileTypeChoices.Add("jpeg image", new List<string>() { ".jpeg" });\n  savePicker.SuggestedFileName = "New picture";\n\n  StorageFile ff = await savePicker.PickSaveFileAsync();\n  if (ff != null)\n  {\n    await photo.MoveAndReplaceAsync(ff);\n  }	0
34323855	34309625	Leading 0's missing from the data of csv file while using it in coded ui test	Name,Number,Telephone\nAlice,"001",01 234 567890\nBrian,"002",01 234 678901	0
25117000	25116943	Printing the Given numbers in given columns and rows Console Application	string total, rows, columns = "";\n\ntotal = "30";\nvar allNumbers = "1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30";\nvar array = allNumbers.Split(',');\n\nrows = "5";\n\ncolumns = "6";\n\nfor (int i = 0; i < Convert.ToInt32(rows); i++)\n{\n    for (int j = 0; j < Convert.ToInt32(columns); j++)\n    {\n        Console.Write(array[j + (i * Convert.ToInt32(columns))]);\n        Console.Write("\t");\n    }\n\n    Console.WriteLine();\n}	0
3580513	3580498	What's wrong with this string formatting?	StringBuilder sbRemove = new StringBuilder();\nsbRemove.Append(@"<object height=\\\"38\" + \"5\\\" width=\\\"64\" + \"0\\\" classid=\\\"clsid:D27CDB6E-\nAE6D-11cf-96B8-444553540000\\\" id=\\\"movie_player\\\" ><param name=\\\"movie\\\" \nvalue=\\\"http:\\/\\/s.ytimg.com\\/yt\\/swf\\/watch_as3-vfl186120.swf\\\"><param \nname=\\\"flashvars\\\" value=\\\"...." allowscriptaccess=\\\"always\\\" \nallowfullscreen=\\\"true\\\" bgcolor=\\\"#000000\\\" \\/>");\nsbRemove.Replace(@"\\\", "");\nsbRemove.Replace(@"\"", "");	0
23238634	23238562	How to allow average to be null	public double? GetSignalAverage\n{\n    get\n    {\n       if(Gsmdata == null || GsmData.Count() == 0)\n           return null;\n\n       var signalaverage = Gsmdata.Select(x => x.SignalStrength)\n                                  .Average();\n       return Math.Round(signalaverage, 2);\n    }\n}	0
25405255	25402496	API or Library to process vCalendar information?	DateTime localTime = DateTime.SpecifyKind(DateTime.Parse(strDate),  \n                                          DateTimeKind.UTC).ToLocalTime();	0
12054258	12049425	Add caption to access fields with c#	using Microsoft.Office.Interop.Access.Dao;\n\n\n        DBEngine dbEng = new DBEngine();\n        Workspace ws = dbEng.CreateWorkspace("", "admin", "",\n            WorkspaceTypeEnum.dbUseJet);\n        Database db = ws.OpenDatabase(@"z:\docs\test.accdb", false, false, "");\n        TableDef tdf = db.TableDefs["Table1"];\n        Field fld = tdf.Fields["Field1"];\n\n        Property prp = fld.CreateProperty("Caption", 10, "My caption");\n\n        fld.Properties.Append(prp);	0
35930	35914	Launch a file with command line arguments without knowing location of exe?	Process.Start	0
1786778	1786695	linq return single row from a goup	var query = yourData\n            .GroupBy(x => new { x.Vol, x.Component, x.Dwg, x.View })\n            .Select(g => g.OrderByDescending(x => x.Revision).First());\n\n// and to test...\nforeach (var x in query)\n{\n    Console.WriteLine("{0}\t{1}\t{2}\t{3}\t{4}",\n        x.Vol, x.Component, x.Dwg, x.View, x.Revision ?? "NULL");\n}\n\n// Volume U01    Composed Drawings    SJTest     1    B\n// Volume U03    Composed Drawings    SJTest2    2    NULL	0
5928173	5925069	Save Icon File To Hard Drive	string s = Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + @"\IconData.ico";\n        using (FileStream fs = new FileStream(s, FileMode.Create))\n            ico.Save(fs);	0
2426810	2426759	is there a way to capture database messages that a script generates while using SqlCommand?	SqlConnection.InfoMessage	0
16774305	16774261	C# - Read a nvarchar (dd/MM/yyyy) into a dateTimePicker	dateTimePicker.Value = DateTime.Parse(reader["Date"].ToString());	0
10705134	10704284	How Do I Change the Size Of A PrintDialog Form	foreach (string s in PrinterSettings.InstalledPrinters)\n{\n    comboBox1.Items.Add(s);\n}	0
3263482	3263407	subscribe to IE process	System.Diagnostics.Process.GetProcesses();	0
31415238	31414117	"Red X of Doom" while plotting multiple time series chart in WinForm	IsXValueIndexed = false,	0
15061773	15038867	facebook c# api, video getting uploaded but its PUBLIC	upload1.Add("privacy", "{\"value\":\"SELF\"}");	0
5889330	5889197	MongoDB/C# get all values of a certain key in all documents	var collection = _db.GetCollection("employees");\nreturn (from p in collection.AsQueryable()\n         select p["FullName"]).toList();	0
13771298	13769081	Asynchronous insert in Azure Table	context.BeginSaveChangesWithRetries(SaveChangesOptions.Batch,\n    (asyncResult => context.EndSaveChangesWithRetries(asyncResult)),\n    null);	0
10626960	10626905	Linq to group by firstname lastname and select from a sub array	var result = from c in contacts\n                 group c by new { c.firstname, c.lastname } into g\n                 select g.ToList();\n\n    var result1 = from c in companyList.SelectMany(company => company.Contacts)\n                  group c by new { c.firstname, c.lastname } into g\n                  select g.ToList();	0
3334289	3334229	How do i get the top 5 items in a database based on the occurence of a particluar field?	IEnumerable<int> top3ProductIds = (from btp in entities.BasketToProduct\n                                   group btp by btp.ProductId into g\n                                   orderby g.Count() descending\n                                   select g.Key).Take(3);	0
1846248	1845864	Get the method parameters from the throwing method in C#	Debugger.Break()	0
33599994	33599760	C# Get all words from text file starting with X	using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing System.IO;\nusing System.Text.RegularExpressions;\n\nnamespace ConsoleApplication1\n{\n    class Program\n    {\n        const string FILENAME = @"c:\temp\test.txt";\n        static void Main(string[] args)\n        {\n            string input = File.ReadAllText(FILENAME);\n            string pattern = @"\('(?'steam'[^']*)";\n            MatchCollection matches = Regex.Matches(input, pattern, RegexOptions.Singleline);\n            foreach (Match match in matches)\n            {\n                Console.WriteLine(match.Groups["steam"]);\n            }\n            Console.ReadLine();\n        }\n    }\n}\n???	0
11732317	11504721	C# Window Form Application: Is there a way to convert pdf into bitmap without using any third party library?	static void Main(string[] args)\n    {\n        // Create an instance of Bytescout.PDFRenderer.RasterRenderer object and register it.\n        RasterRenderer renderer = new RasterRenderer();\n        renderer.RegistrationName = "demo";\n        renderer.RegistrationKey = "demo";\n\n        // Load PDF document.\n        renderer.LoadDocumentFromFile("multipage.pdf");\n\n        for (int i = 0; i < renderer.GetPageCount(); i++)\n        {\n            // Render first page of the document to BMP image file.\n            renderer.RenderPageToFile(i, RasterOutputFormat.BMP, "image" + i + ".bmp");\n        }\n\n        // Open the first output file in default image viewer.\n        System.Diagnostics.Process.Start("image0.bmp");\n    }	0
692517	594174	ListView Cursor changing & flickering	public const uint LVM_SETHOTCURSOR = 4158;\n\n[DllImport("user32.dll")]\npublic static extern IntPtr SendMessage(IntPtr hWnd, uint Msg, IntPtr wParam, IntPtr lParam);\n\nSendMessage(listView1.Handle, LVM_SETHOTCURSOR, IntPtr.Zero, Cursors.Arrow.Handle);	0
32902016	32868206	AsyncFileUpload Dynamically add in custom control	system.web.Extension	0
22132965	22132901	How to convert an array of string to a sentence?	var temp = words.Aggregate((x, y) => x + " " + y);	0
30320979	30318206	Bulk update column in Data Table based on another column	dt.Columns.Add("MyDate", GetType(Date)).Expression = "SUBSTRING(strDateField,5,2)+'/'+SUBSTRING(strDateField,7,2)+'/'+SUBSTRING(strDateField,1,4)";	0
3936195	3936112	Save Webcam Image From Website	Referer: http://bigwatersedge.axiscam.net/view/snapshot.shtml?picturepath=/jpg/image.jpg	0
10183500	10183441	Counting how many objects are being used from a class	public class C\n{\n  private static int numInstances;\n  public C() {\n    ++numInstances;\n    // and whatever else is needed\n  }\n}	0
16314032	16313062	How to read a special character from rtf file using C#?	\rdblquote  0xD3	0
12200405	12199600	How do I get the last part of this filepath?	class Program\n{\n    static void Main(string[] args)\n    {\n        Console.WriteLine(ExtractPath(@"C:\Temp\X\2012\08\27\18\35\wy32dm1q.qyt"));\n        Console.WriteLine(ExtractPath(@"D:\Temp\X\Y\2012\08\27\18\36\tx84uwvr.puq"));\n    }\n\n    static string ExtractPath(string fullPath)\n    {\n        string regexconvention = String.Format(@"\d{{4}}\u{0:X4}(\d{{2}}\u{0:X4}){{4}}\w{{8}}.\w{{3}}", Convert.ToInt32(Path.DirectorySeparatorChar, CultureInfo.InvariantCulture));\n\n        return Regex.Match(fullPath, regexconvention).Value;\n    }\n}	0
33514348	33514076	How to maintain dropdownlist selected value after postback?	public ActionResult TaxMaster(string txtSearchValue, string ddlSearchBy)\n{\n    TaxMaster objTaxTable = new TaxMaster();\n    objTaxTable.TaxTable = new List<moreInsights_offinvoice_taxmaster>();\n    objTaxTable.TaxTable = GetTaxMasterTable(ddlSearchBy, txtSearchValue);\n    ViewBag.SelectedOption=ddlSearchBy;\n    return View(objTaxTable);\n}\n\nstring selectedOption = ViewBag.SelectedOption;\n\n<select id="ddlSearchBy" name="ddlSearchBy" style="width: 150px">\n <option value="TaxCode" selected="@(selectedOption == "TaxCode" ? "selected" : "")">Tax Code</option>\n <option value="TaxDescription" selected="@(selectedOption == "TaxDescription" ? "selected" : "")">Tax Description</option>\n <option value="ClassDescription" selected="@(selectedOption == "ClassDescription" ? "selected" : "")">Class Description</option>\n <option value="ZoneName" selected="@(selectedOption == "ZoneName" ? "selected" : "")">Zone Name</option>\n</select>	0
5622233	5622166	How can I retrieve a List of entities from a many to many relationship?	return db.GradeParaleloes.Single(g => g.GradeParaleloId == gradeParaleloId)\n                         .GradeStudents.Select(s => s.Student).ToList();	0
10602280	10602064	How do I open Microsoft Word and display a specific .doc containing a mail-merge by using Visual C# Express?	var type = Type.GetTypeFromProgID("Word.Application");\ndynamic word = Activator.CreateInstance(type);\nword.Visible = true;\nword.Documents.Open(@"C:\test.docx");	0
18864333	18864209	How can I compare two different fields in two collections?	bool RfcEqualsAfd=rfc.All(q=>\n                         afd.Any(a=>\n                                q.Response==a.Correct && \n                                q.AnswerId==a.AnswerId\n                                )\n                         );	0
22895164	22895074	How clear two RichTextBox using CheckedListBox and button	private void button1_Click(object sender, EventArgs e)\n        {\n\n            for (int i = 0; i < checkedListBox1.Items.Count; i++)\n            {\n                if (checkedListBox1.GetItemChecked(i))\n                {\n                    string str = (string)checkedListBox1.Items[i];\n                    if(str ==  "rtb1")\n                    {\n                      richTextBox1.Clear();\n                      richTextBox1.Focus();\n                    }\n                     if(str ==  "rtb2")\n                    {\n                       richTextBox2.Clear();\n                       richTextBox2.Focus();\n                    }\n                }\n            }	0
20314510	20314499	How to remove all spaces before and after a string in C#	string str = "     hello world        ";\nstr=str.Trim();	0
8586869	4902461	ConfigurationElementCollection with a number of ConfigurationElements of different type	Microsoft.Practices.EnterpriseLibrary.Common.Configuration.PolymorphicConfigurationElementCollection<T>	0
31916355	31916153	C# Display compare timestamp to current month	public static DateTime ParseUnixDateTime(double unixTime)\n    {\n        var dt= new DateTime(1970, 1, 1, 0, 0, 0, 0, System.DateTimeKind.Utc);\n        dt= dt.AddSeconds(unixTimeStamp).ToLocalTime();\n        return dt;\n    }	0
11911380	11911359	dividing a string array in groups	var res = longWord\n    .Split(' ').\n    .Select((s, i) => new { Str = s, Index = i })\n    .GroupBy(p => p.Index / 10)\n    .Select(g => string.Join(" ", g.Select(v => v.Str)));	0
1909803	1699483	Excel reading in ASP.NET : Data not being read if column has different data formats	[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Jet\4.0\Engines\Excel]\n"ImportMixedTypes"="Text"\n"TypeGuessRows"=dword:00000000	0
3047629	3047448	Accessing "current class" from WPF custom MarkupExtension	public override object ProvideValue(IServiceProvider serviceProvider)\n{\n    var rootObjectProvider = serviceProvider.GetService(typeof(IRootObjectProvider)) as IRootObjectProvider;\n    var root = rootObjectProvider.RootObject;\n    // do whatever you need to do here\n}	0
7752798	7728689	removing namespace from xml	XmlDocument query_xml = new XmlDocument();\n        query_xml.Load("Query_1.xml");\n        XmlNodeList elements = query_xml.GetElementsByTagName("Attribute");\n        string[] s = new string[elements.Count];\n\n\n        for (int i = 0; i < elements.Count; i++)\n        {\n            string attrVal = elements[i].Attributes["Value1"].Value;\n        Console.Writeline(attrval)	0
14289387	14289313	How can I programmatically extract the app name and version number?	var xmlReaderSettings = new XmlReaderSettings\n{\n    XmlResolver = new XmlXapResolver()\n};\n\nusing (var xmlReader = XmlReader.Create("WMAppManifest.xml", xmlReaderSettings))\n{\n    xmlReader.ReadToDescendant("App");\n\n    var AppName = xmlReader.GetAttribute("Title");\n    var AppVersion = xmlReader.GetAttribute("Version");\n}	0
25015979	25015791	how to get the current gps coordinates in xamarin	CLLocationManager lm = new CLLocationManager(); //changed the class name\n... (Acurray)\n... (Other Specs)\n\nlm.LocationsUpdated += delegate(object sender, CLLocationsUpdatedEventArgs e) {\n    foreach(CLLocation l in e.Locations) {\n        Console.WriteLine(l.Coordinate.Latitude.ToString() + ", " +l.Coordinate.Longitude.ToString());\n    }\n};\n\nlm.StartUpdatingLocation();	0
4611784	4611761	Custom Linq Extension to replace For loop	public static void For<T>(this IEnumerable<T> items, Action<T, int> predicate)\n{\n    int i=0;\n    foreach (T item in items)\n    {\n        predicate(item, i++);\n    }\n}	0
29721686	29719484	Restructuring my application	public class UserDao : IUserDao\n{\n     public User GetUserById(int id)\n     {\n        ...\n     }\n}	0
11325234	11325028	Extract strings from file and save in another using c#	private void extract_lines(string filein, string fileout)\n    {\n        using (StreamReader reader = new StreamReader(filein))\n        {\n            using (StreamWriter writer = new StreamWriter(fileout))\n            {\n                string line;\n                while ((line = reader.ReadLine()) != null)\n                {\n                    if (line.Contains("what you looking for"))\n                    {\n                        writer.Write(line);\n                    }\n                }\n            }\n        }\n    }	0
14105047	14104824	Rebase a decimal field of an IEnumerable against two other fields in a better & fast way	var preModel = data.GroupBy(x => x.Scheme_Name)\n                   .Select(x => new {\n                                      Scheme_Name = x.Key, \n                                      Max = x.Max(m => m.ReInvest_Nav), \n                                      Data = x\n                                    })\n                   .SelectMany(x => x.Data.Select(y => new {\n                                       y.Scheme_Name, \n                                       y.Date, \n                                       y.ReInvest_Nav, \n                                       Rebased = y.ReInvest_Nav / x.Max * 100\n                                     }))\n                   .OrderBy(x => x.Scheme_Name)\n                   .ThenBy(x => x.Date)\n                   .ToList();	0
3275713	3274197	is there a way to do a reverse lookup in nhibernate?	HasManyToMany(x => x.Dependencies).Table("ComponentDependencies")\n    .ParentKeyColumn("ComponentId").ChildKeyColumn("ComponentDependencyId");\n\nHasManyToMany(x => x.DependentOf).Table("ComponentDependencies")\n    .ParentKeyColumn("ComponentDependencyId").ChildKeyColumn("ComponentId");	0
30606697	30606620	Store Text to String[] Arrays?	string[] lines = System.IO.File.ReadAllLines(@"F:\Designe- Video\projects\Phpgonehelp\Phpgonehelp\PHPCODE\Php1.txt");	0
3232755	3232744	Easiest way to compare arrays in C#	IEnumerable<T>	0
1715666	1715653	extract info from a string	string xml = "<foo>" + foo + "</foo>";	0
6166141	6148639	How to open Outlook new mail window c#	Outlook.Application oApp    = new Outlook.Application ();\nOutlook._MailItem oMailItem = (Outlook._MailItem)oApp.CreateItem ( Outlook.OlItemType.olMailItem );\noMailItem.To    = address;\n// body, bcc etc...\noMailItem.Display ( true );	0
32841889	32825674	NHibernate ICriteria Restriction find properties in a collection that match a value	criteria.CreateAlias("WidgetList", "widgets", JoinType.LeftOuterJoin);\ncriteria = criteria.Add(Restrictions.Eq("widgets.Bar", myValue));	0
3406968	3405128	Linq Where Clause - Accessing a tables column name	public static List<tblInfo> GetProductInfo(string memberid, string locationid, string column, string acitem)\n        {\n\n           MyEntities getproductinfo = new MyEntities ();\n\n            var r = (from p in getproductinfo.tblProductInfo \n                     where p.MemberId == memberid &&\n                              p.LocationId == locationid\n                     select p);\n\n            if (column == "Product")\n                r = r.Where(p => p.Product == acitem);\n\n            if (column == "Category1")\n                r = r.Where(p => p.Category1 == acitem);\n\nreturn r.OrderBy(p => p.Product).ThenBy(p => p.Category1).ToList();	0
4248962	4248930	how can i get one value to another on user click?	textbox2.Text = textbox.Text;	0
32892625	32892008	Convert this SQL Query to a Linq Lambda Expression	var result=db.Monitors\n  .Select(m=> new {\n    monitor=m,\n    queue=m.Queues.OrderByDescending(q=>q.Created).FirstOrDefault()\n  })\n  .Where(m=>m.queue.Created==null || m.queue.Created < DateTimeValue);	0
16277053	16265102	XNA: Orthographic window resizing without stretching	Projection = Matrix.CreateOrthographicOffCenter(\n    0.0f, _graphics.Viewport.Width,\n    _graphics.Viewport.Height, 0.0f,\n    -1.0f, 1.0f);	0
34144337	33900745	Workflow for data from Backbone through NHibernate	void Update(ParentDto parentDto){\n    Parent parent = _session.Get<Parent>(parentDto.Id);\n    //update parent fields\n\n    var childRemoved = //find removed child from parent;\n    parent.Children.Remove(childRemoved);\n\n    _session.SaveOrUpdate(parent);\n}	0
13542860	13542496	Need help creating an expression tree for Where clause	var paramExpr = Expression.Parameter(typeof(TSource), "src");\nvar memberExpr = (MemberExpression)property.Body;\n\nList<Expression> arrayInits = new List<Expression>();\n\nvar arrExpr = Expression.Constant(((string)values[0]).Split(new char[] { ';' }));\n\nMethodInfo containsMethod = typeof(ICollection<string>).GetMethod("Contains");\n\nvar containsExpression = Expression.Call(null, contains, arrExpr, memberExpr);\nvar containsLambda = Expression.Lambda<Func<TSource, bool>>(containsExpression, property.Parameters);	0
9536157	9501560	Run process under current user	ProcessAsUser.Launch("program name");	0
14908455	14908428	Copying offset to offset from file in C#	using (var output = File.Create("output.ts"))\n using (var input = File.OpenRead("input.ts"))\n {\n     AppendChunk(output, input, 0, 1174698823L);\n     AppendChunk(output, input, 1257553244L, 4126897791L);\n }\n\n ...\n\n private static void AppendChunk(Stream output, Stream input,\n                                 long start, long end)\n {\n     // TODO: Argument validation\n     long size = end - start;\n     byte[] buffer = new byte[32 * 1024]; // Copy 32K at a time\n     input.Position = start;\n     while (size > 0)\n     {              \n         int bytesRead = input.Read(buffer, 0, Math.Min(size, buffer.Length));\n         if (bytesRead <= 0)\n         {\n             throw new EndOfStreamException("Not enough data");\n         }\n         output.Write(buffer, 0, bytesRead);\n         size -= bytesRead;\n     }\n }	0
23929735	23929653	how to submit html form from behind code in c sharp	Response.Redirect("pathtomyhtmlpage.html");	0
16226580	16226229	Appending Date to the end of line in multiple textbox	dataTextView.Rows.Add(txtAddText.Text, DateTime.Now.ToShortTimeString());	0
6888051	6885477	Using Autofac to inject log4net into controller	ContainerBuilder builder = new ContainerBuilder();\nbuilder.RegisterControllers(typeof (MvcApplication).Assembly) ;\nbuilder.RegisterModule(new LogInjectionModule());\n\nvar container = builder.Build() ;\nDependencyResolver.SetResolver(new AutofacDependencyResolver(container));	0
25673585	25593771	Telerik, how to preserve a custom colorization when disabling a control?	class Plexiglass : Control\n{\n    protected override void OnPaint(PaintEventArgs e)\n    {\n        if (Parent != null)\n        {\n            Bitmap plexiCover = new Bitmap(Parent.Width, Parent.Height);\n            foreach (Control c in Parent.Controls)\n                if (c.Bounds.IntersectsWith(this.Bounds) & c != this)\n                    c.DrawToBitmap(plexiCover, c.Bounds);\n            e.Graphics.DrawImage(plexiCover, -Left, -Top);\n            plexiCover.Dispose();\n        }\n        e.Graphics.FillRectangle(new SolidBrush(Color.FromArgb(128, 0, 0, 0)), Bounds);\n    }\n}	0
22593024	22592997	How to get dataset from Getpaged?	bvl2 = bvs.GetPaged(" Date = '" + Today + "' AND UserId = " + SpecUserID + "", null, 0, 1000, out x).ToDataSet(false);	0
23809252	23809189	How to change a string to an int using Convert.ToSingle() in C#	int.Parse(ageMonth)	0
1195910	1195896	ThreadStart with parameters	Thread t = new Thread (new ParameterizedThreadStart(myMethod));\nt.Start (myParameterObject);	0
17092840	17092632	Saving values of a table output from stored procedure in a list	foreach (DataRow r in ds.Tables[0].Rows)\n{\n   for(int x = 0; x < r.ItemArray.Length; x++)\n       Console.WriteLine(r.ItemArray[x].ToString());\n   Console.WriteLine();    \n}	0
6580869	6580765	C# listbox continuous loop	BackgroundWorker worker = sender as BackgroundWorker;\nbool go = true;\nwhile(go)\n{\n    for (int i = listBox1.Items.Count - 1; i >= 0; i--)\n    {\n        {\n            if (worker.CancellationPending == true)\n            {\n                e.Cancel = true;\n                go = false;\n                break;\n            }\n            else\n            {\n                string queryhere = listBox1.Items[i].ToString();\n                this.SetTextappend("" + queryhere + "\n");\n                System.Threading.Thread.Sleep(500);\n                worker.ReportProgress(i * 1);\n            }\n        }\n    }\n}	0
6223662	6223570	Creation of Marquee in .NET windows application	private int xPos=0;\n\n        public Form1()\n        {\n            InitializeComponent();\n        }\n\n        private void timer1_Tick(object sender, EventArgs e)\n        {\n            if (this.Width == xPos)\n            {\n                //repeat marquee\n                this.lblMarquee.Location = new System.Drawing.Point(0, 40);\n                xPos = 0;\n            }\n            else\n            {\n                this.lblMarquee.Location = new System.Drawing.Point(xPos, 40);\n                xPos++;\n            }\n        }\n\n        private void Form1_Load(object sender, EventArgs e)\n        {\n            timer1.Start();\n        }	0
221209	221154	How can I Convert a Big decimal number to Hex in C# (Eg : 588063595292424954445828)	static string ConvertToHex(decimal d)\n{\n    int[] bits = decimal.GetBits(d);\n    if (bits[3] != 0) // Sign and exponent\n    {\n        throw new ArgumentException();\n    }\n    return string.Format("{0:x8}{1:x8}{2:x8}",\n        (uint)bits[2], (uint)bits[1], (uint)bits[0]);\n}	0
3989727	3989638	Best way to access a SQL Server database using C# .Net	// assuming a "Product" table, which has an entity pluralized to "Products"\n\nMyEntities db = new MyEntities();\n\nvar cheapProducts = db.Products.Where(p => p.Price > 30); // var is IEnumerable<Product>	0
9923283	9922997	Joins in nhibernate	PGrpR pGrpR = null;\n IList<PGrp> pGrps = _session.QueryOver(() => _pGrp)\n            .Where(x => !x.AC)\n            .JoinAlias(pgrps => pgrps.pGrpR, () => pGrpR) // Set real property name\n            .OrderBy(() => pGrpR.Name).Asc\n            .Select(Projections.Distinct(Projections.Property(() => pGrpR."PropertyForDistinct")))\n            .TransformUsing(Transformers.DistinctRootEntity)\n            .List<PGrp>();	0
8760492	8760263	How to release anonymous event hander resource?	EventHandler handler = null;\nhandler = (s, e) => \n{    \n    //......                 \n    vm.Loaded -= handler;\n};	0
15915419	15913292	Some sequential SignalR invokes getting dropped	var hubConnection = new HubConnection("http://url/");\n        hubConnection.TraceWriter = Console.Out;\n        hubConnection.Closed += () => Console.WriteLine("hubConnection.Closed");\n        hubConnection.ConnectionSlow += () => Console.WriteLine("hubConnection.ConnectionSlow");\n        hubConnection.Error += (error) => Console.WriteLine("hubConnection.Error {0}: {1}", error.GetType(), error.Message);\n        hubConnection.Reconnected += () => Console.WriteLine("hubConnection.Reconnected");\n        hubConnection.Reconnecting += () => Console.WriteLine("hubConnection.Reconnecting");\n        hubConnection.StateChanged += (change) => Console.WriteLine("hubConnection.StateChanged {0} => {1}", change.OldState, change.NewState);	0
23898770	23898187	Dealing with root nodes inside root nodes in XML with C#	[Serializable()]\npublic class Report {\n\n    [XmlIgnore()]\n    private AttachedFiles _attachedFiles;\n    public Report() {\n            attachedFiles = null;\n    } // end constructor\n\n    [XmlArray(ElementName = "AttachedFiles"), XmlArrayItem(ElementName = "AttachedFile")]\n    public AttachedFiles Files {\n            get { return _attachedFiles; }\n            set { _attachedFiles = value; }\n    } // end property Files\n\n} // end class Report\n\n[Serializable()]\n[XmlRoot("ReportList")]\npublic class ReportList {\n\n    [XmlIgnore()]\n    private Report[] _reports;\n\n    public ReportList() {\n        _reports = null;\n    } // end constructor\n\n    [XmlArray(ElementName = "nodes"), XmlArrayItem(ElementName = "node")]\n    public Report[] Reports {\n            get { return _reports; }\n            set { _reports = value; }\n    } // end property Reports\n\n} // end class ReportList\n\n[Serializable()]\npublic class AttachedFiles : List<string> {\n\n} // end class AttachedFiles	0
27161416	27161381	Iteratively add values from C# configuration file to drop down box	var maxIndex = ConfigurationManager.AppSettings.AllKeys\n                 .ToList()\n                 .Where(k => k.StartsWith("confname"))\n                 .Count();\n\nfor (var index = 1; index <= maxIndex; index++)\n{\n  cbxConfig.Items.Add(ConfigurationManager.AppSettings["confname{0}", index])\n}	0
25012357	25012262	Enum values to string list with filter	return\n    Enum.GetValues( typeof(AnimalCodeType) ).\n    Cast<AnimalCodeType>().\n    Where( v => (int)v > 0 ).\n    Select( v => v.ToString() ).\n    ToList();	0
30163227	30163147	Json passing multiple objects	List<Weapon> weapons = new List<Weapon>();\nforeach(var weapon in database.weapons)\n{\n    weapons.add(new Weapon \n                    { \n                        // initialise from db fields \n                    });\n}  \nws = JsonConvert.SerializeObject(weapons);	0
11706719	11706652	Select value in multi-column ListView	listViewResultados.SelectedItem	0
21778778	21778674	Split string and numbers	(?:(\d+):\s([^\d]+))+?	0
1908612	1908494	c# - combine 2 statements in a catch block into one	catch (MyCustomException)\n{\n   throw;\n}\ncatch (Exception ex)\n{\n   throw new MyCustomException(ex);\n}	0
12428413	12428049	How to query a XmlDocument without using LINQ	System.Xml.XmlNodeList MSPressBookList = xmldoc.SelectNodes("//Publisher[. = 'MSPress']/parent::node()/Title");	0
18085592	18085140	Switching Panels via Index Methods	void uc_ButtonClicked(object sender, EventArgs e) {\n  UserControl1 uc = sender as UserControl1;\n  if (uc != null) {\n    int childIndex = flowLayoutPanel1.Controls.GetChildIndex(uc);\n    if (childIndex > 0) {\n      UserControl1 ucTop = flowLayoutPanel1.Controls[0] as UserControl1;\n      flowLayoutPanel1.Controls.SetChildIndex(uc, 0);\n      flowLayoutPanel1.Controls.SetChildIndex(ucTop, childIndex);\n    }\n  }\n}	0
2884878	2884873	LINQ Query to filter DTO	masterList.Where(c => !excludeItem.Contains(c.customField));	0
27126887	27126364	gdi+ error saving image from console application	var path = @"D:\test1\newImage.bmp";	0
18901967	18795561	Multiple Automapper Naming Conventions	public class FromUnderscoreMapping : Profile\n{\n    protected override void Configure()\n    {\n        SourceMemberNamingConvention = new LowerUnderscoreNamingConvention();\n        DestinationMemberNamingConvention = new PascalCaseNamingConvention();\n        CreateMap<ArticleEntity, Article>();\n    }\n\n    public override string ProfileName\n    {\n        get { return "FromUnderscoreMapping"; }\n    }\n}\n\npublic class ToUnderscoreMapping : Profile\n{\n    protected override void Configure()\n    {\n        SourceMemberNamingConvention = new PascalCaseNamingConvention();\n        DestinationMemberNamingConvention = new LowerUnderscoreNamingConvention();\n        CreateMap<Article, ArticleEntity>();\n    }\n\n    public override string ProfileName\n    {\n        get { return "ToUnderscoreMapping"; }\n    }\n}	0
21084917	21084821	How to arrange Buttons in Circular shape in wpf using c# code?	Point cntr = new Point(this.Width/2, this.Height/2); // cntr Points Center of Circle\n// Count gives Number of Buttons        \nint count = 25; \n// angle gives angle Between each Button\ndouble angle = 360/(double)count; \nint radius = 150; // Circle's Radius\nfor (int i = 0; i < count; i++)\n{\n    Button button = new Button();\n    button.Text = "Button " + i;\n    button.Location = new Point((int)(cntr.X + radius * Math.Cos((angle * i) * Math.PI / 180)),\n        (int)(cntr.Y + radius * Math.Sin((angle * i) * Math.PI / 180)));\n    this.Panle1.Controls.Add(button);\n}	0
3645652	3645643	c# how to deal with events for multi dynamic created buttons	for (int i = 0; i < 10; i++)\n{\n    var btn = new Button();\n    btn.Text = "Button " + i;\n    btn.Location = new Point(10, 30 * (i + 1) - 16);\n    btn.Click += (sender, args) =>\n    {\n        // sender is the instance of the button that was clicked\n        MessageBox.Show(((Button)sender).Text + " was clicked");\n    };\n    Controls.Add(btn);\n}	0
2557662	2557598	How can I make a fixed hex editor?	int fd = open("test.dat", O_RDWR);\noff_t offset = lseek(fd, 200, SEEK_SET);\nif (off_t == -1) {\n    printf("Boom!\n");\n    exit(1);\n}    \nchar buf[1024];\nssize_t bytes_read = read(fd, buf, 1024);\noffset = lseek(fd, 100, SEEK_SET);\nssize_t bytes_written = write(fd, buf, 1024);\nflush(fd);\nclose(fd);	0
8659717	8658947	Looping through an XML document and assigning data in C# variables	XDocument xdoc = XDocument.Parse(@"<sitecollection name=""collectionName"">\n    <site name=""sitename"">\n    <maingroup name=""maingroupname""> \n    <group name=""groupname""> </group>\n    </maingroup> \n    </site>\n    </sitecollection>\n    ");	0
523586	523200	How do I get a user GUID from a selected item in a DropDownBox that is databound to a LINQ datasource?	UserClass user = MyDropDown.SelectedValue as UserClass;	0
29254252	29250818	How to get System.Windows.Media.Color From From HEX Windows 8 Application	public System.Windows.Media.Color ConvertStringToColor(String hex)\n    {\n        //remove the # at the front\n        hex = hex.Replace("#", "");\n\n        byte a = 255;\n        byte r = 255;\n        byte g = 255;\n        byte b = 255;\n\n        int start = 0;\n\n        //handle ARGB strings (8 characters long)\n        if (hex.Length == 8)\n        {\n            a = byte.Parse(hex.Substring(0, 2), System.Globalization.NumberStyles.HexNumber);\n            start = 2;\n        }\n\n        //convert RGB characters to bytes\n        r = byte.Parse(hex.Substring(start, 2), System.Globalization.NumberStyles.HexNumber);\n        g = byte.Parse(hex.Substring(start + 2, 2), System.Globalization.NumberStyles.HexNumber);\n        b = byte.Parse(hex.Substring(start + 4, 2), System.Globalization.NumberStyles.HexNumber);\n\n        return System.Windows.Media.Color.FromArgb(a, r, g, b);\n    }	0
670603	670570	Class in the BCL that will event at a given DateTime?	public void StartTimer(DateTime target) {\n  double msec = (target - DateTime.Now).TotalMilliseconds;\n  if (msec <= 0 || msec > int.MaxValue) throw new ArgumentOutOfRangeException();\n  timer1.Interval = (int)msec;\n  timer1.Enabled = true;\n}	0
19861256	19860145	How do I use Setup Project with Crystal Reports	"~\Report.rpt"	0
6130957	6119617	Click a button from another Application, emulating mouse + coords?	PostMessage(mainControlChild, WM_KEYDOWN, (int)Keys.Return, 0);\nPostMessage(mainControlChild, WM_KEYUP, (int)Keys.Return, 0);	0
1343360	1343341	XPath: How to select the first given parent of a node?	//currentSelectedNode/ancestor::childOfChild[1]	0
9289115	9287656	How to deal with null data in controller/view model	public ActionResult Edit(int id)\n{\n    var page = Services.PageService.GetPage(id);\n\n    if(page == null)\n    {\n        return Content("CANNOT FIND PAGE");\n    }\n\n    return View(page);\n}	0
17216552	17183714	browser showing model as query string in mvc	[HttpPost]\n   public ActionResult DisplayEmployee(Guid id)\n   {\n    model.emp=GetEmployeeDetails(id);\n     return View("GetEmployees");\n   }	0
18055487	18054739	How to filter data inside subreport RDLC	string tutorUserName = (e.Parameters["tutorusername"].Values.First()).ToString();\n ReportDataSource rdsTradeDetails = new ReportDataSource("Test_DataSet", report);\n e.DataSources.Add(rdsTradeDetails);	0
6999771	6999296	split huge 40000 page pdf into single pages, itextsharp, outofmemoryexception	iTextSharp.text.pdf.PdfReader reader = new iTextSharp.text.pdf.PdfReader(new iTextSharp.text.pdf.RandomAccessFileOrArray(@"C:\PDFFile.pdf"), null);	0
12309706	12309607	Accessing my Model from a background agent in Windows Phone 7 using MVVM Light	- Project.Model\n    ModelClass\n    ModelClass2\n- Project.Background\n    Agent\n- Project.Application\n    App\n    MainPage	0
24853500	24853376	Before inserting new element in xml check if exists the value	XDocument xml = XDocument.Load("path_to_file");\nstring newCountry = "UAE";\n\nXElement countries = xml.Descendants("Countries").First();\nXElement el = countries.Elements().FirstOrDefault(x => x.Value == newCountry);\nif (el == null)\n{\n    el = new XElement("country");\n    el.Value = newCountry;\n    countries.Add(el);        \n}\n\n//Console.WriteLine(countries.ToString());	0
3230704	3228883	Copying a range of cells from excel into powerpoint using VSTO	app.ActiveWindow.View.Paste(); \n// instead of\n// pptSlide.Shapes.Paste();	0
18322616	18322559	How to programmatically hide the keyboard	this.Focus();	0
27105879	27105702	How can I use regex expression to match database and table name given in textbox	var query = @"SELECT * FROM [Database Name].[dbo].[Table Name]";\n var match = Regex.Match(query, @"\[([^\]]+)\]\.\[dbo\]\.\[([^\]]+)\]").Groups;\n var database = match[1].ToString();\n var table = match[2].ToString();\n\n //database = "Database Name"\n //table = "Table Name"	0
7026172	7026097	How to do language Specific sort in C#?	Thread.CurrentThread.CurrentCulture = = new CultureInfo("ja-JP");	0
14776413	14776105	delete folder after I use the program	string imgPath = string.Format("{0}{1}.jpg", pngOutputPath, i);\n// Retrieve image from file\nImage img = Image.FromFile(imgPath);\n// Create new canvas to paint the picture in\nBitmap tempImg = new Bitmap(img.Width, img.Height);\n// Paint image in memory\nusing (Graphics g = Graphics.FromImage(tempImg))\n{\n   g.DrawImage(img, 0, 0);\n}\n// Assign image to PictureBox\npb.Image = tempImg;\n// Dispose original image and free handles\nimg.Dispose();\n// Delete the original file\nFile.Delete(imgPath);	0
9853715	9853467	Update ASP Label inside ASP Datalist	(e.Item.FindControl("lblShowResponses") as Label).Text = "Test";\n(e.Item.FindControl("lblShowResponses") as Label).Visible = true;	0
11158792	11158401	Matrix multiplication in C#	Parallel.For(\n  0\n  ,5000\n  , (i) => { \n    for(var j=0;j<1024;j++)\n    {\n      result[i,j] = .....\n    }\n);	0
27461931	27461741	Parsing through innerHTML with HtmlAgilityPack	HtmlNodeCollection nodes = doc.DocumentNode.SelectNodes("//div[@class='result-link']");\nif (nodes != null)\n{\n    foreach (HtmlNode node in nodes)\n    {\n        HtmlNode a = node.SelectSingleNode("a[@href]");\n        if (a != null)\n        {\n            // use  a.Attributes["href"];\n        }\n\n        // etc...\n    }\n}	0
24717969	24717887	How do I populate a 'asp:ListBox' with an array of strings?	lstDSYDepartment.Items.Add("Administration");\nlstDSYDepartment.Items.Add("Imaging Services");\n...	0
4048479	4048459	creating new threads in a loop	foreach (int num in Enumerable.Range(0,5))\n    {\n        int loopnum = num;\n\n        thread = new Thread(() => print(loopnum.ToString())); \n        thread.Start();  \n    }	0
16297293	16297171	scriptmanager alert not working with in modelpopup button click	ClientScript.RegisterStartupScript(this.GetType(), "Alert", script, true);	0
21410278	21410153	Get duplicates from C# List<object>	List<ListItem> entitiesList = new List<ListItem>();\n//some code to fill the list\nvar duplicates = entitiesList.OrderByDescending(e => e.createdon)\n                    .GroupBy(e => e.accountNumber)\n                    .Where(e => e.Count() > 1)\n                    .Select(g => new\n                    {\n                        MostRecent = g.FirstOrDefault(),\n                        Others = g.Skip(1).ToList()\n                    });\n\nforeach (var item in duplicates)\n{\n    ListItem mostRecent = item.MostRecent;\n    List<ListItem> others = item.Others;\n    //do stuff with others\n}	0
7113481	7112378	Oracle stored procedure creation from C# code fails for PL/SQL devloper	SQL> CREATE OR REPLACE PROCEDURE p(TYPE IN VARCHAR2) IS\n  2  BEGIN\n  3    dbms_output.put_line(TYPE);\n  4  END;\n  5  /\n\nProcedure created\nSQL> DECLARE\n  2  BEGIN\n  3    p('This is a test');\n  4  END;\n  5  /\n\nThis is a test\n\nPL/SQL procedure successfully completed\n\nSQL>	0
2321106	2321103	An attribute argument must be a constant expression is there a way around this in C#?	#if x64\n// ... define all x64 imports here\n#else\n// ... define all x86 imports here\n#endif	0
27469119	27468865	How to update a single column with Multiple values using MS Access as RDBMS and c#?	SQLCommand.Parameters.AddWithValue("@RollNo", Convert.ToInt32(this.rollNumber7_combo.SelectedItem.ToString());\nSQLCommand.Parameters.AddWithValue("@regYear", Convert.ToInt32(this.comboBox3.SelectedItem.ToString());\nSQLCommand.Parameters.AddWithValue("@program ", this.comboBox2.SelectedItem.ToString();\nSQLCommand.Parameters.AddWithValue("@faculty ", this.comboBox1.SelectedItem.ToString();     \n\n SQLString2 = "DELETE subjects WHERE RollNo = @RollNo AND regYear = @regYear AND program = @program AND faculty = @faculty; \n\n'---Execute the delete statement...\n\n foreach (var item in checkedListBox1.CheckedItems)\n        {\n            foreach (string subName in (item.ToString().Split('+')))\n            {\n                SQLCommand.Parameters.AddWithValue("@SUBJECT", subName);\n\n                SQLString2 = "INSERT INTO subjects ('RollNo','RegYear','faculty','program','subjectN') VALUES (@RollNo,@regYear,@faculty,@program,@SUBJECT);\n\n\n            }	0
14365234	14365143	Create a random customer number and display it in a textbox	Guid g = Guid.NewGuid();	0
932380	932300	C# Ranking of objects, multiple criteria	static class Program\n{\n\n    static IEnumerable<Result> GetResults(Dictionary<TournamentTeam, double> wins, Dictionary<TournamentTeam, double> scores)\n    {\n        int r = 1;\n        double lastWin = -1;\n        double lastScore = -1;\n        int lastRank = 1;\n\n        foreach (var rank in from name in wins.Keys\n                             let score = scores[name]\n                             let win = wins[name]\n                             orderby win descending, score descending\n                             select new Result { Name = name, Rank = r++, Score = score, Win = win })\n        {\n            if (lastWin == rank.Win && lastScore == rank.Score)\n            {\n                rank.Rank = lastRank;\n            }\n            lastWin = rank.Win;\n            lastScore = rank.Score;\n            lastRank = rank.Rank;\n            yield return rank;\n        }\n    }\n}\n\nclass Result\n{\n    public TournamentTeam Name;\n    public int Rank;\n    public double Score;\n    public double Win;\n}	0
25735821	25735796	Ensure a string representing a decimal number has a 0 before the "."	newValue = searchFieldValue1.StartsWith(".")\n               ? "0" + searchFieldValue1\n               : searchFieldValue1;	0
8931565	8931027	Easiest way to create a delegate when the method contains a 'ref' parameter	Delegate methodCall = new Func<MyService.CallResult>(delegate() { return service.DoWork(ref myInput)});\nobject callResult = CallMethod(methodCall, null);	0
27441902	27417445	How to not insert a field in mongodb if it is null?	{ "date", mydate.Value, mydate.HasValue }	0
6942461	6942071	How to get the path of an embebbed resource?	GetType().Assembly.GetManifestResourceStream("someresourcestringhere")	0
13615327	13614242	VSIX: open browser window	var itemOps = Dte.ItemOperations;\nitemOps.Navigate("http://bing.com");	0
26191287	26191281	C# join two datatables with conditions	where row1.Field<string>("value") == "I"\nselect something;	0
7804763	7804125	How to pass a control as a parameter to delegate	cbo1.Dispatcher.BeginInvoke(\n    (Action)(() => StyleComboBoxItem(cbo1)), \n    System.Windows.Threading.DispatcherPriority.Background);\n\ncbo1.Dispatcher.BeginInvoke(\n    (Action)(() =>\n    {\n        //code to style the comboboxitem;\n    }),\n    System.Windows.Threading.DispatcherPriority.Background);	0
9369573	9369535	How to prompt user to save an automated Excel file	const string fName = @"C:\Test.xls";\n  FileInfo fi = new FileInfo(fName);\n  long sz = fi.Length;\n\n  Response.ClearContent();\n  Response.ContentType = Path.GetExtension(fName);\n  Response.AddHeader("Content-Disposition", string.Format("attachment; filename = {0}",System.IO.Path.GetFileName(fName)));\n  Response.AddHeader("Content-Length", sz.ToString("F0"));\n  Response.TransmitFile(fName);\n  Response.End();	0
21929954	21929762	Save Config in the Application Startup	msi package	0
12983599	12972497	How to seed data to a List<String> model member?	public class Person\n{\n    public int Id { get; set; }\n    public string Firstname { get; set; }\n    public string Lastname { get; set; }\n    public virtual List<Child> Children { get; set; }\n    // Your other code\n}\n\npublic class Child\n{\n    public int Id { get; set; }\n    public string Name { get; set; }\n}	0
7305690	7305651	How to refactor sequential ifs?	catch(){}	0
14092438	14091854	one-to-many insert using dapper dot net	var allSurveyCategories = surveys.SelectMany(s =>\n     s.Categories.Select(c => new{SurveyId = s.SurveyId, CategoryId = c}));	0
14793056	14783522	How can I force the application to use only library from the specified path in c#?	var initialName = AssemblyName.GetAssemblyName("Foo.dll");\nConsole.WriteLine(initialName);\nConsole.WriteLine(initialName.Version);\n// replaced the dll manually\n\ninitialName = AssemblyName.GetAssemblyName("Foo.dll");\nConsole.WriteLine(initialName);\nConsole.WriteLine(initialName.Version);	0
14711868	14711685	Download files from sql-server with an specific name using mvc2010	Response.AddHeader("content-disposition", "attachment;filename=" + Path.GetFileName(file.Name));	0
7114637	7114619	C# String.Format with Curly Bracket in string	string.Format("{{ foo: '{0}', bar: '{1}' }}", foo, bar);	0
34367223	34367077	How to express ordinal/cardinal directions that can be added together in C#?`	if a = b then \n   new_direction = a\n else      \n   if a < b then \n     if (b-a < 180) then\n       new_direction = (a + (b-a)/2) mod 360\n     else\n       new_direction = (b + (360 - b + a)/2) mod 360\n   else\n     if (a-b < 180) then\n       new_direction = (b + (a-b)/2) mod 360 \n     else\n       new_direction = (a + (360 - a + b)/2) mod 360	0
7762074	7762036	Several inserts performance c#	using (var connection = ...)\nusing (var tx = new TransactionScope()) {\n   foreach (var row in rows) {\n      // insert row\n   }\n   // commit all at once\n   tx.Complete();\n}	0
31523381	31523288	How do I use string formatting, comparison and parsing in a system-independent way?	CultureInfo.DefaultThreadCurrentCulture	0
22795262	22795199	Proper Implementation of IQueryable as a Member Variable on a Model?	var messages = db.Pads.Where(p => p.PadId == padGuid)\n    .SelectMany(pad => p.Messages.OrderBy(c => c.SendTime)\n        .Skip(Math.Max(0, pad.Messages.Count() - 25)));	0
30639118	30637452	StackOverflowException with Process in C#	public void RecurseTask() {\n    while(true)\n    {\n        /*\n        You can try one of these, but you will se CPU usage go crazy and perhaps concurrency errors due IO blocking\n\n        Parallel.ForEach( _videoStreamSlugs, ( e ) => _videoStreamScreenShots.GrabScreenShot( e ) );\n\n        foreach ( var slug in _videoStreamSlugs ) {\n            Task.Run( () => _videoStreamScreenShots.GrabScreenShot( slug ) );\n        }\n        */\n\n        //we want to grab screen shots for every slug in out slug list!\n        foreach ( var slug in _videoStreamSlugs ) {\n            _videoStreamScreenShots.GrabScreenShot( slug );\n        }\n\n        //sleep for a little while\n        Thread.Sleep( _recurseInterval );\n\n        //A heavy clean up!\n        //We do this, trying to avoid a stackoverflow excecption in the recursive method\n        //Please inspect this if problems arise\n        //GC.Collect(); Not needed\n\n        //lets grab over again\n    }\n}	0
10304304	10303961	Custom Attribute - get value of underlying enum	public enum NavigationLinks\n{\n    SystemDashboard,\n    TradingDashboard,\n}\n\npublic static class Program\n{\n    private static string ToFriendlyName(string defaultName)\n    {\n        var sb = new StringBuilder(defaultName);\n\n        for (int i = 1; i < sb.Length; ++i)\n            if (char.IsUpper(sb[i]))\n            {\n                sb.Insert(i, ' ');\n                ++i;\n            }\n\n        return sb.ToString();\n    }\n\n    public static void Main(string[] args)\n    {\n        var value = NavigationLinks.SystemDashboard;\n\n        var friendlyName = ToFriendlyName(value.ToString());\n    }\n}	0
15945720	15945662	Returning values from threads	// Return a value type with a lambda expression\n    Task<int> task1 = Task<int>.Factory.StartNew(() => 1);\n    int i = task1.Result;\n\n    // Return a named reference type with a multi-line statement lambda.\n    Task<Test> task2 = Task<Test>.Factory.StartNew(() =>\n    {\n        string s = ".NET";\n        double d = 4.0;\n        return new Test { Name = s, Number = d };\n    });\n    Test test = task2.Result;	0
28114428	28112387	MVC Kendo Grid not showing any data	public JsonResult KendoGrid([DataSourceRequest]DataSourceRequest request)\n{\n    DataSourceResult result = UnitOfWork.Enrollment.Dependents.ToDataSourceResult(request,\n        model => new DependentModel\n        {\n            SSN = model.SSN,\n            FirstName = model.FirstName,\n            LastName = model.LastName,\n            DateOfBirth = model.DateOfBirth,\n            Gender = model.Gender,\n            DependentTypeId = model.DependentTypeId\n        });\n\n\n    return Json(result,JsonRequestBehavior.AllowGet);   \n}	0
1605235	1605231	Accessing value of a non static class in a static class	staticA.AValue = b.BValue	0
2636328	2636225	Additional parameters for FileSystemEventHandler	foreach (String config in configs)\n{\n    ...\n    FileWatcher.Created += (s,e) => DoSomething(e.FullPath, mSettings);\n    ...\n}	0
8885460	8884499	How to determine if an instance of the .NET application from a certain location is running?	public partial class App : Application\n    {\n        private Mutex _instanceMutex = null;\n\n        protected override void OnStartup(StartupEventArgs e)\n        {\n\n            string path = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location).Replace("\\", ".");\n\n            // check that there is only one instance of the control panel running...\n            bool createdNew;\n            _instanceMutex = new Mutex(true, path, out createdNew);\n            if (!createdNew)\n            {\n                _instanceMutex = null;\n                MessageBox.Show("Instance already running");\n                Application.Current.Shutdown();\n                return;\n            }\n\n            base.OnStartup(e);\n        }\n\n        protected override void OnExit(ExitEventArgs e)\n        {\n            if (_instanceMutex != null)\n                _instanceMutex.ReleaseMutex();\n            base.OnExit(e);\n        }\n\n}	0
13900890	13900793	How can I view string content being written by XMLWriter to a Stream/MemoryStream?	memoryStream.Position = 0;\n    var sr = new StreamReader(memoryStream);\n    var myStr = sr.ReadToEnd();\n    Console.WriteLine(myStr);	0
19624889	19624731	How to open file that is on desktop	private void ReadFromDesktop(string fileName)\n    {\n        string desktopPath = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);\n        string fullName = System.IO.Path.Combine(desktopPath, fileName);\n        using (StreamReader steamReader = new StreamReader(fullName))\n        {\n            string content = steamReader.ReadToEnd();\n        }\n    }	0
6770436	6756289	How to draw child controls and custom drawings in expected order?	GraphicsPath path = new GraphicsPath();\n// add some shapes to path here, describing the control shape\n// ...\nthis.Region = new Region(path);	0
8657303	8652393	How to link the scrollbar position of a set of controls?	public class CompositeScroll\n{\n    private List<Scrollbar> scrollbars = new List<Scrollbars>();\n\n    public void AddScrollbar(Scrollbar scrollbar)\n    {\n        scrollbars.Add(scrollbar);\n        scrollbar.OnScroll += OnScroll;\n    }\n\n    private void OnScroll(object sender, EventArgs e)\n    {\n        var current = (Scrollbar)sender;\n        var scrollbarsToMove = scrollbars.Where(x => x != current);\n\n        foreach(var scrollbar in scrollbarsToMove)\n            scrollbar.Position = current.Position;\n    }\n}\n\npublic class MyForm : Form\n{\n    private CompositeScroll compositeScroll = new CompositeScroll();        \n\n    public MyForm()\n    {\n        InitializeComponents();\n        compositeScroll.AddScrollbar(scrollbar1);\n        compositeScroll.AddScrollbar(scrollbar2);\n        compositeScroll.AddScrollbar(scrollbar3);\n        compositeScroll.AddScrollbar(scrollbar4);\n    }\n}	0
4581058	4581022	How do I save settings in C#	RegistryKey currentUser = Registry.CurrentUser;\nRegistryKey subKey = currentUser.CreateSubKey("MyTest", RegistryKeyPermissionCheck.ReadWriteSubTree);\nsubKey.SetValue("WindowHeight", 1024);\nsubKey.SetValue("WindowWidth", 1024);	0
11123601	11120385	XMLNode children allowed by the XML Schemes associated	push-based manner	0
21026039	21025021	Dynamically adding TextBlock using C# in Windows store App	TextBlock colorText = new TextBlock();\ncolortext.Foreground= new SolidColorBrush(Colors.Yellow);\n\nthis.Panel.Children.Add(colortext)	0
12872616	12872596	How can i debug a program written in c# without VS	System.Reflection.MethodBase.GetCurrentMethod().Name	0
29850623	29850169	how to iterate through model to find similar value in MVC	public static string LocationIPAssign(Location locationToAssign)  \n{ \n    string workstationLocation = ComputerIPName();\n    foreach(Location location in Locations) // ICollection<Location>, IList<Location>\n    { \n        if(location.AssignedIP == workstationLocation) \n        {\n            // do whatever you have to do with your locationToAssign\n        }\n    }\n    return workstationLocation;\n}	0
2077791	2038730	Sending keystrokes from a C# application to a Java application - strange behaviour?	private void SendKeysToWindow(string WindowName, string KeysToSend)\n    { \n        IntPtr hWnd = FindWindow(null, WindowName);            \n        ShowWindow(hWnd, SW_SHOWNORMAL);\n        SetForegroundWindow(hWnd);\n        Thread.Sleep(50);\n        SendKeys.SendWait(KeysToSend);           \n    }	0
32861576	32861357	Access view model required error message data annotation from Resource file in code - MVC	retVal =  (string)req.GetType().GetProperty("ErrorMessageString", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance).GetValue(req);	0
9938582	9938524	Querying Datatable with where condtion	var res = from row in myDTable.AsEnumerable()\nwhere row.Field<int>("EmpID") == 5 &&\n(row.Field<string>("EmpName") != "abc" ||\nrow.Field<string>("EmpName") != "xyz")\nselect row;	0
6738142	6737976	XML Based Project File	public XDocument NewDocument(string path)\n{\n    var doc =\n        new XDocument(\n            new XElement(\n                "Project",\n                new XAttribute("version", "1.0"),\n                new XAttribute("authorname", "user"),\n                new XElement("Platform", ".NET"),\n                new XElement("Code", "codefile.xml"),\n                new XElement("Canvas", "canvas.xml")));\n    doc.Save(path);\n    return doc;\n}	0
23496442	23479732	ServiceStack setting the date format per IService, not globally	JsConfig<ResponseType>.DeSerializeFn	0
9319323	9314943	Serializing a class to xml using RestSharp.AddBody fails	class Dummy\n{\n    public string A { get; set; };\n    public string B { get; set; };\n\n    public Dummy() {\n        A = "Some string";\n        B = "Some string";\n    }\n}	0
15429991	15429656	textbox max characters without special characters	private void textBox1_KeyPress(object sender, KeyPressEventArgs e)\n{\n    if(Char.IsNumber(e.KeyChar))\n        if(textBox1.Text.Replace(",", "").Replace(".", "").Length >= 5)\n            e.Handled = true;\n}	0
28573914	28573784	EF6 Getting Count In Single Call	string query = "SELECT *, \n                       (SELECT Count(*) FROM ChildTable c \n                       WHERE c.ParentId = p.Id) as NumberOfVotes\n                FROM ParentTable p";\n\nRowShape[] rows = ctx.Database.SqlQuery<RowShape>(query, new object[] { }).ToArray();	0
3698929	3698885	How to remove non-ASCII word from a string in C#	string input = "AB ?? CD";\nstring result = Regex.Replace(input, "[^\x0d\x0a\x20-\x7e\t]", "");	0
12720436	12718754	How to load all the known Colors with in a Listbox?	KnownColor[] colors  = Enum.GetValues(typeof(KnownColor));\nforeach(KnownColor knowColor in colors)\n{\n  Color color = Color.FromKnownColor(knowColor);\n\n    ListBoxItem listItem = new ListBoxItem();\n    listItem.Content = color.ToString();\n    listItem.Color = color ;\n    listbox1.Items.Add(listItem);\n}	0
19280662	19278470	XmlException while parsing xml with encoding specified as "utf-16"	string encoding = "UTF-8"; // should match encoding in XML\nstring xml = @"<?xml version='1.0' encoding='UTF-8'?><table><row>1</row></table>";\n\nvar ms = new MemoryStream(Encoding.GetEncoding(encoding).GetBytes(xml));\n\nvar xdrs = new XmlReaderSettings()\n    {IgnoreComments = true,\n    IgnoreWhitespace = true,\n    CloseInput = true};\n\nvar xdr = XmlReader.Create(ms, xdrs);\nwhile (xdr.Read())\n {\n    Console.Write("qqq");\n }	0
18734238	17545064	Changing the view in the library DhtmlX	scheduler.Initialview="viewname";	0
33933800	33933417	JSON.Net deserialization populate missing properties	public class Root\n{\n    public SpecialProperty Name { get; set; }\n    public SpecialProperty Surname { get; set; }\n\n    public Root()\n    {\n        this.Name = SpecialProperty.GetEmptyInstance();\n        this.Surname = SpecialProperty.GetEmptyInstance();\n    }\n}\n\npublic class SpecialProperty\n{\n    public string Name { get; set; }\n    public string Type { get; set; }\n\n    public static SpecialProperty GetEmptyInstance()\n    {\n         return new SpecialProperty\n         {\n              Name = string.Empty,\n              Type = string.Empty\n         };\n    }\n}	0
15107348	15106605	Catch Xpath conditions with Regex	string regex=@"\[.*\]";\nstring predicate=Regex.Match(input, regex).Value;//assuming there is a match\nregex=@"\s(and|or)\s";\nstring[] conditions=Regex.Split(predicate, regex);	0
22541659	22541429	Issue on Replacing Text with Index Value in C#	void Main() {\n\n    string text = File.ReadAllText(@"T:\File1.txt");\n    int num = 0;\n\n    text = (Regex.Replace(text, "map", delegate(Match m) {\n        return "map" + num++;\n    }));\n\n    File.WriteAllText(@"T:\File1.txt", text);\n}	0
5326556	5326411	Adding childs to a treenode dynamically in c#	TreeView myTreeView = new TreeView();\nmyTreeView.Nodes.Clear();\nforeach (string parentText in xml.parent)\n{\n   TreeNode parent = new TreeNode();\n   parent.Text = parentText;\n   myTreeView.Nodes.Add(treeNodeDivisions);\n\n   foreach (string childText in xml.child)\n   {\n      TreeNode child = new TreeNode();\n      child.Text = childText;\n      parent.Nodes.Add(child);\n   }\n}	0
18686918	18685421	Localization - how to name resource file so asp.net mvc will find it?	Localization.resx\nLocalization.en-US.resx\nLocalization.fr-FR.resx\nLocalization.ru-RU.resx	0
10950738	10950671	Need a performant way to return all duplicates from a list	var cars = new List<Car> { car1, car2, car3, car4, car5 };\nvar lookup = cars.ToLookup(car => car.Color);\nvar redCars = lookup[Red];\n// redCars == { car1, car4, car5 }	0
13502965	13502616	Fill SQL data from a .sql file downloaded automatically	using System.Net;\n\n//Download\nWebClient Client = new WebClient ();\nClient.DownloadFile("http://ts1.travian.com/map.sql", @"C:\folder\file.sql");\n\n// Read into a file\nvar sqltext = System.IO.File.ReadAllText(@"c:\folder\file.sql");\n// Split the sql statements up\nvar sqlStatements = sqltext.Split(';'); \n\n// Insert\nusing (SqlConnection connection = new SqlConnection(connectionParameters))\n    {   \n        connection.Open();\n        foreach (var sqlStatement in sqlStatements)  \n        {\n            SqlCommand command = new SqlCommand(sqlStatement, connection);\n            command.ExecuteNonQuery();\n        }\n    }	0
25175552	25175402	how to insert two values manually into table by using code	var result = new List<Role> {\n   new Role { Id = 0, Name = "--Select Roles--" },\n   new Role { Id = -1, Name = "--Any--" }\n};\n\nvar roles = from role in _db.Roles\n            where role.FunctionId == functionId\n            orderby role.Name ascending\n            select role;\n\nresult.AddRange(roles);\n\nreturn result;	0
6362008	6361986	how get integer only and remove all string in C#	input = Regex.Replace(input, "[^0-9]+", string.Empty);	0
9760751	9759697	Reading a file used by another process	using (var fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))\nusing (var sr = new StreamReader(fs, Encoding.Default)) {\n    // read the stream\n    //...\n}	0
16320655	16320243	setting a value based on another value in a linq query	SomeByte = (byte)(x.SomeField=="test"?1:0)	0
7897886	7897699	reading windows font	using System.Drawing.Text;\n\nInstalledFontCollection myFonts = new InstalledFontCollection();\nforeach (FontFamily ff in myFonts.Families)\n  comboBox1.Items.Add(ff.Name);\n}	0
3057601	3057473	Disable the 'requirement' to double click an unfocused window when clicking on a menustrip	protected override void WndProc(ref Message m) {\n    int WM_PARENTNOTIFY = 0x0210;\n    if (!this.Focused && m.Msg == WM_PARENTNOTIFY) {\n        // Make this form auto-grab the focus when menu/controls are clicked\n        this.Activate();\n    }\n    base.WndProc(ref m);\n}	0
31256079	31255115	How to input selected characters of password using selenium c# webdriver	//Your password string\nconst string testPassword = "TestPassword";\n//find the id attribute that contains the index of character needs to be input\nstring str= driver.FindElement(By.CssSelector("input[id^='edit-password-challenge']")).GetAttribute("id");\n//find the index of the char\nint index = Convert.ToInt16(Regex.Match(str, "[0-9]+").ToString().Replace("\"", ""));\n//find the char and convert to string so that can be used with SendKeys() method\nstring charToInput = testPassword[index-1].ToString();\n\n//input the password using the SendKeys() method\ndriver.FindElement(By.CssSelector("the selector")).SendKeys(charToInput);	0
7436454	7436400	How to use Split with TryParse?	var myDoubleList = new List<double>();\nforeach(var doubleString in textBox1.Text.Split(' '))\n{\n    double myDouble;\n    if (double.TryParse(doubleString, out myDouble))\n        myDoubleList.Add(myDouble);    \n}	0
1407261	1407195	Prevent DataGridView selecting a row when sorted if none was previously selected	this.dataGridView1.Sorted += new System.EventHandler(dataGridView1_Sorted);\n\nvoid dataGridView1_Sorted(object sender, System.EventArgs e)\n{\n    dataGridView1.ClearSelection();\n}	0
26584367	23860300	wptoolkit windows phone 8 AutocompleteBox	private void acBox_SelectionChanged(object sender, SelectionChangedEventArgs e)\n        {\n            if (e.AddedItems.Count > 0)\n            {\n                ItemViewModel firstItem = e.AddedItems[0] as ItemViewModel;\n                if (firstItem != null)\n                {\n                    int fileId = firstItem.HymnId;\n                    fileId = fileId - 1;\n                    NavigationService.Navigate(new Uri("/DetailsPage.xaml?selectedItem=" + fileId, UriKind.Relative));\n                }\n            }\n        }	0
4867105	4866691	EF4 POCO Many To One	public class Customer\n{\n  public int CustomerId { get; set;}\n //navigation\n  public List<CustomerProperty> CustomerProperties { get; set;}\n}\n\npublic class CustomerProperty\n{\n  public int CustomerPropertyId { get; set;}\n  //navigation\n  public Customer Customer { get; set; }\n}	0
9767499	9767240	Keep database file in different partition	-- For an .mdf with no log file - rebuild it.\nCREATE DATABASE [{0}] ON ( FILENAME = N'{1}' ) ATTACH_REBUILD_LOG;);     \n-- For a standard attach.\nCREATE DATABASE [{0}] ON ( FILENAME = N'{1}' ) FOR ATTACH;	0
25239759	25239696	Pass additional parameters to generic implementation	public interface IService<T>\n{\n    void Do<T>(T entity, params object[] parameters);\n}	0
6192804	6189782	C# XNA Matrices - Calculate moon rotation around axis with matrices	world = Matrix.CreateScale(size,size,size)\n        * Matrix.CreateTranslation(0,0,0) \n        * Matrix.CreateRotationY(rotation)\n        * Matrix.CreateTranslation(position)\n        * Matrix.CreateRotationY(revolution); \n\nworld *= Matrix.CreateTranslation( parent.getPosition() );	0
15126042	15125735	Data encoding - PHP vs C#	byte[] asciiBytes = ASCIIEncoding.ASCII.GetBytes(tosigndata); // tosigndata is your string variable\nbyte[] hashedBytes = MD5CryptoServiceProvider.Create().ComputeHash(asciiBytes);\nstring hashedString = BitConverter.ToString(hashedBytes).Replace("-", "").ToLower();\n// hashString contains your hash data similar to php md5	0
31584724	31181547	Can you open perfmon.exe, clear any current counts and add your custom app counters?	Stats.Increment("db.query.count");	0
10246789	10246642	Add project as reference to another project	when you have different target .NET framework	0
24082521	24082445	C# - Detect locked files in a directory	public bool IsFileLocked(string filePath)\n{\n    try\n    {\n        using (File.Open(filePath, FileMode.Open)){}\n    }\n    catch (IOException e)\n    {\n        retturn true;\n    }  \n\n    return false;\n}	0
9455079	9455043	How do i make a class iterable	class csWordSimilarity : IEnumerable<int>\n{\n    private int _var1 = 1;\n    private int _var2 = 1;\n    private int _var3 = 1;\n    private int _var4 = 1;\n\n    public IEnumerator<int> GetEnumerator()\n    {\n        yield return _var1;\n        yield return _var2;\n        yield return _var3;\n        yield return _var4;\n    }\n\n    IEnumerator IEnumerable.GetEnumerator()\n    {\n        return GetEnumerator();\n    }\n}	0
9615999	9615661	Save Headers from datagridview to excel? save as Excel 2007 format (.xlsx)?	dataGridView1.Columns[X].HeaderText	0
11794234	11794146	Convert int to byte as HEX in C#	int num = 45;\nint bcdNum = 16*(num/10)+(num%10);	0
3893711	3893622	Windows 98-style progress bar	using System;\nusing System.Windows.Forms;\nusing System.Runtime.InteropServices;\n\nclass SimpleProgressBar : ProgressBar {\n    protected override void OnHandleCreated(EventArgs e) {\n        base.OnHandleCreated(e);\n        if (Environment.OSVersion.Version.Major >= 6) {\n            SetWindowTheme(this.Handle, "", "");\n        }\n    }\n    [DllImport("uxtheme.dll")]\n    private static extern int SetWindowTheme(IntPtr hWnd, string appname, string idlist);\n}	0
12880048	12880009	How to call a webservice when in localhost	WebRequest.Create	0
21685553	21684773	Pull entire excel row using LinqToExcel	var excel = new ExcelQueryFactory("excelFileName");\nvar firstRow = excel.Worksheet().First();\nvar companyName = firstRow["CompanyName"];	0
16154891	16154809	Given top left and bottom right points, how can I find all points inside a rectangle?	for i = left_edge to right_edge\n    for j = top_edge to bottom_edge\n        add [i, j] to list of points inside rectangle	0
30833814	14543828	How do I programatically add more panes to a avalon dock	LayoutAnchorable la = new LayoutAnchorable { Title = "New Window", FloatingHeight = 400, FloatingWidth = 500, Content = new YourUserControl() };\n    la.AddToLayout(dockingManager, AnchorableShowStrategy.Right);\n    la.Float();	0
27292136	27291816	Binding combo-box with default text using Reader	cboDepartment.Items.Add("--Select Department--");\n while (oReader.Read())\n  {                   \n    string _Combobox = oReader["Name"].ToString();\n    cboDepartment.Items.Add(_Combobox);\n  }\n  cboDepartment.selectedIndex=0;	0
8282350	8282258	convert equirectangular to tiles library C#	System.Drawing.Bitmap.Clone(Rectangle, PixelFormat)	0
33029473	33029360	How does one manage a mix of synchronous and asynchronous processes in C#?	void ProcessA()\n{\n    ProcessA1();\n    ProcessA2();\n}\n\nvoid ProcessB()\n{\n    ProcessB1();\n    ProcessB2();\n}\n\nvoid LaunchProcesses()\n{\n    Task aTask = Task.Run((Action)ProcessA); //You could also call use Task.Run(() => ProcessA());\n    Task bTask = Task.Run((Action)ProcessB);\n    aTask.Wait();\n    bTask.Wait();\n}	0
2976427	2976373	How do I get generics to work with return values that require careful casting?	var result = ExecuteScalar(storedProcName, parameters);\nif(Convert.IsDBNull(result))\n    return default(T)\nif(result is T) // just unbox\n    return (T)result;\nelse            // convert\n    return (T)Convert.ChangeType(result, typeof(T));	0
26117896	26117620	Replacing Activator.CreateInstance with a compiled lambda	var receptionPanelView = constructor.DynamicInvoke() as System.Windows.Window;	0
1593119	1593104	Problem with calling a run file from c# Application	batch.StartInfo.WorkingDirectory = "E:\\newFiles";	0
12355359	12355125	linq to sql loading children on one to many relationship	lo.LoadWith<IncidentRootCause>(irc => irc.RootCause);	0
18858584	18857483	Getting default value of the default drop down list choice on Page Load	SqlDataSource1.SelectCommand = "select * from ta where name like '%'+@userParam+'%'";\nif (SqlDataSource1.SelectParameters.Count == 0)\n{\n    SqlDataSource1.SelectParameters.Add("userParam", DbType.String, nameDropDownList.SelectedItem.Value);\n}\nSqlDataSource1.SelectParameters["userParam"].DefaultValue = nameDropDownList.SelectedItem.Value ;	0
10563058	10563005	How to get from html the element of a register field by Name?	wb.Document.GetElementsByTagName("input")["passwort"]	0
15056574	15056249	How to pass dropdownlist value to another page	if (!IsPostBack)\n{\n  DropDay.Items.Clear();\n      for (int i = 1; i <= 10; i++)\n      {\n          DropDay.Items.Add(i.ToString());\n      }\n}	0
26543355	26527367	WPF XamNumericEditor binded to Slider	void NumericEditorOnGotFocus(object sender, RoutedEventArgs e)
\n{
\nvar numericEditor = sender as XamNumericEditor;
\n
\nif (numericEditor != null)
\n{
\nvar text = numericEditor.Text;
\nvar numberMatch = Regex.Match(text, @"\d");
\nif (numberMatch.Success)
\n{
\n                    numericEditor.SelectionStart = numberMatch.Index;
\n}
\n}
\n}	0
3356927	3356896	How to provide a readonly Collection that implements INotifyCollectionChanged	ReadOnlyObservableCollection<T>	0
7377430	7377390	C# removing the current item in a listbox	int index = listbox.SelectedIndex();\nlistThatHoldsObjects.RemoveAt(index); \nlistbox.ItemsSource = listThatHoldsObjects	0
13019916	13019811	Count Text in a String	string str = "Lorem ipsum is great. lorem ipsum Lorem...";\nstring word = "Lorem";\nConsole.WriteLine(Regex.Matches(str,word).Count);	0
18431952	18431598	Identity server single sign out, logout from server too	private ActionResult ShowSignOutPage(string returnUrl)\n {\n   ....\n   FederatedAuthentication.SessionAuthenticationModule.DeleteSessionTokenCookie(); //added this\n   return View("Signout", realms);\n }	0
20133304	20100504	AWS SDK migration from v1 to v2: How to implement WithSubscriber() correctly?	request.UploadProgressEvent += this.uploadFileProgressCallback;	0
22629812	22629288	Custom control - first draws OK, second doesn't	protected override void OnPaint(PaintEventArgs e)\n{\n   //...\n            Invalidate();\n}	0
12787335	12786897	Can a Message Contract Extend a Data Contract?	[MessageContract]\nclass ExtendedRequestObject\n{\n    [MessageBodyMember]  RequestObject Request;\n\n}	0
10771411	10771400	How to perform a dynamic query with Linq	test1 = test.Where(z => z.Id > 1);\n    test2 = test.Where(x => x.Name == "Admin"); //or name equals admin\n\n    test = test1.Union(test2)	0
13093141	13093059	Trouble with using Reflection	//Gets the label (includes private fields)\nFieldInfo fi = this.GetType().GetField("plabel" + count, \n                   BindingFlags.NonPublic | BindingFlags.Instance); \n\nLabel label = fi.GetValue(this) as Label;\n\nif (label != null)\n{\n    MessageBox.Show(label.Text);\n}	0
942360	942358	How to get a filename from a path?	myfilename = Path.GetFileName(mypath);	0
202646	202630	How do I detect a null reference in C#?	void DoSomething( MyClass value )\n{\n    if( value != null )\n    {\n        value.Method();\n    }\n}	0
16727478	16727390	Line break a string on x number of characters but not through a word	public static string SpliceText(string text, int lineLength)\n{\n    var charCount = 0;\n    var lines = text.Split(new string[] {" "}, StringSplitOptions.RemoveEmptyEntries)\n                    .GroupBy(w => (charCount += w.Length + 1) / lineLength)\n                    .Select(g => string.Join(" ", g));\n\n    return String.Join("\n", lines.ToArray());\n}	0
32468287	32466591	ASP.NET MVC map single controller to root of website	routes.MapRoute("MarketingPages", "{action}",\n  new { controller = "Marketing" },\n  new { action = @"About|Social" });	0
9894635	9885382	In C# change visio Shape Position	var shape = currentPage.Drop(...);\nshape.CellsU["PinX"].Formula = "2";\nshape.CellsU["PinY"].Formula = "2";	0
6434117	6434065	Center a C# Windows Form inside another window	[DllImport("user32.dll")]  \nstatic extern IntPtr GetForegroundWindow();  \n\n\nprivate IntPtr GetActiveWindow()  \n{  \n    IntPtr handle = IntPtr.Zero;  \n    return GetForegroundWindow();  \n}\n\nThen get the window position with GetWindowRect.\n\n[DllImport("user32.dll")]  \n[return: MarshalAs(UnmanagedType.Bool)]  \nstatic extern bool GetWindowRect(IntPtr hWnd, out RECT lpRect);  \n\n[StructLayout(LayoutKind.Sequential)]  \npublic struct RECT  \n{\n    public int Left;        // x position of upper-left corner  \n    public int Top;         // y position of upper-left corner  \n    public int Right;       // x position of lower-right corner  \n    public int Bottom;      // y position of lower-right corner  \n}	0
2412918	2375318	How can you calculate the X/Y coordinate to zoom to	var pointClicked = (where user clicked)\nvar myWindow = (whatever your window is);\n\nmyWindow.RenderTransform = new TransformGroup();\nvar pan = new TranslateTransform(pointClicked.X, pointClicked.Y);\nvar scale = new ScaleTransform(6.0,6.0);\nmyWindow.RenderTransform.Children.Add(pan);\nmyWindow.RenderTransform.Children.Add(scale);	0
9207867	9207683	replacing operator in Where clause Lambda with a parameter	class YourClass\n{\n     static readonly Dictionary<string, Func<DateTime, DateTime, bool>> s_filters = new Dictionary<string, Func<DateTime, DateTime, bool>>\n     {\n       {  ">", new Func<DateTime, DateTime, bool>((d1, d2) => d1  > d2) }\n       { "==", new Func<DateTime, DateTime, bool>((d1, d2) => d1 == d2) }\n       { "!=", new Func<DateTime, DateTime, bool>((d1, d2) => d1 != d2) }\n       { ">=", new Func<DateTime, DateTime, bool>((d1, d2) => d1 >= d2) }\n       { "<=", new Func<DateTime, DateTime, bool>((d1, d2) => d1 <= d2) }\n     };\n\n     public IEnumerable<Localisation> GetByFiltre(string filter, string valeurDate1)\n     {\n        ...\n\n        DateTime dt = Convert.ToDateTime(valeurDate1);\n        var filterDelegate = s_filters[filter];\n\n        var mod = from o in new GpsContext().Locals.Where(loc => filterDelegate(loc.Date,dt));\n\n        ...\n     }\n}	0
14192525	14192363	How do I use a variable within a control name? (C#)	for (int i = 0; i < 7; i++)\n{\n    if (checkBoxes[i].Checked == false)\n    {\n        labels[i].Text = rng.Next(1, 7).ToString();\n    }\n}	0
33974140	33974044	Counting Sort Implementation in C#	for (i = n - 1; i >= 0; i--)\n                {\n                    anothersmallestvalue = x;\n                    for (j = 0; j <= lengthof_B ; j++)        \n                    {\n\n                        if (a[i] == anothersmallestvalue)\n                        {\n                            temp = b[j];\n                            c[temp - 1] = anothersmallestvalue;\n                            b[j] = b[j] -1 ;// Possible Mistake I think here\n                        }\n                        anothersmallestvalue++;\n                    }\n                }	0
5948304	5936998	C# translator with babel fish translator	string fromCulture = from.Name;\n            string toCulture = to.Name;\n            string translationMode = string.Concat(fromCulture, "_", toCulture);\n\n            string url = String.Format("http://babelfish.yahoo.com/translate_txt?lp={0}&tt=urltext&intl=1&doit=done&urltext={1}", translationMode, HttpUtility.UrlEncode(resource));\n            WebClient webClient = new WebClient();\n            webClient.Encoding = System.Text.Encoding.Default;\n            string page = webClient.DownloadString(url);\n\n            int start = page.IndexOf("<div style=\"padding:0.6em;\">") + "<div style=\"padding:0.6em;\">".Length;\n            int finish = page.IndexOf("</div>", start);\n            string retVal = page.Substring(start, finish - start);	0
2068791	2066418	How do I update a table with LINQ-to-SQL without having to delete all the existing records?	var existingUsers = from u in db.MailListUsers\n                    select u;\n\nvar deletedUsers = from u in existingUsers\n                   where !userIDs.Contains(u.UserID)\n                   select u;\n\nvar newUsers = from n in userIDs\n               let ids = from u in existingUsers\n                         select u.UserID\n               where !ids.Contains(n)\n               select new MailListUser {\n                    UserID = n\n               };\n\ndb.MailListUsers.DeleteAllOnSubmit(deletedUsers);\ndb.MailListUsers.InsertAllOnSubmit(newUsers);\ndb.SubmitChanges();	0
6206229	6200070	How to generate 3 node treeview in winforms with mysql?	treeView1.Nodes[1].Node[0]	0
8831368	8831241	Is there a way to combine two LINQ queries into one?	var groups = \n    from r in dbRecipes\n    orderby r.DisplayOrder\n    group r by r.Group into g\n    orderby g.Key.GroupOrder\n    select g;\n\nforeach (var g in groups) \n{ \n   output.Write("{0}<br/>", g.Key.GroupName); \n\n   foreach(var r in g) \n   { \n      output.Write("---{0}<br/>", r.Recipe.Title); \n   } \n}	0
10501456	10501403	PartialView form validation then calling a controller method in MVC3	[HttpPost]\npublic ActionResult Create(ForumPost model)\n{\n    if (!ModelState.IsValid)\n    {\n        // validation failed => redisplay the view so that the user can fix the errors\n        return View(model);\n    }\n\n    // at this stage the model is valid => process it:\n    service.CreateForumPost(model);\n\n    return ...\n}	0
4340962	4340941	How create a serializable C# class from XML file	xsd myFile.xml\nxsd myFile.xsd	0
10882794	10880232	How to get the text-area content as exactly user entered	text.Replace(Environment.NewLine, "<br />");	0
2972169	2972103	How to convert a String to a Hex Byte Array?	static class HexStringConverter\n{\n    public static byte[] ToByteArray(String HexString)\n    {\n        int NumberChars = HexString.Length;\n        byte[] bytes = new byte[NumberChars / 2];\n        for (int i = 0; i < NumberChars; i += 2)\n        {\n            bytes[i / 2] = Convert.ToByte(HexString.Substring(i, 2), 16);\n        }\n        return bytes;\n    }\n}	0
26063511	26062729	How can I submit form fields from iOS to a UIWebView using Xamarin?	string password = "1234";\nvar req = new NSMutableUrlRequest (new NSUrl ("http://example.com"));\nreq.HttpMethod = "POST";\nreq.Body = NSData.FromString(String.Format("passwd={0}", password));\nreq["Content-Length"] = req.Body.Length.ToString();\nreq["Content-Type"] = "application/x-www-form-urlencoded charset=utf-8";\nmyWebView.LoadRequest (req);	0
20460644	20460500	How to Cast Application Bar Color to a Theme Resource Color	ApplicationBar.ForegroundColor = (Application.Current.Resources["PhoneChromeBrush"] as SolidColorBrush).Color;	0
18369932	18369919	How do I hide the console window in my program?	/target:winexe	0
15380771	15380672	Remove an item based on its content	foreach (var item in combo.Items)\n{\n    if (item.Name == contentToRemove) // Check item.Name or something similar property.\n        combo.Items.Remove(item);\n}	0
7368565	7368559	List<T> without Where in the intellisense	using System.Linq;	0
20378424	20378312	Converting bitshifted numbers back to their original index	uint v;\nuint c = 32;\nv &= (0-v);\nif (v != 0) c--;\nif ((v & 0x0000FFFF) != 0) c -= 16;\nif ((v & 0x00FF00FF) != 0) c -= 8;\nif ((v & 0x0F0F0F0F) != 0) c -= 4;\nif ((v & 0x33333333) != 0) c -= 2;\nif ((v & 0x55555555) != 0) c -= 1;	0
20557877	20557678	WPF Animation on Grid Height	grid1.BeginAnimation(Rectangle.HeightProperty, null);	0
6282174	6282156	Load a gridview with a list?	yourgrid.DataSource=SubmissionsList;\nyourgrid.DataBind();	0
6311044	6310967	How do you read data from an ObservableCollection in C#	string test1 = DataCollection.ElementAt(0).Facility;\n        string test2 = DataCollection.ElementAt(0).Key;	0
33084515	33084104	Add a right click event to a tab in a TabControl container	private void tabControl1_MouseUp(object sender, MouseEventArgs e)\n{\n    if (e.Button == MouseButtons.Right)\n    {\n        Application.Exit();\n    }\n    else\n    {\n\n    }\n}	0
12218356	12218321	C# datetimepicker reading values before changing date	public class MyClass\n{\n\n    DateTime? LastDateValue = null;\n\n    void OnLoad()\n    {\n       //Set both datepicker and LastDateValue to be the same\n    }\n\n    void DateTimePicker_valueChanged()\n    {\n       //use LastDateValue to save text fields\n       //set LastDateValue to match new value ready to use on next event fire\n    }\n\n}	0
34040783	34040712	Difference in Double & double	System.Double	0
10052653	10052380	C# function that takes pointer to function as an in parameter without declaring any specific delegate types?	public void TestInvokeDelegate()\n{\n    InvokeDelegate( new TestDelegate(ShowMessage), "hello" );\n}\n\npublic void InvokeDelegate(TestDelegate del, string message)\n{\n    del(message);\n}\n\npublic delegate void TestDelegate(string message);\n\npublic void ShowMessage(string message)\n{\n    Debug.WriteLine(message);\n}	0
23462122	23461998	How to save the value of the variable after closing the form	public FoodFormResult ShowForm()\n    {\n        return new FoodFormResult(\n            ShowDialog() == DialogResult.OK, \n            _indicators);\n    }	0
32200078	32199908	C# search for specific string with specific length	[^\d](\d{13})[^\d]	0
14634625	14593696	.NET Modifying Class Library Application Settings from Host Application	String cfgFileName = "IntercompanyConsoleApp.exe.config";\n        ExeConfigurationFileMap cfgMap = new ExeConfigurationFileMap();\n        cfgMap.ExeConfigFilename = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) + "\\" + cfgFileName;\n\n        Configuration cfg = ConfigurationManager.OpenMappedExeConfiguration(cfgMap, ConfigurationUserLevel.None);\n\n        // IntercompanyService is the name of my service app, which is where the real app.config file resides -- hence the entries in the xml are based on this application.\n        // Also, the scope of my settings entries is Application\n        ClientSettingsSection section = (ClientSettingsSection)cfg.GetSection("applicationSettings/IntercompanyService.Properties.Settings"); \n\n        Console.WriteLine(section.Settings.Get("Server").Value.ValueXml.InnerText);\n        Console.WriteLine(section.Settings.Get("Database").Value.ValueXml.InnerText);	0
18146081	18038867	how to get js POST in asp.net webform?	protected void Page_Load(object sender, EventArgs e)\n{\n    if (IsPostBack)\n    {\n        StripeConfiguration.SetApiKey("[API Secret Key");\n        NameValueCollection nvc = Request.Form;\n        string amount = nvc["amount"];\n        var centsArray = amount.Split('.');\n        int dollarsInCents = Convert.ToInt32(centsArray[0]) * 100;\n        int remainingCents = Convert.ToInt32(centsArray[1]);\n        string tokenId = nvc["stripeToken"];\n\n        var tokenService = new StripeTokenService();\n        StripeToken stripeToken = tokenService.Get(tokenId);\n\n\n        var myCharge = new StripeChargeCreateOptions\n        {\n            TokenId = tokenId, \n            AmountInCents = dollarsInCents + remainingCents,\n            Currency = "usd"\n        };\n        var chargeService = new StripeChargeService();\n        StripeCharge stripeCharge = chargeService.Create(myCharge);\n    }\n}	0
13921656	13270497	Creating a custom pop up for Umbraco back office	document.copy()	0
20765665	20765589	Finding duplicate integers in an array and display how many times they occurred	static void Main(string[] args)\n{              \n    int[] array = { 10, 5, 10, 2, 2, 3, 4, 5, 5, 6, 7, 8, 9, 11, 12, 12 };\n    var dict = new Dictionary<int, int>();\n\n    foreach(var value in array)\n    {\n        if (dict.ContainsKey(value))\n            dict[value]++;\n        else\n            dict[value] = 1;\n    }\n\n    foreach(var pair in dict)\n        Console.WriteLine("Value {0} occurred {1} times.", pair.Key, pair.Value);\n    Console.ReadKey();\n}	0
33828649	33828090	MySQL insert based on datetime	try\n                {\n                    comm.ExecuteNonQuery();\n\n                }\n                catch(MySql.Data.MySqlClient.MySqlException mySqlEx)\n                {\n                    Console.WriteLine("Duplicate entry found");\n                }	0
11528189	11528122	Escape Character for SQL in C#	string strOrdersOrigSQL = "SELECT LastName FROM Employees";\n// Concatenate the default SQL statement with the "Where" clause and add an OrderBy clause\n       strOrdersSQL = strOrdersOrigSQL + " where FirstName ='"+ strFname + "'";	0
22055824	22055042	Function to locate a string in a text	using System;\nusing System.Net;\nusing System.Text.RegularExpressions;\nusing System.Collections.Generic;\n\nclass Program\n{\n    static void Main()\n    {\n        var map = new Map();\n        Console.WriteLine(map[300000011]);\n    }\n}\n\npublic class Map: Dictionary<int, string>\n{\n    public Map()\n    {\n        WebClient wc = new WebClient()\n        {\n            Proxy = null\n        };\n\n        string rawData = wc.DownloadString("<insert url with data in new format here>");\n        PopulateWith(rawData);\n    }\n\n    void PopulateWith(string rawText)\n    {\n        string pattern = @"ID: (?<id>\d*) NAME: (?<name>.*)";\n\n        foreach (Match match in Regex.Matches(rawText, pattern)) \n        {\n            // TODO: add error handling here\n            int id = int.Parse( match.Groups["id"].Value );\n            string name = match.Groups["name"].Value;\n\n            this[id] = name;\n        }\n    }    \n}	0
14291813	14291769	How to cast ComObject to ENVDTE.Project?	if (projObj is Project)\n        {\n            Project selectedProject = (Project)projObj;\n            MessageBox.Show(selectedProject.FullName);\n        }\n        else if(projObj is ProjectItem)\n        {\n            ProjectItem selectedProject = (ProjectItem)projObj;\n            MessageBox.Show(selectedProject.get_FileNames(1));\n        }	0
20053839	20052827	How to conditionally filter IQueryable by type using generic repository pattern	private static readonly PropertyInfo _organizationIdProperty \n    = typeof(OrganisationDependent).GetProperty("OrganisationID");\n\nprivate static Expression<Func<T, bool>> FilterByOrganization<T>(int organizationId)\n{\n    var item = Expression.Parameter(typeof(T), "item");\n    var propertyValue = Expression.Property(item, _organizationIdProperty);\n    var body = Expression.Equal(propertyValue, Expression.Constant(organizationId));\n    return Expression.Lambda<Func<T, bool>>(body, item);\n}\n\npublic virtual IQueryable<T> All\n{\n    get\n    {\n        IQueryable<T> set = Context.Set<T>();\n        if (typeof(T).IsSubclassOf(typeof(OrganisationDependent)))\n        {\n            var filter = FilterByOrganization<T>(CurrentOrganisationID);\n            set = set.Where(filter);\n        }\n\n        return set;\n    }\n}	0
17143552	17143179	Disable browser specific hotkeys for Silverlight application	CTRL+SHIFT+S	0
32806041	32805855	Regex match up to the end of a standard pattern	string input = "TV.Show.S01E01.1080p.BluRay.x264-ROVERS";\n            string pattern = @"(?'pattern'^.*\d\d[A-Z]\d\d)";\n            string results = Regex.Match(input, pattern).Groups["pattern"].Value;	0
21895226	21895214	Format dd/MM/yyy hh:mm:ss in a datapicker c#	cmd1S.CommandText = "UPDATE AC SET date = @p1 WHERE NTIVO = @p2 AND NUMA = @p3 AND NUIPO=@p4 AND SUACT=@p5";\nvar p1 = cmd1S.CreateParameter();\np1.Name = "p1";\np1.Value =  DateTime.ParseExact(datep.Value, "dd/MM/yyyy hh:mm:ss", CultureInfo.InvariantCulture)\ncmd1S.Parameters.Add(p1);\n//other parameters\ncmd1S.Connection = conn;\ncmd1S.ExecuteNonQuery();	0
7744933	7744842	Linq doesn't provide a byte[] data type fo storing files	myPDFFile.Content = new BinaryReader(hpf.InputStream).ReadBytes(hpf.InputStream.Length)	0
5996394	5996359	Putting \" in verbatim string with C#	string templateString = @"\n        {0}\n        ""{1}""\n        {2}\n        ";	0
18167161	18165993	how to click json hyperlink on page using javascript	signupWebView.InvokeScript("eval", new string[] { "document.getElementsByClassName('user-signup ctools-bp-modal')[0].click();" });	0
3434888	3434798	converting object to byte[]	static void Main(string[] args)\n{\n    using (var stream = new MemoryStream())\n    {\n        // serialize object \n        var formatter = new BinaryFormatter();\n        var foo = new Foo();\n        formatter.Serialize(stream, foo);\n\n            // get a byte array\n            // (thanks to Matt for more concise syntax)\n            var bytes = stream.GetBuffer(); \n\n        // deserialize object\n        var foo2 = (Foo) formatter.Deserialize(stream);\n    }\n}\n\n[Serializable]\nclass Foo:ISerializable\n{\n    public string data;\n\n    #region ISerializable Members\n\n    public void GetObjectData(SerializationInfo info, StreamingContext context)\n    {\n        info.AddValue("data",data);\n    }\n\n    #endregion\n}	0
4421398	4421381	How to rotate Text in GDI+?	String theString = "45 Degree Rotated Text";\nSizeF sz = e.Graphics.VisibleClipBounds.Size;\n//Offset the coordinate system so that point (0, 0) is at the\ncenter of the desired area.\ne.Graphics.TranslateTransform(sz.Width / 2, sz.Height / 2);\n//Rotate the Graphics object.\ne.Graphics.RotateTransform(45);\nsz = e.Graphics.MeasureString(theString, this.Font);\n//Offset the Drawstring method so that the center of the string matches the center.\ne.Graphics.DrawString(theString, this.Font, Brushes.Black, -(sz.Width/2), -(sz.Height/2));\n//Reset the graphics object Transformations.\ne.Graphics.ResetTransform();	0
12421564	12421305	C# / Sqlite simple way to store query result as variable	public string QueryResult(string query)\n        {\n              SQLiteDataAdapter ad;\n              string result = "";\n              SQLiteConnection sqlite = new SQLiteConnection("Data Source=/path/to/file.db");\n              try\n              {\n                    SQLiteCommand cmd = new  SQLiteCommand();\n                    sqlite.Open();  //Initiate connection to the db\n                    cmd = sqlite.CreateCommand();\n                    cmd.CommandText = query;  //set the passed query\n                    result = cmd.ExecuteScalar().Tostring();\n              }\n              catch(SQLiteException ex)\n              {\n                    //Add your exception code here.\n              }\n              sqlite.Close();\n              return dt;\n  }	0
1894663	1894646	Need generic utility C# method for populating ASP.NET DropDownList	public void FillCombo<TSource>(DropDownList ddl, TSource dataSource, string textField, string valueField, bool addSelect) {\n\n    ddl.DataValueField = valueField;\n    ddl.DataTextField = textField;\n    ddl.DataSource = dataSource;\n    ddl.DataBind();\n\n    if (addSelect) AddSelectCombo(ddl, "Select", -1);\n\n}	0
30267741	30267670	parse strange JSON response as List<string>	var result = JsonConvert.DeserializeObject<Dictionary<Guid, bool>>(json);\nvar resultlist = result.Select(c => c.Key).ToList();	0
3831917	3831886	Pass Interface into function for use with Create<T>	public object GetProxy<T>()\n{\n    return XmlRpcProxyGen.Create<T>();\n}	0
33495651	33495535	Not able to save more than 43679 char in text datatype column in SQL Server	varchar(max)	0
15674041	13889682	show MDI child from splitcontainer panel	frmMasterlistAdministrationAdd frmMasterlistAdministrationAdd = new frmMasterlistAdministrationAdd();\n    frmMasterlistAdministrationAdd.TopLevel = false;\n    frmMain frmMain = new frmMain();\n    frmMasterlistAdministrationAdd.Parent = frmMain;\n    splitContainer3.Panel2.Controles.add(frmMasterlistAdministrationAdd);\n    frmMasterlistAdministrationAdd.Show();	0
9412515	9412459	Unable to access table fields using range variable in LINQ to SQL	public static void DeleteCategory(int id)\n{\n    var result = from a in adb.Artifacts\n                 where a.CatgId == id\n                 group a by a.ArtId into g\n                 select new { count = g.Count(), artid = g.Key }; //not able to get ArtId using range variable a.\n\n    if (result.count > 0)\n    {\n        foreach (var r in result)\n        {\n            MyArtifact.DeleteByKey(r.artid);\n        }\n    }\n}	0
2538109	2525791	How to see if a user is following you on Twitter using C# Twitter API wrapper Tweetsharp	var twitter = FluentTwitter.CreateRequest()\n                .AuthenticateAs(_username, _password)\n                .Friendships()\n                .Verify(_username).IsFriendsWith(_userNameToCheck)\n                .AsJson();	0
28793820	28793583	C# Error Finding Item in ListView	if(listView.Items.Cast<ListViewItem>().Any(c => c.Content.ToString().Contains(txtSearch.Text)))\n{\n    // You have a match\n}	0
25098025	25092646	Is there a compact way to define multiple params for a Sql Query from C# code	SqlParameter[] parameterList = new SqlParameter[]\n{\n    new SqlParameter("@CreatedBy", Int32.Parse(User.Identity.GetUserId())),\n    new SqlParameter("@CreatedDate", DateTime.UtcNow),\n    new SqlParameter("@TestId", testId),\n    new SqlParameter("@TestStatusId", 3)\n};	0
11231991	11142702	AspNet WebApi POST parameter is null when sending XML	var xml = GlobalConfiguration.Configuration.Formatters.XmlFormatter;\nxml.UseXmlSerializer = true;	0
22779119	22778752	change the font size in screens	//set fonts           \nthis.Font = Settings.Default.appFont;	0
19779208	19778625	Change the text colour of every row where a cell's value is 0?	public TransparentDataGridView()\n    {\n        this.SelectionChanged += TransparentDataGridView_SelectionChanged;\n    }\n\n    void TransparentDataGridView_SelectionChanged(object sender, EventArgs e)\n    {\n        ClearSelection();\n    }	0
21131824	21131537	delete row in gridview	GridViewRow gvRow = (GridViewRow)((Button)sender).Parent.Parent;\nint ID = Convert.ToInt32(grdView.DataKeys[gvRow.RowIndex]["ID"]);\n\nDataTable grdContent = (DataTable)ViewState["grdContent"];\n\nforeach (DataRow dr in grdContent.Rows)\n{\n    if (dr["ID"].ToString() == ID.ToString())\n    {\n        grdContent.Rows.Remove(dr);\n        grdContent.AcceptChanges();\n        break;\n    }\n}\n\ngrdView.DataSource = grdContent;\ngrdView.DataBind();	0
26628556	24960759	POCO Controllers in MVC 6	public class HomeController\n{\n    // Use the ActivateAttribute to inject services into your controller\n    [Activate]\n    public ViewDataDictionary ViewData { get; set; }\n\n    public ActionResult Index()\n    {\n        return new ViewResult() { ViewData = ViewData };\n    }\n}	0
1734014	1734009	asp.net cookie from a resource project (+ a general info)	System.Web.HttpContext.Current	0
34227287	34227161	How do i match something based on the number of strings?	// Match a Regex and Do Stuff\n        public void showMatch(string input, string expr)\n        {\n            MatchCollection mc = Regex.Matches(input, expr); \n            int num = 0;  \n            foreach (Match m in mc)\n            {\n                string tm = m.ToString();\n                num++;\n                if (num == 1)\n                {\n                    // Do Stuff if 1 match.\n                }\n                if (num == 2)\n                {\n                    // Do Stuff if 2 matches.\n                }\n            }\n       }\n\n\n            // showMatch(input, @"(?:[0-9]+){17}");	0
3588121	3588067	XPath syntax to extract URL from HTMLNode using HTMLAgilityPack?	//a[@id='123']/@href	0
18776564	18776200	How to Authenticate user in ASP.NET	FormsAuthentication.RedirectFromLoginPage(userName,yourRememberMeCheckBox.Checked);	0
1742135	1742078	log4net Configuration for console app	static class Log4NetHelper\n{\n    private static bool _isConfigured;\n\n    static void EnsureConfigured()\n    {\n        if (!_isConfigured)\n        {\n            ... configure log4net here ...\n            _isConfigured = true;\n        }\n    }\n\n    public static ILog GetLogger(string name)\n    {\n        EnsureConfigured();\n        log4net.ILog logger = log4net.LogManager.GetLogger(name);\n        return logger;\n    }\n}	0
6913231	6913153	C# Extracting String From ListView	string item = listView1.Items[i].Text	0
30027983	30027876	Run an exe with command-line parameters	var query = Path.Combine(path, calculator.ExeName + ".exe");\n    var p = new Process();\n    p.StartInfo.FileName = query;\n    p.StartInfo.WorkingDirectory = path;\n    //the command line parameter that causes the exe to start in an invisible mode\n    p.StartInfo.Arguments = "episrc"\n    p.Start();	0
5960476	5949687	Find all action methods that have been decorated with [OutputCache] and remove	public ActionResult Invalidate()\n{\n    OutputCacheAttribute.ChildActionCache = new MemoryCache("NewDefault");\n    return View();\n}	0
33750595	33750229	How to get the list of all the databases in an Azure DocumentDB account?	using (var documentClient = new DocumentClient(new Uri("<endpoint>"), "<accountkey>"))\n            {\n                var listDatabasesOperationResult = await documentClient.ReadDatabaseFeedAsync();\n                foreach (var item in listDatabasesOperationResult)\n                {\n                    Console.WriteLine(item.Id);\n                }\n            }	0
545585	515360	DependancyProperty attach to a property of a property	Activity=BusinessProcess, Path=userAccount.Name	0
27009638	26977130	Cannot ungroup a PowerPoint SmartArt Shape	osh.Copy\nosh.Delete\nSet osh = ActiveWindow.Selection.SlideRange(1).Shapes.PasteSpecial(ppPasteEnhancedMetafile)(1)\nWith osh.Ungroup\n    .Ungroup\nEnd With	0
12473922	9110397	Get original request url in WCF REST service	System.ServiceModel.Web.WebOperationContext.Current.IncomingRequest.UriTemplateMatch.RequestUri.OriginalString;	0
1463691	1463664	Is there any way to jump to the last line of a file in C#?	public string GetLastLine(Stream stream, Encoding enc) {\n  const int64 range = 100;\n  var found = false;\n  var index = stream.Length;\n  var data = new byte[range];\n  var builder = new StringBuilder();\n  while ( true ) { \n    index = Math.Max(0, index -= range); \n    var count = stream.Read(data, 0, data.Length);\n    if ( count == 0 ) {\n      break;\n    }\n    var text = enc.GetString(data, 0, count);\n    var newLineIndex = text.Index(Environment.NewLine);\n    if ( newLineIndex >= 0 ) {\n      builder.Insert(text.SubString(newLineIndex+Environment.NewLine.Length),0);\n      break; \n    } else { \n      builder.Insert(text, 0);\n    }\n  }\n  return builder.ToString();\n}	0
19554726	19439873	Can't get PrincipalContext to work in SharePoint 2010 with Claims Based Authentication	private string GetADName(string userID)\n    {\n        try\n        {\n            using (HostingEnvironment.Impersonate())\n            {\n\n                PrincipalContext ctx = new PrincipalContext(ContextType.Domain);\n\n                UserPrincipal qbeUser = new UserPrincipal(ctx);\n\n                qbeUser.SamAccountName = userID.ToLower();\n\n                PrincipalSearcher srch = new PrincipalSearcher(qbeUser);\n\n                foreach (var found in srch.FindAll())\n                {\n                    if (found.SamAccountName.ToLower() == userID.ToLower())\n                    {\n                        return found.Name;\n                    }\n                }\n            }\n        }\n        catch (Exception ex)\n        {\n        }\n        return "";\n    }	0
11760570	11760423	Using C# lambas to combine List<int> and int	listOfPairs.Select(p => new []{ p.First }.Concat(p.Second).ToList()).ToList()	0
25901144	25880318	Format of Javascript Object of Arrays to save as C# dictionary for WCF	[ \n  { Key: "foo" , Value: ["abc", "def", "ghi"]},\n  { Key: "foo2", Value: ["123", "456", "789"]}, \n]	0
7412925	7412770	Obligatory DateTime issues with C# - Determine if UtcNow is between given time span only	DateTime dt3 = DateTime.UtcNow;\nif(dt3.Hour <= 6 || dt3.Hour >=18)//24 hr format\n   MessageBox.Show("6PM - 6AM range");// UTC will have only one time and should get satisfied irrespective of date	0
12973388	12972915	Setting up resources in separate dll WPF	Source="pack://application:,,,/GX3StyleResources;component/GX3StyleResources.xaml"	0
19312710	19312059	Stopping a Specific Thread and Starting It Up Again From Windows Service	public class AccountListener\n{\n    private Thread _worker = null;\n    private MobileAccount _mobileAccount;\n    public AccountListener(MobileAccount mobileAccount)\n    {\n        _mobileAccount = mobileAccount;\n    }\n\n    protected void Listen()\n    {\n        try\n        {\n            DoWork();\n        }\n        catch (Exception exc)\n        {\n        }\n    }\n\n    protected virtual void DoWork()\n    {\n        Console.WriteLine(_mobileAccount);\n    }\n\n    public void Start()\n    {\n        if (_worker == null)\n        {\n            _worker = new Thread(Listen);\n        }\n        _worker.Start();\n    }\n\n    public void Stop()\n    {\n        try\n        {\n            _worker.Abort();\n        }\n        catch (Exception)\n        {\n            //thrad abort exception\n        }\n        finally\n        {\n            _worker = null;\n        }\n    }\n}	0
8495844	8495642	How to insert a row using a IDbDataAdapter(SqlDataAdapter or OleDbDataAdapter) without loading the entire table?	OleDbDataAdapter da = new OleDbDataAdapter("SELECT * FROM Nodes", _cnAq9);\nDataTable dt = new DataTable();\nda.FillSchema(dt, SchemaType.Source);\n\nDataRow dr = dt.NewRow();\ndr["nID"] = nNodeID;\ndr["csNumber"] = strNumber;\ndt.Rows.Add(dr);\nda.Update(dt);	0
11929653	11929595	URI Update Request	var uri = new Uri("http://somesite.com/something");\nvar request = WebRequest.Create(uri) as HttpWebRequest;\nrequest.Credentials = new NetworkCredential("myUserName","myPassword");\nrequest.PreAuthenticate = true;	0
27715125	27714870	How to don't make screen blink when use Response.Write	Response.Write("<script>setTimeout(alert(\'Error.Please check your ID\');history.back();', 200)</script>");	0
11102150	11102139	Hide my application from taskbar	Me.ShowInTaskbar = False	0
25299241	25276516	Linear interpolation for dummies	float interpolate(float p1, float p2, float fraction) { return p1 + (p2 - p1) * fraction; }	0
15757749	15757181	Regular expressions for reading sms from device	Regex r = new Regex(@"\+CMGL: (\d*),""(.+)"",""(.+)"",(.*),""(.+)""\r\n((.|\r|\n)+)\r\n");	0
33898522	33898318	Asynchronous Where Filter with Linq	EventsDates = await YourWebServiceMethodCall();\nList<DateTime> dates = EventsDates.Where (x => x.Day == tmp.Day && x.Month == tmp.Month && x.Year == tmp.Year).ToList();	0
31264213	31263260	Equivalent of outer join with non-equals predicate in Linq	from t0 in MyTable\nFrom t1 in MyTable( x=>x.Fk_CompanyId=t0.Fk_CompanyId && x.CheckedUtc > t0.CheckedUtc ).DefaultIfEmpty()\nwhere t1.Fk_CompanyId == null && t0.CheckedUtc != null \nselect new { cid = t0.Fk_CompanyId, cuct = t0.CheckedUtc, isbl = t0.IsBlocking }	0
9506857	9506829	Get a float of seconds since minimum in C#	TimeSpan t = (DateTime.UtcNow - \n               new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc));\n float seconds  = (float) t.TotalSeconds;\n Console.WriteLine (seconds);	0
11003405	11003314	Creating a dynamic variable	foreach (DataRow dRow in dTable.Rows)\n  {\n      service1.SDataRow row1 = new service1.SDataRow();	0
25861050	25861016	50% chance to make a boolean true or not by clicking a button?	bool yourBool= false;\nRandom rand = new Random();\n\nif (rand.Next(0, 2) != 0)\n{\n    yourBool = true;\n}	0
25956783	25956096	How to get the Customer id of each by json data returned from server	function func() {\n        var JsonData = [\n      {\n          "CustomerID": "100",\n          "ContactName": "Indocin",\n          "City": "David"\n      },\n      {\n          "CustomerID": "200",\n          "ContactName": "Enebrel",\n          "City": "Sam"\n      },\n      {\n          "CustomerID": "300",\n          "ContactName": "Hydralazine",\n          "City": "Dhaka"\n      }\n    ];\n       GetCustomerID(JsonData);\n    }\n    function GetCustomerID(JsonData) {\n        alert(JsonData);\n        var custIDArray = new Array(JsonData.length);\n        for (var i = 0; i < JsonData.length; i++) {\n            custIDArray[i] = JsonData[i]["CustomerID"];        \n        }\n        return custIDArray;\n    }	0
744899	744774	Resetting properties from a property grid	private void resetToolStripMenuItem_Click(object sender, EventArgs e)\n{                        \n    PropertyDescriptor pd = propGrid.SelectedGridItem.PropertyDescriptor;\n    pd.ResetValue(propGrid.SelectedObject);\n}	0
3565824	3565796	Periodically shut down a program	foreach (var process in Process.GetProcessesByName("kol"))\n{\n    process.Kill();\n}	0
15412990	15411445	How to add a HtmlPrefix to Views Using MVC Actions?	public ActionResult AddDetail(string Key)\n{\n    ViewData.TemplateInfo.HtmlFieldPrefix = string.Format("{0}", key)\n    return View(key);\n}	0
13387724	13386698	Disable save button when validation fails	partial class Player : IDataErrorInfo\n{\n    private delegate string Validation(string value);\n    private Dictionary<string, Validation> columnValidations;\n    public List<string> Errors;\n\n    public Player()\n    {\n        columnValidations = new Dictionary<string, Validation>();\n        columnValidations["Firstname"] = delegate (string value) {\n            return String.IsNullOrWhiteSpace(Firstname) ? "Geef een voornaam in" : null;\n        }; // Add the others...\n\n        errors = new List<string>();\n    }\n\n    public bool CanSave { get { return Errors.Count == 0; } }\n\n    public string this[string columnName]\n    {\n        get { return this.GetProperty(columnName); } \n\n        set\n        { \n            var error = columnValidations[columnName](value);\n\n            if (String.IsNullOrWhiteSpace(error))\n                errors.Add(error);\n            else\n                this.SetProperty(columnName, value);\n        }\n    }\n}	0
10927632	10927523	Text box only allow IP address in windows application	public bool IsValidIP(string addr)\n    {\n        //create our match pattern\n        string pattern = @"^([1-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])(\.\n([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])){3}$";\n        //create our Regular Expression object\n        Regex check = new Regex(pattern);\n        //boolean variable to hold the status\n        bool valid = false;\n        //check to make sure an ip address was provided\n        if (addr == "")\n        {\n            //no address provided so return false\n            valid = false;\n        }\n        else\n        {\n            //address provided so use the IsMatch Method\n            //of the Regular Expression object\n            valid = check.IsMatch(addr, 0);\n        }\n        //return the results\n        return valid;\n    }	0
25031773	25030961	Selecting a HTML node based on text containing space	"//td[starts-with( normalize-space(), 'Yellow\u00A0Fees')]"	0
2722363	2718748	XNA C# getting 12 trangle faces of a cube , given (MIN,MAX) of BoundingBox	static float a , b , h ;\n\n        static Vector3 MinV = new Vector3(0f, 0f, 0f);\n        static Vector3 MaxV = new Vector3(a, b, h);\n\n        Vector3 topLeftBack = new Vector3(MinV.X, MaxV.Y, MinV.Z);\n        Vector3 topRightBack = new Vector3(MaxV.X, MaxV.Y, MinV.Z);\n        Vector3 bottomLeftBack = new Vector3(MinV.X, MinV.Y, MinV.Z); //min\n        Vector3 bottomRightBack = new Vector3(MaxV.X, MinV.Y, MinV.Z);\n\n        Vector3 topLeftFront = new Vector3(MinV.X, MaxV.Y, MaxV.Z);\n        Vector3 topRightFront = new Vector3(MaxV.X, MaxV.Y, MaxV.Z);  //max  \n        Vector3 bottomLeftFront = new Vector3(MinV.X, MinV.Y, MaxV.Z);\n        Vector3 bottomRightFront = new Vector3(MaxV.X, MinV.Y, MaxV.Z);	0
19697136	19697028	C# Updating a dropdown box with value from another dropdown box	protected void update_SelectedItem(object sender, EventArgs e)\n{\n    lbAuthorList.Items.Clear();\n    lbAuthorList.Items.Add(new ListItem(DropDownList1.SelectedItem.Text, DropDownList1.SelectedItem.Text));\n    lbAuthorList.Items.FindByValue(DropDownList1.SelectedItem.Text).Selected = true;\n}	0
1511085	1511077	Read from Array in C#	foreach (string cat in cats) {\n    Console.WriteLine(cat);\n}	0
9208172	9208117	Get name of project from where dll is referenced via code	public void MyMethod()\n{\n    // I need name of caller project, but how?\n}\n\npublic void MyMethod(String callerProject)\n{\n    // People who call this method know the name of their own project :)\n}	0
27176924	27170410	Using C# remove unnecessary ?TABLE_NAME? from Excel worksheets	static string[] GetExcelSheetNames(string connectionString)\n    {\n        OleDbConnection con = null;\n        DataTable dt = null;\n\n        con = new OleDbConnection(connectionString);\n        con.Open();\n\n        dt = con.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);\n\n        if ((dt == null))\n        {\n            return null;\n        }\n\n        String[] excelSheetNames = new String[dt.Rows.Count];\n\n        var rowsToRemove = new List<DataRow>();\n        for (int i = 0; i < dt.Rows.Count; i++)\n        {\n            var row = dt.Rows[i];\n            excelSheetNames[i] = row["TABLE_NAME"].ToString();\n\n            if ((excelSheetNames[i].Contains("_xlnm#Print_Titles") || (excelSheetNames[i].Contains("Print_Titles"))))\n            {\n                   rowsToRemove.Add(dt.Rows[i]);\n            }\n\n            i++;\n        }\n\n        foreach (var dataRow in rowsToRemove)\n        {\n            dt.Rows.Remove(dataRow);\n        }\n\n        return excelSheetNames;\n    }	0
26243208	26240362	Problems with Sending message to MSMQ	MessageQueue  msMq = new MessageQueue(MQPath);\nmsmq.Send(sb.tostring());\n\nMessage[] msgs = msMq.GetAllMessages();\n\nforeach (var msg in msgs)\n      {\n            System.IO.StreamReader reader = new System.IO.StreamReader(msg.BodyStream);\n            MSGtext = reader.ReadToEnd();\n\n            string MSGValue = (string)XmlDeserializeFromString(MSGtext);\n\n        }\n }\n public object XmlDeserializeFromString(string objectData)\n    {\n        var serializer = new XmlSerializer(typeof(string));\n        object result;\n\n        using (TextReader reader = new StringReader(objectData))\n        {\n            result = serializer.Deserialize(reader);\n        }\n        return result;\n    }	0
4616980	4616642	Team Foundations Version Control - VersionControlServer - Get a list of folders and files from path?	var allItems = sc.GetItems("$/TeamProject/release/*");\nvar folders = allItems.Items.Where(t => t.ItemType == ItemType.Folder);\n\nvar folderPaths = folders.Select(f => f.ServerItem);	0
3645165	3645120	c# : How to Monitor Print job Using winspool_drv	PrintDialog pd = new PrintDialog();\npd.ShowDialog();\nPrintDoc.PrinterSettings = pd.PrinterSettings;\nPrintDoc.PrintPage += new PrintPageEventHandler(PrintDoc_PrintPage);\nPrintDoc.Print();\n\nobject status = Convert.ToUInt32(9999);\nwhile ((uint)status != 0) // 0 being idle\n{\n    ManagementObjectSearcher mos = new ManagementObjectSearcher("select * from Win32_Printer where Name='" + pd.PrinterSettings.PrinterName + "'");\n    foreach (ManagementObject service in mos.Get())\n    {\n    status = service.Properties["PrinterState"].Value;\n    Thread.Sleep(50);\n    }\n}	0
2220558	2220465	How can I bypass the execution of a method in a RhinoMocks mock?	[Test]\npublic void Test()\n{\n    var classMock = MockRepository.GenerateMock<MyClass>();\n    var linkedMock = MockRepository.GenerateStub<MyClass>();\n\n    classMock.Expect(c => c.MyMethod(linkedMock));\n\n    classMock.MyMethod(linkedMock);\n\n    classMock.AssertWasCalled(c => c.MyMethod(linkedMock));\n}\n\npublic class MyClass\n{\n    public virtual void MyMethod(MyClass linkedClass)\n    {\n        Console.WriteLine("MyMethod is called");\n    }\n}	0
3166151	3166113	how do I determine where the user came from in asp.net?	Request.ServerVariables["HTTP_REFERER"]	0
9859657	9859643	Decimal string format truncates the zero left to the decimal point	"{0:#,###,##0.##}"	0
30988928	30988840	Deserializing Json data to c# for use in GridView - Error Data source is an invalid type	GridView1.DataSource = personDetail.PersonDetails;	0
34165165	34157359	How to handle variables that is null in JSON	if(matchGame == null)\n            {\n                // Only do this if the serial is not null\n                if (i["serial"].Type != JTokenType.Null)\n                {\n                   Console.WriteLine(i["serial"].ToString());\n                   var Game = new RentGame(i["item"]["name"].ToString(), i["id"].ToString(), i["serial"].ToString());\n                   rentGame.Add(Game);\n                   Console.WriteLine("Add rent game " + Game.name);\n            }	0
26879829	26879597	Wrong user credentials opening login popup with automation API	Repository.SuppressSecurityDialog = true	0
4610416	4608988	Lucene optional exact match query syntax	+make:dell +model:latitude +year:2010 +(title:p0175 content:p0175)	0
15263619	15263570	Add comma before last character of a string in c#	strTarget = strTarget.Insert( srtrTarget.Length -1, ",");	0
28949891	28949482	Is there a way in WCF to have a pointer to a method on the server that it can use?	public class MyObject()\n{\n    private MyWcfProxy WcfChannel;\n\n    public MyObject (MyWcfProxy wcfChannel) {WcfChannel = wcfChannel;}\n\n    public decimal CalcArea() { /*Area calculation logic*/ }\n\n    public decimal CalcAreaOnServer() { return WcfChannel.CalcArea(this); }\n}	0
730418	730268	Unique random string generation	Guid g = Guid.NewGuid();\n    string GuidString = Convert.ToBase64String(g.ToByteArray());\n    GuidString = GuidString.Replace("=","");\n    GuidString = GuidString.Replace("+","");	0
27104104	27103641	How do I check is uptime value on datasource with C#	if (drv["uptime"].ToString().Contains("day"))\n{\n    // up for one day or more\n}\nelse\n{\n    // not up for a day yet\n}	0
1370305	1370275	Is there any way to change a class' attributes?	[CollectionDataContract(Name = "MyItemInfoList", Namespace = "MyNamespace")]\npublic class MyItemInfoList<TItem> : ItemInfoList<TItem> where TItem : class	0
22318754	22318561	Display text on textbox based on month selected in datetimepiecker	if (datetimepicker1.Value.Date.Month == 3)\n   texbox1 .Text = "3";	0
34173543	34115181	Remove from subdocument from mongodb version 2.4 by id	const int id = 1;\nvar pull = Builders<Post>.Update.PullFilter(x => x.Tags, a => a.Id == id);\nvar filter1 = Builders<Post>.Filter.And(Builders<Post>.Filter.Eq(a => a.Id, 1), Builders<Post>.Filter.ElemMatch(q => q.Tags, t => t.Id == id));\ncollection.UpdateOneAsync(filter1, pull);	0
20340904	20340638	Boolean Statement True For Length of Time	private bool CurrentlyValidated\n{\n  get\n  {\n    return DateTime.Now < _expiryTime && _validated ;\n  }\n  set\n  {\n    _validated  = value ;\n    _expiryTime = DateTime.Now.AddMinutes(5) ;\n  }\n}\nprivate bool     _validated  ;\nprivate DateTime _expiryTime ;	0
13212289	13211714	CSharpCodeProvider Output console app as windows form app	compilerparams.CompilerOptions = "/target:winexe";	0
21577806	21577249	Overwrite file, but only parts that are not spaces	var byteCharZero = Convert.ToByte('0');\nvar stringBuilder = new StringBuilder("         00000000            0000000000000000 ");\nusing (var fileStream = File.Open("D:\\file.dat", FileMode.OpenOrCreate, FileAccess.Write))\n{\n  var length = Math.Min(stringBuilder.Length, fileStream.Length);\n  for (var i = 0; i < length; i++)\n  {\n    if (stringBuilder[i] == '0')\n    {\n      fileStream.Position = i;\n      fileStream.WriteByte(byteCharZero);\n    }\n  }\n}	0
1841276	1841246	C# Splitting An Array	public void Split<T>(T[] array, int index, out T[] first, out T[] second) {\n  first = array.Take(index).ToArray();\n  second = array.Skip(index).ToArray();\n}\n\npublic void SplitMidPoint<T>(T[] array, out T[] first, out T[] second) {\n  Split(array, array.Length / 2, out first, out second);\n}	0
23709991	23709725	Brush only parts of an Ellipse in WPF	var geometry = new GeometryGroup();\ngeometry.Children.Add(new RectangleGeometry(new Rect(1, 0, 1, 1)));\ngeometry.Children.Add(new RectangleGeometry(new Rect(0, 1, 1, 1)));\nvar drawing = new GeometryDrawing(Brushes.Black, null, geometry);\nvar brush = new DrawingBrush(drawing);\n\ndc.DrawEllipse(brush, pen, cntrpoint, 30, 30);	0
15162298	15162046	EF add a FK that is already defined	using System;\nusing System.Collections.Generic;\nusing System.ComponentModel.DataAnnotations;\nusing System.Data;\nusing System.Data.Entity;\nusing System.Linq;\nusing System.Text;\n\nnamespace CFExamples2\n{\n    public class Servicio \n    {\n        public int Id { get; set; }\n\n        public int? PartoId { get; set; }\n        public virtual Parto Parto { get; set; }\n    }\n\n    public class Parto\n    {\n        public int Id { get; set; }\n        public virtual int ServicioId { get; set; }\n        [Required]\n        public virtual Servicio Servicio { get; set; }\n    }\n\n\n    public class Model : DbContext\n    {\n        public DbSet<Servicio> Servicios { get; set; }\n        public DbSet<Parto> Partos { get; set; }\n\n        protected override void OnModelCreating(DbModelBuilder modelBuilder)\n        {\n\n        }\n    }\n    class Program\n    {\n        static void Main(string[] args)\n        {\n\n\n        }\n    }\n}	0
1741879	1741864	Winform, authorization on ui	Button adminButton = new Button();\nButton userButton = new Button();\n...\n\npublic void Form_Load(object sender, EventArgs e)\n{\n    User user = // find user\n    adminButton.Enabled = (user.Role == UserRoles.Admin)\n    userButton.Enabled = (user.Role == UserRoles.Admin || user.Role == UserRoles.Standard)\n}	0
8801162	8800997	Configuring multiple relationships between entities	modelBuilder.Entity<Course>()\n     .HasRequired(c => c.Leader)\n     .WithMany(p => p.CoursesLead)\n     .Map(m => m.MapKey("Leader_PersonID"));\n\nmodelBuilder.Entity<Course>()\n     .HasRequired(c => c.CreatedBy)\n     .WithMany(p => p.CoursesCreated)\n     .Map(m => m.MapKey("CreatedBy_PersonID"));\n\nmodelBuilder.Entity<Course>()\n     .HasRequired(c => c.UpdatedBy)\n     .WithMany(p => p.CoursesUpdated)\n     .Map(m => m.MapKey("UpdatedBy_PersonID"));	0
5944600	5944581	Is there anyway to save the output of shell script into a text file?	mycommand.exe > logfile.txt	0
20444357	20442475	how can i get RouteValueDictionary values from Page.RouteData.DataTokens	Page.RouteData.Values	0
29185084	29153967	Convert a byte[] into an Emgu/OpenCV Image	byte[] depthPixelData = new byte[640*480]; // your data\n\nImage<Gray, byte> depthImage = new Image<Gray, byte>(640, 480);\n\ndepthImage.Bytes = depthPixelData;	0
13646026	13645960	Split string to array, remove empty spaces	String tmp = @"abc 123 ""Edk k3"" String;";\nvar tmpList = tmp.Split(new[] { '"' }).SelectMany((s, i) =>\n{\n    if (i % 2 == 1) return new[] { s.Replace(" ", "") };\n    return s.Split(new[] { ' ', ';' }, StringSplitOptions.RemoveEmptyEntries);\n}).ToList();	0
14507316	14499570	How to get a stream from a byte array in a windows8 store app	// put bytes into the stream\nvar ms = new InMemoryRandomAccessStream();\nvar dw = new Windows.Storage.Streams.DataWriter(ms);\ndw.WriteBytes(new byte[] { 0x00, 0x01, 0x02 });\nawait dw.StoreAsync();\n\n// read them out\nms.Seek(0);\nbyte[] ob = new byte[ms.Size];\nvar dr = new Windows.Storage.Streams.DataReader(ms);\nawait dr.LoadAsync((uint)ms.Size);\ndr.ReadBytes(ob);	0
27584	27570	Find number of files in all subdirectories	string[] files = directory.GetFiles(@"c:\windows\system32", "*.dll", SearchOption.AllDirectories);\n\nreturn files.Length;	0
9676758	9674078	DataGridView-when I press enter it goes to the next cell	private void dataGridView1_KeyDown(object sender, KeyEventArgs e)\n    {\n        if (e.KeyData == Keys.Enter)\n        {\n            int col = dataGridView1.CurrentCell.ColumnIndex;\n            int row = dataGridView1.CurrentCell.RowIndex;\n\n            if (col < dataGridView1.ColumnCount - 1)\n            {\n                col ++;\n            }\n            else\n            {\n                col = 0;\n                row++;\n            }\n\n            if (row == dataGridView1.RowCount)\n                dataGridView1.Rows.Add();\n\n            dataGridView1.CurrentCell = dataGridView1[col, row];\n            e.Handled = true;\n        }\n    }	0
16608155	16608127	Deserialize varbinary in file	Car car = new Car("BMW");\n\nBinaryFormatter bFormatter = new BinaryFormatter();\nMemoryStream ms = new MemoryStream();\nbFormatter.Serialize(ms, car);\nSystem.Data.Linq.Binary carBinary \n    = new System.Data.Linq.Binary(ms.ToArray());\n\nTestDB db = new TestDB(ConfigurationManager.ConnectionStrings["TestDBConnectionString"].ConnectionString);\ndb.InsertObjectSerialize(carBinary);\n\nISingleResult<GetObjectSerializeResult> result = db.GetObjectSerialize(1);\nSystem.Data.Linq.Binary carBinaryFromDB\n    = result.Single().Object;\nms = new MemoryStream(carBinaryFromDB.ToArray());\n\nCar carFromDB = (Car)bFormatter.Deserialize(ms);	0
33180224	33180163	Auto generate Guid with EntityTypeConfiguration	entity.Property(e => e.Id).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);	0
2678510	2677285	Convert SQL with Inner AND Outer Join to L2S	public static DataTable GetImmunizations(int haReviewID)\n{\n    using (var context = McpDataContext.Create())\n    {\n        var currentImmunizations =\n            from haReviewImmunization in context.tblHAReviewImmunizations\n            where haReviewImmunization.HAReviewID == haReviewID\n\n            join maintItem in context.tblMaintItems\n            on haReviewImmunization.ImmunizationMaintID \n            equals maintItem.ItemID\n\n            join maintItem2 in context.tblMaintItems\n            on haReviewImmunization.ImmunizationReasonID \n            equals maintItem2.ItemID into g\n            from maintItem3 in g.DefaultIfEmpty()\n\n            select new\n            {\n                haReviewImmunization.ImmunizationDate,\n                haReviewImmunization.ImmunizationOther,\n                maintItem.ItemDescription,\n                Reason = maintItem3 == null ? " " : maintItem3.ItemDescription\n            };\n\n        return currentImmunizations.CopyLinqToDataTable();\n    }\n}	0
32666629	32666221	C# Tuition Discount How to compute discount	//Computation\nvar cashDiscount = tuition * (cash / 100); \nvar installationDiscount = tuition * installment; \ndiscount = cashDiscount + installationDiscount;\ntotal = tuition - discount; \n\ntextBox5.Text = discount.ToString(); \ntextBox3.Text = total.ToString();	0
17683036	17682099	Convert string to TimeSpan	static Regex myTimePattern = new Regex( @"^(\d+)(\.(\d+))?$") ;\nstatic TimeSpan MyString2Timespan( string s )\n{\n  if ( s == null ) throw new ArgumentNullException("s") ;\n  Match m = myTimePattern.Match(s) ;\n  if ( ! m.Success ) throw new ArgumentOutOfRangeException("s") ;\n  string hh = m.Groups[1].Value ;\n  string mm = m.Groups[3].Value.PadRight(2,'0') ;\n  int hours   = int.Parse( hh ) ;\n  int minutes = int.Parse( mm ) ;\n  if ( minutes < 0 || minutes > 59 ) throw new ArgumentOutOfRangeException("s") ;\n  TimeSpan value = new TimeSpan(hours , minutes , 0 ) ;\n  return value ;\n}	0
10886978	10884182	Creating a com object with another com object in C#	object atl3270Tool = null, ErrMsg = null;\n    object atlDirectorObject = Activator.CreateInstance(Type.GetTypeFromProgID("atlDirectorObject.atlDirector"));\n    object[] p = { "3270", 1, true, true, 0, atl3270Tool, ErrMsg };\n    object[] p2 = { "xxxx", "", "xxxxxxxxxx", ErrMsg };\n    Boolean[] cb = new Boolean[7];\n    cb[5] = true; //set array index of atl3270Tool to true\n    Microsoft.VisualBasic.CompilerServices.NewLateBinding.LateCall(atlDirectorObject, atlDirectorObject.GetType(), "CreateTool", p, null, null, cb, false);\n    atl3270Tool = p[5];\n    Microsoft.VisualBasic.CompilerServices.NewLateBinding.LateCall(atl3270Tool, atl3270Tool.GetType(), "ShowScreen", p2, null, null, null, false);\n// add code to release com objects	0
19447879	19447509	How to execute each iteration of the loop in one thread with task?	var sw = Stopwatch.StartNew();\nvar pendingTasks =\n  myListOfLists\n    .Select(iterator => TaskEx.Run(() => myCheckMethod(iterator))).ToArray();\nTask.WaitAll(pendingTasks);\nvar elapsedTime = sw.Elapsed;	0
8755351	8755285	How to Read Value From ASP.net TextBox Template Column in JavaScript	function getgridvalue()\n     {\n      // Call this on button click\n     Array obj;\n      var gridview=document.getElementById("<GridView ID here>"); //Grab a reference to the Grid\n      for (i=1;i<gridview.rows.length;i++) //Iterate through the rows\n       {\n        obj[i]=gridview.rows[i].cells[1].firstChild.value; //get the values\n       }\n\n     }	0
27891378	27891260	De\Serializing list of objects XML	[Serializable()]\n  public class Observer : MapObject\n  {\n\n    private XmlSerializer ser;\n\n    public int ID_Observer { get; set; }\n    public double azimuth { get; set; }\n    public double Long { get; set; }\n    public double Lat { get; set; }\n    public double Lenght { get; set; }\n    public bool haveConnection { get; set; }\n    public bool DrawAzimuth { get; set; }\n\n    /// <summary>\n    /// C'tor\n    /// </summary>\n    public Observer(int ID_Observer = 0, double azimuth = 0, double Lat = 0, double Long = 0, double Lenght = 0, bool haveConnection = true, bool DrawAzimuth = true)\n    {\n      this.ID_Observer = ID_Observer;\n      this.azimuth = azimuth;\n      this.Long = Long;\n      this.Lat = Lat;\n      this.haveConnection = haveConnection;\n      this.DrawAzimuth = DrawAzimuth;\n      this.Lenght = Lenght;\n    }\n\n    public Observer()\n    {\n      ser = new XmlSerializer(this.GetType());\n    }\n  }	0
26586937	26586836	Creating link with html content	RouteValueDictionary routedict = new RouteValueDictionary(routevalues);	0
31410021	31409667	How to modify properties of the incoming object without creating a new instance?	foreach(ReportItem item in report.Items)\n{\n   // update item\n}	0
25895026	25894948	Make an array work like a circle	new_index = (current_index+3)%length_of_array	0
6950631	6950495	LINQ swap columns into rows	vector.AddRange(values.Select(value => value[i]));	0
20615560	20614817	How to set date/time from time server	private static TimeZoneInfo INDIAN_ZONE = TimeZoneInfo.FindSystemTimeZoneById("India Standard Time");\nDateTime indianTime =  TimeZoneInfo.ConvertTimeFromUtc(DateTime.UtcNow, INDIAN_ZONE);	0
16227987	16227964	Save Byte Array to UNC Path	System.IO.File.WriteAllBytes(@"\\server\tmp\" + FileName, fileData);	0
14038340	14038221	Finding Date of Birth given age in months	int ageInMonths = 18;\nDateTime dt = DateTime.Today;\nDateTime DateOfBirth = dt.AddMonths(-ageInMonths);	0
19643324	19643018	Need help writing string to HEX in C#	byte[] octets ;\nEncoding someEncoding = new UTF8Encoding(false) ;\n\nusing( MemoryStream aMemoryStream = new MemoryStream(8192) ) // let's start with 8k\nusing ( BinaryWriter writer = new BinaryWriter( aMemoryStream , someEncoding ) ) // wrap that puppy in a binary writer\n{\n  byte[] prefix = { 0x02 , 0x00 , 0x35 , 0x37 , 0xFF , } ;\n  byte[] suffix = { 0x00 , 0x03 , } ;\n\n  writer.Write( prefix ) ;\n  writer.Write( "OF=TEST" );\n  writer.Write( suffix ) ;\n\n  octets = aMemoryStream.ToArray() ;\n\n}\n\nforeach ( byte octet in octets )\n{\n  Console.WriteLine( "0x{0:X2}" , octet ) ;\n}	0
6698371	6698294	How to create a piece of C#.NET script to let MySql server execute a MySql Script?	string myTestSql = IO.File.ReadAllText("myTest.sql");\n...\nMySqlCommand newCmd = new MySqlCommand(myTestSql, cn);	0
30797217	30796629	90/180/270 deg rotation of BitmapImage in windows phone 8	MyImageControl.Source= new BitmapImage(new Uri("ms-appx:///Assets/SmallLogo.scale-240.png", UriKind.RelativeOrAbsolute));\n\nRotateTransform myRotateTransform = new RotateTransform();\nmyRotateTransform.Angle=30;\nMyImageControl.RenderTransform = myRotateTransform;	0
21597769	21597601	Change in string some part, but without one part - where are numbers	string ReplaceSomeHyphens(string input)\n{\n    string result = Regex.Replace(input, @"(\D)-", "${1} ");\n    result = Regex.Replace(result, @"-(\D)", " ${1}");\n    return result;\n}	0
9715896	9711221	How do you set the DisplayMemberPath for a List of Lists (at runtime)?	listView1.DisplayMemberPath = "Property2.ColumnName";	0
6665963	6665862	Getting a statabase query returned as string in c#	using (var reader = command.ExecuteReader())\n{\n    while (reader.Read())\n    {\n        string line = string.Format(\n                          "{0},{1},{2}",\n                          reader["STUDENTNAME"],\n                          reader["STUDENTNUMBER"],\n                          reader["STUDENTDESCRIPTION"]);\n\n        ...\n    }\n}	0
23516966	23516188	TargetedPatchingOptOut and other attributes on abstract methods	[AttributeUsage(AttributeTargets.Method | AttributeTargets.Constructor, \n     AllowMultiple = false, Inherited = false)]\npublic sealed class TargetedPatchingOptOutAttribute : Attribute {\n    // etc...\n}	0
5481156	5481131	Counting rows with a SqlDataAdapter	dt.Rows.Count	0
10912625	10911002	How to know whether replace success or fail?	Excel.Range Range = xlWorkSheet.UsedRange;\n\n  currentFind =  Range .Find(textBox1.Text,                      Type.Missing,Excel.XlFindLookIn.xlValues,               Excel.XlLookAt.xlPart,                             Excel.XlSearchOrder.xlByRows,Excel.XlSearchDirection.xlNext,false,\n    Type.Missing, Type.Missing);\n\n\n   if (currentFind!=null)\n   {\n\n        SheetsArray.Add(xlWorkSheet.Name);\n   }	0
25515575	25515530	c# - Reading lines from text file and adding to listbox	string[] lines = System.IO.File.ReadAllLines(filesrc);\nlistDOF.Items.AddRange(lines);	0
4099406	4099344	How to wait until webBrowser1 completey loads after webBrowser1 click or submit event fired	private void PrintHelpPage()\n{\n    // Create a WebBrowser instance. \n    WebBrowser webBrowserForPrinting = new WebBrowser();\n\n    // Add an event handler that prints the document after it loads.\n    webBrowserForPrinting.DocumentCompleted +=\n        new WebBrowserDocumentCompletedEventHandler(PrintDocument);\n\n    // Set the Url property to load the document.\n    webBrowserForPrinting.Url = new Uri(@"\\myshare\help.html");\n}\n\nprivate void PrintDocument(object sender,\n    WebBrowserDocumentCompletedEventArgs e)\n{\n    // Print the document now that it is fully loaded.\n    ((WebBrowser)sender).Print();\n\n    // Dispose the WebBrowser now that the task is complete. \n    ((WebBrowser)sender).Dispose();\n}	0
5375987	5375947	How do I edit/update records from a database using textbox?	if (!Page.IsPostBack)	0
24349208	24349133	Working with methods that return anonymous methods	public class SomeClass\n{\n    private static Action<string> cachedAction;\n    public Action<string> SomeAction { get; set; }\n\n    public SomeClass()\n    {\n        SomeAction = GetSomeAnonymousMethod();\n    }\n\n    private Action<string> GetSomeAnonymousMethod()\n    {\n        Action<string> action = cachedAction;\n        if (action == null)\n        {\n            action = AnonymousMethodImplementation;\n            cachedAction = action;\n        }\n        return action;\n    }\n\n    private static void AnonymousMethodImplementation(string text)\n    {\n        Console.WriteLine(text);\n    }\n}	0
11204698	6549701	Is there a dynamic-creation-friendly LinkLabel Alternative?	LinkLabel.Links.Add	0
5735707	5735693	Search file by filter with regex	List prftFiles = (new DirectoryInfo(filePath)).GetFiles("prft*", SearchOption.AllDirectories)	0
23267769	23267490	How to break Execution of an override method from it's base class implementation in windows phone?	public class BaseViewModel : ViewModelBaseX\n{\n\n\n       protected virtual void HandleNavigatedTo(NavigationMode mode, Uri uri, IDictionary<string, string> queryString)\n        {\n        }\n\n        public override void OnNavigatedTo(NavigationMode mode, Uri uri, IDictionary<string, string> queryString)\n        {\n            if (condition)\n            {\n                HandleNavigatedTo(mode, uri, queryString);\n             }\n        }\n    }\n\n    public class AboutViewModel:BaseViewModel\n    {\n          public override void HandleNavigatedTo(NavigationMode mode, Uri uri, IDictionary<string, string> queryString)\n          {\n              // here some code to be execute \n          }\n     }	0
29212149	29212121	How do I set a #define for each file?	Project -> Properties -> Build -> Conditional compilation symbols	0
27975626	27772825	Outlook Interop: is there a way to check if an Outlook folder is read-only	try\n{\n    ((AppointmentItem)calendarFolder.Items.Add(OlItemType.olAppointmentItem)).Delete();\n\n    // Do whatever you need with this folder.\n}\ncatch\n{\n    // This probably means the folder is not writeable.\n}	0
26294173	22780343	How to programmatically check if user is federated in Office 365?	POST\nhttps://login.microsoftonline.com/GetUserRealm.srf\nContent-Type: application/x-www-form-urlencoded\nAccept: application/json\nhandler=1&login=johndoe@somecompany.onmicrosoft.com	0
12506132	12505859	Allow a ProgessBar to run in a separate thread but occasionally step in to control it?	void startProgress()\n{\n    ThreadStart ts = new ThreadStart(Go);\n    Thread t = new Thread(ts);\n    t.Start();\n}\n\nvoid Go()\n{\n    double val = 0;\n    while (val < 100)\n    {\n        Thread.Sleep(50);\n        Dispatcher.Invoke(new action(() =>\n        {\n            MyProgressBar.Value += 0.5;\n            val = MyProgressBar.Value;\n        }));\n    }\n}\n\ndelegate void action();	0
26041145	26037701	how to display content of two dimensional string array in listview under two columns?	foreach (var item in arrStr){ \nListViewItem itm = new ListViewItem(item);\nlistView1.Items.Add(itm);}	0
7266896	7266866	How do I reset sorting for a GridView?	gridViewInstance.Sort("", SortDirection.Ascending);	0
3628696	3628630	Use reflection to get attribute of a property via method called from the setter	var method = new StackTrace().GetFrame(1).GetMethod();\nvar propName = method.Name.Remove(0, 4); // remove get_ / set_\nvar property = method.DeclaringType.GetProperty(propName);\nvar attribs = property.GetCustomAttributes(typeof(TestMaxStringLength), true);	0
21074357	21074297	Building up a matrix dynamically in the xy plane	SortedList<int, SortedList<int, int>>	0
30011604	29996654	Mapped Id using StringObjectIdGenerator produces string _id in database	cm.MapIdMember(p => p.Id)\n                .SetIdGenerator(StringObjectIdGenerator.Instance)\n                .SetSerializer(new StringSerializer(BsonType.ObjectId));	0
28457579	28457458	Entity Framework - how to remove linked elements	Entity.Children.AssociationChanged += \nnew CollectionChangeEventHandler(EntityChildrenChanged);\nEntity.Children.Clear();            \n\nprivate void EntityChildrenChanged(object sender,\n    CollectionChangeEventArgs e)\n{\n    // Check for a related reference being removed. \n    if (e.Action == CollectionChangeAction.Remove)\n    {\n        Context.DeleteObject(e.Element);\n    }\n}	0
7435128	7434811	Load a single related object	var princess = context.Princesses.Find(id);\nvar unicorns = context.Unicorns.Where(u => u.PrincessId == id && u.UnicornName == "Blinky");\n\nprincess.Unicorns = unicorns.ToList();	0
6431740	6431693	Setting the selected value of a ListBoxView as a string (C#)	System.Windows.Forms.ListBox lb= new ListBox();\n            lb.SelectedItem.ToString();	0
20986540	20986486	To check if print command was sent to the printer in wpf	PrintDialog dialog = new PrintDialog(); \nif (dialog.ShowDialog()) \n  printDialog.PrintVisual(document, "doc");	0
3146460	3146456	How can I change the background color of a gridview cell, based on a conditional statement?	/// <summary>\n/// Handles gridview row data bound event.\n/// </summary>\n/// <param name="sender">Sender Object</param>\n/// <param name="e">Event Argument</param>\nprotected void Gv_RowDataBound(object sender, GridViewRowEventArgs e)\n{\n    // We don???t want to apply this to headers.\n    if (e.Row.RowType == DataControlRowType.DataRow)\n    {\n        try\n        {\n            //your data-object that is rendered in this row, if at all required.\n            //Object obj = e.Row.DataItem;\n\n            //find the right color from condition\n            string color = condition ? "#ff9900" : "some-other-color";\n\n            //set the backcolor of the cell based on the condition\n            e.Row.Cells[4].Attributes.Add("Style", "background-color: " + color + ";");\n        }\n        catch\n        {\n        }\n    }\n}	0
10541162	10541127	Get Page's Type from URL in C#	System.Web.Compilation.BuildManager.GetCompiledType(Me.Request.Url.AbsolutePath)	0
18154455	18154286	I need to accept from input file and that may be of any format in C# . i need to check the format and extract year	DateTime temp;\nif (DateTime.TryParseExact("20130101", "yyyyMMdd", CultureInfo.InvariantCulture, DateTimeStyles.None, out temp))\n{\n     string year = temp.Year.ToString();\n}	0
5322279	5303843	Validating data annotations inside a class: TryValidateObject results always empty	[Required]\n   public string SomeValue {get;set;}	0
11598392	11598370	Visual C#: How to add controls to a form created with code?	label1.Location = new Point(25,25);\n\n   this.Controls.Add(label1);	0
3907218	3907170	Setting label text in DataBinding in a GridView (ASP.NET/C#)	protected void Label1_DataBinding(object sender, EventArgs e)\n{\n    Label lb = (Label)sender;\n\n    lb.Text = lb.Text.Replace(Environment.NewLine, "<br />");\n}	0
11541933	11541855	How can I let my customers have their own domains redirect to my server and identify them?	Request.Url or look in the Request.ServerVariables["SERVER_NAME"]	0
16966828	16951232	Clicking on TextBox inside Panel triggers Enter event multiple times	Dim lFocused as Boolean\n\nPrivate Sub TextBox1_GotFocus(ByVal sender As Object, ByVal e As System.EventArgs) Handles TextBox1.GotFocus\n        TextBox1.SelectAll()\n        lFocused = True\nEnd Sub\n\nPrivate Sub TextBox1_Leave(ByVal sender As Object, ByVal e As System.EventArgs) Handles TextBox1.Leave\n        lFocused = False\n    End Sub\n\nPrivate Sub TextBox1_MouseUp(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles TextBox1.MouseUp\n    lFocused = True\n    TextBox1.SelectAll()\nEnd Sub	0
28321997	28321508	publish a project with local database	Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\Database.mdf;Integrated Security=True	0
13237403	13236919	Querying highest value by keys from database	var counts = from item in database.Items\n             group item by new { item.ParentId, item.ItemId } into itemGroup\n             select new Item()\n                    {\n                        ParentId = itemGroup.Key.ParentId,\n                        ItemId = itemGroup.Key.ItemId,\n                        Count = itemGroup.Max(x => x.Count)\n                    };	0
3156075	3155801	RSS Feed validation: IRI found where URL expected - How to convert IRI link to the valid URL?	string url = new Uri(iri).AbsoluteUri	0
2826292	2826116	binding list variable one after another	string[] names = FunNames();\nstring[] ages = FunAge();\nstring[] genders = Fungender();\nstring[] countries = FunCountry();\n\n/* have to make sure they are not of different lengths */\n\nint minLength = names.Length;\n\nif (ages.Length < minLength)\n    minLength = ages.Length;\n\nif (genders.Length < minLength)\n    minLength = genders.Length;\n\nif (countries.Length < minLength)\n    minLength = countries.Length;\n\nfor(int i=0 ; i < minLength; i++)\n{\n    Users item = new Users();\n    item.Name = names[i];\n    item.Age = int.Parse(ages[i]);\n    item.Gender = genders[i];\n    item.Country = countries[i];\n\n    myList.Add(item);\n}	0
19154130	19109946	show timespan values after changed into local time	var utcTime = DateTime.UtcNow.AddHours(5).AddMinutes(30);\n        TimeSpan ts = utcTime.Subtract(dateTime);	0
11529802	11513513	How do I tretrieve html table values(text) using Selenium 1 C#	"//del[contains(., '$')]"	0
7988588	7984398	Selecting values from an xml document object with XPATH in code behind (c#)	strExpression1 = "/Results/Checks/Check[@id = 'adsl']/Linespeed";\n//or strExpression1 = "//Checks/Check[@id = 'adsl']/Linespeed";\n//doc has no namespace\nCheck = root.SelectSingleNode(strExpression1);\n....\nstring Linespeedval = Check.InnerText;	0
14449032	14437597	Creating dynamic charting tooltips	int points = 0;\n\n        //For every row in the values table, plot the date against the variable value\n        foreach (DataRow row in Values.Rows)\n        {\n            myChart.Series[Variable].Points.AddXY(Convert.ToDateTime(row["Date"].ToString()), row["Variable"].ToString());               \n            myChart.Series[Variable].Points[points].ToolTip = Variable + " = #VALY \r\nDate = #VALX{d} \r\nSerial = " + row["Serial"].ToString();\n            points += 1;\n        }	0
8104818	8104752	How can move an object from one cell to other cell in c#	Grid.SetRow(i1, 2);\nGrid.SetColumn(i1, 4);	0
7587051	7417758	c# datagridview control	private void dataGridView1_DoubleClick(object sender, EventArgs e)\n{\n    Control newControl = new MyTextBox();\n\n    dataGridView1.Controls.Add(newControl);\n    dataGridView1.ClearSelection();  //to be sure that any of cells are selected  \n    newControl.Focus();\n}\n\nclass MyTextBox : TextBox\n{\n    protected override bool ProcessCmdKey(ref Message msg, Keys keyData)\n    {\n        if (keyData == Keys.Enter || keyData == Keys.Tab || keyData == Keys.A)\n        {\n            Trace.WriteLine("Ok, key = " + keyData);\n            return true;///Or false??? return to override the basic behavior\n        } \n        return base.ProcessCmdKey(ref msg, keyData);\n    }\n }	0
33382841	33382812	calculator delete same text from textbox asp .net	var input = ResultBox.Text;\nvar operators = new[] { '+', '-', '*', '/' };\nif (operators.Any (o => o == input[input.Length - 1]) \n    && operators.Any (o => o == input[input.Length - 2]))\n{\n    input = input.Substring(0, input.Length - 1);\n}\n\nResultBox.Text = input;	0
4799217	4796110	How to get ratio of width x height of an image on disk / file?	Image img = System.Drawing.Image.FromFile(path);\n int height = img.Height;\n int width = img.Width;	0
3968601	3968210	Disable clicking through other controls - WPF	private void button1_Click(object sender, System.Windows.RoutedEventArgs e)\n{\n  if (e.Source == this.button1)\n  {\n    Application.Current.Shutdown();\n  }\n}	0
6326754	6326208	C# 'select count' sql command incorrectly returns zero rows from sql server	command.CommandType = CommandType.Text	0
24048154	24047407	Invalid cross-thread access in TimerEvent for ViewModel update	async Task LoadData()\n{\n    // do some stuff\n    var data = await SomeWebCall();\n    Deployment.Current.Dispatcher.BeginInvoke( () => {\n        MyObservableCollection = data; // or new ObservableCollection(data);\n    });\n}	0
20070587	20070489	Comparing two Array in C#	Console.WriteLine("Two arrays are equal? ...{0}", arOne.Intersect(arTwo).Any() ? "true" : "false");	0
6823418	6823377	Encode HTML before sending to Controller/DB	public class MyViewModel\n{\n    public string prop1 { get; set; }\n\n    [AllowHtml]\n    public string prop2 { get; set; }\n}	0
12508780	12508643	How to activate task in c#?	var result = await _client.GetAllCitiesAsync( new BaseRequest());	0
20068033	20067518	RegEx - Filtering out empty strings between delimiters	var input = "Hey; &nbsp &nbsp; Hi; ;;";\nvar result = input.Split(';')\n                  .Select(c => c.Replace("&nbsp", " ").Trim())\n                  .Where(c => c.Length != 0);\nforeach (var item in result)\n{\n    Console.WriteLine(item);\n}	0
30596757	30596360	Add objects to list in web application	public class WS : System.Web.Services.WebService\n{\n\n    [WebMethod(EnableSession = true)]\n    [ScriptMethod(UseHttpGet = true)]\n    public void registerUser()\n    {\n        try\n        {\n            if(Session["users"] == null)\n                Session["users"] = new List<User>();\n\n            List<User> users = (List<User>)Session["users"];\n\n            string s = HttpContext.Current.Request.Form[0].ToString();\n            User tempUser = new User();\n            tempUser = JsonConvert.DeserializeObject<User>(s);\n            users.Add(tempUser);\n\n            Session["users"] = users;\n        }\n        catch(Exception e)\n        {\n            HttpContext.Current.Response.Write(e.Message);\n        }\n    }\n}	0
31811277	31811085	Crtl+Shift+Space shortcut in Visual Studio 2015	Edit.ParameterInfo	0
23465827	23465690	Unsafe Variable Initialization?	int variable;\nfor(int i=0; i++; i<4){\n     variable+=i; //Compilation error, garbage or expected result, depending on language\n}	0
5956514	5956371	wpf binding change of binding source	public class MyClass : INotifyPropertyChanged\n{\n    private Network _network;\n\n    public Network Network\n    {\n        get\n        {\n            return _network;\n        }\n        set\n        {\n            if (value != _network)\n            {\n                _network = value;\n                NotifyPropertyChanged(value);\n            }\n        }\n    }\n\n\n    protected NotifyPropertyChanged(string propertyName)\n    {\n        if (PropertyChanged != null)\n            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));\n    }\n\n}	0
13658301	13658272	Converting xls to DataTable	string[] csvRows = System.IO.File.ReadAllLines(strfilename); \n for(int x = 0; i < csvRows.Length; x++)\n     dt.Columns.Add("Col" + x.ToString());	0
13835270	13834969	How to remove the sql injection from this query and make it working well?	private bool isAdmin(string username)\n {\n    string connString = "Data Source=appSever\\sqlexpress;Initial Catalog=TestDB;Integrated Security=True";\n    string cmdText = "SELECT ID, NetID FROM dbo.Admins WHERE NetID = @NetID)";\n    using (SqlConnection conn = new SqlConnection(connString))\n    {\n        conn.Open();\n        // Open DB connection.\n        using (SqlCommand cmd = new SqlCommand(cmdText, conn))\n        {\n            cmd.Parameters.AddWithValue("@NetID", NetID);\n            SqlDataReader reader = cmd.ExecuteReader();\n            if (reader != null)\n                if (reader.Read())\n                    if (reader["ID"].Equals(1))\n                        return true;\n            return false;\n        }\n    }\n }	0
15956840	15907868	winform change BackgroundImage property of a button on hover	this.btnGetHardwareID.FlatAppearance.MouseOverBackColor = System.Drawing.Color.Transparent;	0
13379319	13379258	Group a List based on uniqueness	var newList = dtoCollection.GroupBy(d => d.Name)\n             .Select(g => new DTO(){ Name=g.Key, Count=g.Select(d => d.Count).Sum()})\n             .ToList();	0
2605092	2605082	Include a c# file in aspx page	public class MyBaseClass : System.Web.UI.Page\n{\n    protected override void OnLoad(EventArgs e)\n    {\n       // ... add custom logic here ...\n\n       // Be sure to call the base class's OnLoad method!\n       base.OnLoad(e);\n    }\n}\n\npublic class WebForm1 : MyBaseClass\n{\n    private void Page_Load(object sender, System.EventArgs e)\n    {\n        // Put user code to initialize the page here\n    }\n\n    ...\n}	0
8318881	8317751	Detaching EF entities from DB context, removing their relations?	public static string Serialize(object model)\n {\n     var settings = new JsonSerializerSettings\n                     {\n                        ReferenceLoopHandling = ReferenceLoopHandling.Ignore,\n                     };\n     return JsonConvert.SerializeObject(model, Formatting.None, settings);\n }	0
25107211	25107156	random generator won't generate more than 1 password	for (int i = 0; i<passwordsNum; i++)\n{\n    passwordline = "";\n    for (int i2 = 0; i2 < passwordLength; i2++)\n    {\n        //Other code is the same\n    }\n}	0
10045849	9814206	How to change a Android.graphics.bitmap into a byte array in c#	Bitmap thumb;\nAndroid.Net.Uri val;\nthis.thumb = MediaStore.Images.Media.GetBitmap(this.ContentResolver, this.val);                        \nBitmap scaledThumb = Bitmap.CreateScaledBitmap(this.thumb, 1600, 1200, true);                        \nMemoryStream stream = new MemoryStream();\nscaledThumb.Compress(Bitmap.CompressFormat.Jpeg, 50, stream);\nthis.byteArr = stream.ToArray();	0
31429687	31428847	select multiple values in combo box having dropdown without using checkbox	private void cbList_SelectionChanged(object sender, SelectionChangedEventArgs e)\n{\n    cbList.SelectedIndex = -1;\n}\n\nprivate void cbList_DropDownClosed(object sender, EventArgs e)\n{\n    foreach(CheckBox chk in cbList.Items){\n        if(chk.IsChecked.HasValue && chk.IsChecked.Value){\n            switch (chk.Content.ToString()) { \n                case "one":\n                    // Do something\n                    break;\n                case "two":\n                    // Do something\n                    break;\n                case "three":\n                    // Do something\n                    break;\n            }\n        }\n    }\n}	0
29563866	29563279	ListView cancel editItem	protected void Page_Load(object sender, EventArgs e)\n    {\n        if (!IsPostBack)\n        {\n             ListView1.EditIndex = -1;\n             ListView1.InsertItemPosition = InsertItemPosition.LastItem;\n        }\n    }	0
25420276	25419221	If - return is a huge bottleneck in my application	public class PlayerLocaiton\n{\n    Dictionary<Point, List<Player>> _playerLocation = new ...\n    public void SetPlayer(int x, int y, Player p)\n    {\n      _playerLocation[new Point(x,y)].add(p); \n    }\n\n    public Player GetSquareCache(int x, int y)\n    {\n      if (squaresCacheValid)\n      {\n           Player value;\n           Point p = new Point(x,y);\n           if(_playerLocation.TryGetValue(p, out value))\n           {\n                return value ;\n           }\n\n           return Player.None; \n      }\n      else\n        //generate square cache and retry...\n   }\n}	0
29391617	29391411	How To Determine Which Version of Excel last saved a Workbook	var excelWB = new OleDocumentPropertiesClass();\n excelWB.Open(FilePath, false, dsoFileOpenOptions.dsoOptionDefault);\n string FileUsedVersion = excelWB.SummaryProperties.Version.ToString();	0
28552072	28542513	Windows phone Text Boundaries	TextBlock t = new TextBlock();\nt.Text = "Lorum ipsum";\n\nDebug.WriteLine("Text {0} {1},{2}", t.Text, t.ActualWidth, t.ActualHeight);	0
32260748	32171860	how to pass datagridview value to another form	public partial class frmPatientsNameDuplicated : Form\n{\nPatientFiles frmPatientsFiles = Application.OpenForms["PatientFiles"] as PatientFiles;\npublic frmPatientsNameDuplicated()\n{\n    InitializeComponent();\n}\nprivate void btnCancel_Click(object sender, EventArgs e)\n{\n   this.Close();\n}\n\nprivate void btnOk_Click(object sender, EventArgs e)\n{\n   frmPatientsFiles.txtFileNum.Text = this.dgvPatientsName.CurrentRow.Cells[0].Value.ToString();\n   frmPatientsFiles.txtArbName.Text = this.dgvPatientsName.CurrentRow.Cells[1].Value.ToString();\n   frmPatientsFiles.txtEngName.Text = this.dgvPatientsName.CurrentRow.Cells[2].Value.ToString();\n   this.Close();\n}\n}	0
7350930	7350555	Parallel HttpWebRequests with Reactive Extensions	var svcObs = Observable.FromAsyncPattern<Stream>(this.BeginDownloadAttachment2, This.EndDownloadAttchment2);\n\nvar obs = from image in imagesToDownload.ToObservable()\n          from responseStream in svcObs(image)\n          .ObserveOnDispatcher()\n          .Do(response => image.FileContent = response.ReadToEnd())\n          select image;\nreturn obs;	0
11440750	11440671	I need to convert this SQL Query to LINQ so that I can use it inside my project	var Results = (from g in DB.Galleries\n               join m in DB.Media\n               on g.GalleryID equals m.GalleryID\n               group m by new { g.GalleryID, g.GalleryTitle, g.GalleryDate } into grp\n               orderby grp.Key.GalleryID descending\n               select new LatestGalleries\n               {\n                   GalleryID = grp.Key.GalleryID,\n                   GalleryTitle = grp.Key.GalleryTitle,\n                   GalleryDate = grp.Key.GalleryDate,\n                   MediaThumb = grp.FirstOrDefault().MediaThumb\n               });	0
22744796	22744714	BinaryFile Read to byte[]	using (var streamReader = new StreamReader(filePath))\n  {\n    string line;\n    while ((line = streamReader.ReadLine()) != null)\n    {\n      Console.WriteLine(line);\n    }\n  }	0
20254406	20254276	Parse HTML With C#	var markup = @"<span class=text14 id=""article_content""><!-- RELEVANTI_ARTICLE_START --><span ></b>The most important component for <a class=bluelink href=""http://www.ynetnews.com/articles/0,7340,L-3284752,00.html%20""' onmouseover='this.href=unescape(this.href)' target=_blank>Israel</a>'s security is its special relations with the American administration, and especially with its generous purse. When the Netanyahu government launches a great outcry against the</span>";\n\nvar doc = new HtmlDocument();\ndoc.LoadHtml(markup);\n\nvar content = doc.GetElementbyId("article_content").InnerText;\n\nConsole.WriteLine(content);	0
809884	709391	Remove title bar text of a window but keep status bar text	[DllImport("uxtheme.dll")]\npublic static extern int SetWindowThemeAttribute(IntPtr hWnd, WindowThemeAttributeType wtype, ref WTA_OPTIONS attributes, uint size);\n\npublic enum WindowThemeAttributeType : uint\n{\n    /// <summary>Non-client area window attributes will be set.</summary>\n    WTA_NONCLIENT = 1,\n}\n\npublic struct WTA_OPTIONS\n{\n    public uint Flags;\n    public uint Mask;\n}\npublic static uint WTNCA_NODRAWCAPTION = 0x00000001;\npublic static uint WTNCA_NODRAWICON = 0x00000002;\n\nWTA_OPTIONS wta = new WTA_OPTIONS() { Flags = WTNCA_NODRAWCAPTION | WTNCA_NODRAWICON, Mask = WTNCA_NODRAWCAPTION | WTNCA_NODRAWICON };\n\nSetWindowThemeAttribute(this.Handle, WindowThemeAttributeType.WTA_NONCLIENT, ref wta, (uint)Marshal.SizeOf(typeof(WTA_OPTIONS)));	0
25206263	25206179	Getting individual values from an element in a List	snake[5].Item1;	0
5549817	5549807	Get list of object with matching property	var results = listOfPerson.Where(\n    p => p.Name.StartsWith("pra", StringComparison.CurrentCultureIgnoreCase));\n\nforeach(Person p in results)\n{\n    ...\n}	0
27091105	27091048	How do I format the output of a nested JSON object with JSON.net?	string json = JsonConvert.SerializeObject(movieObject, Formatting.Indented);	0
18593206	18593150	Is it possible to restrict attribute usage to only certain interfaces?	typeof(someType).GetInterfaces().Contains(typeof(IAppModule))	0
27360876	27360806	How to Horizontalalign Center merged cells in EPPlus	worksheet.Cells["A2:A4"].Style.HorizontalAlignment = ExcelHorizontalAlignment.Center;	0
15390429	15389548	Bootstrap Modal fires but not ASP Button Click event	protected void TestButton_Click(object sender, EventArgs e)\n                    {\n\n                     // do something then call modal\nClientScript.RegisterStartupScript(GetType(), "Show", "<script> $('#example').modal('toggle');</script>");\n                    }	0
4705056	4704869	How to inject inside catch block to send exception email/sms/event log in C#	[Serializable]\npublic class FooException : Exception\n{\n    // Logger configured for email, file, etc.\n    static ILog _log = LogFactory.Create();\n\n    public FooException(string message, Exception innerException)\n        : base(message, innerException)\n    {\n        _log.Error(message, innerException);\n    }\n\n    // ...\n}\n\npublic class FooDataAccess<T> : IFooRepository\n{\n    public T GetFoo()\n    {\n        // Consider creating general helper methods with \n        // Action, Func, parameters so that you only have\n        // to code the try ... catch block once.\n        try\n        {              \n            // all exceptions caught\n        }\n        catch (Exception e)\n        {\n            throw new FooException(Exceptions.GetFooException, e);\n        }\n    }     \n}	0
24461104	24460971	Show some controls based on radio button choice	public class Form1 : Form\n{\n    public Form1()\n    {\n        InitializeComponent();\n        panel2.Location = panel1.Location;\n        .....\n    }\n}	0
9921005	9920916	Run a function every 100 iterations but also catch the last ones	if (counter % 100 != 0) \n{ \n    postgresSQLDBConnection.PostgreSQLExecutePureSqlNonQuery(postgresQuery.ToString()); \n\n    postgresQuery.Clear(); \n}	0
2252904	2252806	Binary addition of 2 values represented as strings	int number_one = Convert.ToInt32(a, 2);\nint number_two = Convert.ToInt32(b, 2);\n\nreturn Convert.ToString(number_one + number_two, 2);	0
8293615	8293275	How do I put my data in a stacked bar graph	myPane.BarSettings.Type = BarType.Stack;	0
29434278	29434043	How I can get the rowcount of a tableLayoutPanel from another form?	Form2 frm2 = new Form2();\nfrm2.show();\nint count = frm2.GetTableRowCount()\nbtn.Text  = count.ToString();	0
17052013	17051927	How do I use DllImport with a C++ class?	[DllImport(...)]	0
5160131	5160102	most efficient way to get various variables out of a string	var input = "...some_general_infomations,param1=value1,param2=value2,paramN=valueN";\nvar tokens = input.Split(',');\nif (tokens.Length > 0)\n{\n    foreach (var token in tokens)\n    {\n        var parts = token.Split('=');\n        if (parts.Length > 1)\n        {\n            string paramName = parts[0];\n            string paramValue = parts[1];\n        }\n    }\n}	0
489951	489937	In C# how do you accomplish the same thing as a #define	const int BUFFER_SIZE = 1024;	0
9002508	9002426	How to bind generic types with constraints	Bind(typeof(IRepository<>)).To(typeof(Repository<>));	0
7127446	7127168	How to change a cells content in UltraGrid	e.Cell.Row.Cells["StartDate"].Value = DateTime.Today; //or whatever your date is	0
21775921	21773730	Adding listener to MessageBox ok button in Windows Phone	Deployment.Current.Dispatcher.BeginInvoke(() => {\n            List<string> messageboxitm = new List<string>();\n            messageboxitm.Add("Yes");\n            messageboxitm.Add("No");\n            IAsyncResult result = Guide.BeginShowMessageBox("Message", "The alarm has been raised", messageboxitm, 0, MessageBoxIcon.Alert, new AsyncCallback(OnMessageBoxClosed), null);\n\n});\n private void OnMessageBoxClosed(IAsyncResult ar)\n        {\n            int? buttonIndex = Guide.EndShowMessageBox(ar);\n            switch (buttonIndex)\n            {\n                case 0:\n                   //Do your work\n                    break;               \n                default:\n                    break;\n            }\n        }	0
10475117	10474838	Not all parameters in WCF data contract make it through the web service call	[DataContract(Namespace="http://example.com/recordservice")]\npublic class Appointment\n{\n    [DataMember(Order = 1)]\n    public int ResponseType { get; set; }\n\n    [DataMember(Order = 2)]\n    public int ServiceType { get; set; }\n\n    [DataMember(Order = 3)]\n    public string ContactId { get; set; }\n\n    [DataMember(Order = 4)]\n    public string Location { get; set; }\n\n    [DataMember(Order = 5)]\n    public string Time { get; set; }        \n}	0
1367808	1367788	Testing using a guid... how do I set the variable to a Guid?	Guid x = new Guid("5fb7097c-335c-4d07-b4fd-000004e2d28c");	0
4588438	4588284	C# problem with multi-clients server application	public void listenForPeers()\n{\n  //Setup the server socket\n\n  while(true){\n    Socket newClient = serverSock.Accept();\n    if(newClient.Connected){\n      Thread tc = new Thread(new ParameterizedThreadStart(listenclient));\n      tc.start(newClient);\n    }\n  }\n}\n\nvoid listenclient(object clientSockObj)\n{\n  Socket clientSock = (Socket)clientSockObj;\n\n  //communication to client via clientSock.\n}	0
2637502	2637417	Best way to get a single value from a DataTable?	DataTable itemTbl = GetItemTable().AsEnumerable();\n\ndouble dt1 = ((From t In itemTbl Where t.Id = <your_id> Select t).First())["Data1"];	0
33454855	33453391	Error filter the table based on a date field	SqlDataReader DR = ExecuteReader(System.Data.CommandType.Text, "Select Sum(Price) From Tbl_Cost Where Dat Between @F AND @L", new SqlParameter[]\n            {\n                new SqlParameter("@F", firstDayOfMonth),\n                new SqlParameter("@L", lastDayOfMonth),\n            }	0
17186990	17170588	Upsert a list with Simple.Data	Database.Open().MySchema.MyTable.Upsert(list).ToArray();	0
11502475	11502381	How to learn and show gridview rows includes "?" data 	for (int i = 0; i < gv.Rows.Count; i++)\n        {\n            valueCount=0;\n            for (int j = 1; j < gv.Columns.Count; j++)\n            {\n              if (gv.Rows[i].Cells[j].ToString()!="")\n                  valueCount++;\n            }\n             gv.Rows[i].Cells[0].Text =valueCount.ToString();  \n        }	0
4826200	4825907	Convert Int to Guid	public static Guid ToGuid(int value)\n{\n    byte[] bytes = new byte[16];\n    BitConverter.GetBytes(value).CopyTo(bytes, 0);\n    return new Guid(bytes);\n}	0
9084352	9084309	how to add { in String Format c#	string s = String.Format("{{ hello to all }}");\nConsole.WriteLine(s);    //prints '{ hello to all }'	0
1110241	1106436	Compact Framework Current Folder	string fullAppName = Assembly.GetCallingAssembly().GetName().CodeBase;\nstring fullAppPath = Path.GetDirectoryName(fullAppName);	0
18098642	18098616	How to read computer's datetime format and change the code appropriately	DateTime myDate = DateTime.Now.AddDays(-1);	0
18506214	18488872	Azure - How to access content files of WorkerRole?	Path.Combine(Environment.GetEnvironmentVariable("RoleRoot") + @"\", @"approot\FileTemplates\");	0
28907788	28907703	Lambdas in Base Constructor Call	public class StructInputValidator<T> : InputValidator<T?> where T : struct\n{\n    public StructInputValidator(TryParse<T> parser, T? initialValue) \n        : base(ToNullableTryParse(parser), initialValue)\n    { }\n\n    private static TryParse<T?> ToNullableTryParse(TryParse<T> parser)\n    {\n        return (string text, out T? result) => {\n            T nonNullableResult;\n            bool parseSuccessful = parser(text, out nonNullableResult);\n            result = parseSuccessful ? (T?)nonNullableResult : null;\n            return parseSuccessful;\n        };\n    }\n}	0
13779246	13778859	Radio buttons change warning message	NewTrdButtonFemale.Checked -= new RoutedEventHandler(NewTrdButtonFemale_Checked);\n                    NewTrdButtonFemale.IsChecked = true;\n                    NewTrdButtonFemale.Checked += new RoutedEventHandler(NewTrdButtonFemale_Checked);	0
483335	483333	How to expose only one particular class from an assembly?	internal class C2\n{\n//...\n}	0
20898832	20898189	Mandrill API response with HTTP Status 500	Mandrill.EmailMessage message = new Mandrill.EmailMessage();\nmessage.from_email = _setting.UserName;\nmessage.from_name = "Whatever";\nmessage.html = body;\nmessage.subject = subject;\nmessage.to = new List<Mandrill.EmailAddress>()\n{\n    new Mandrill.EmailAddress(to, toDisplayName)\n};\n\nMandrill.MandrillApi mandrillApi = new Mandrill.MandrillApi(_setting.Password, false);\nvar results = mandrillApi.SendMessage(message);\n\nforeach (var result in results)\n{\n      if (result.Status != Mandrill.EmailResultStatus.Sent)\n           LogManager.Current.LogError(result.Email, "", "", "", null, string.Format("Email failed to send: {0}", result.RejectReason));\n}	0
6627847	6627126	How to comment out all script tags in an html document using HTML agility pack	foreach (var scriptTag in htmlDocument.DocumentNode.SelectNodes("//script"))\n        {\n            var commentedScript = HtmlTextNode.CreateNode(string.Format("<!--{0}-->", scriptTag.OuterHtml));\n            scriptTag.ParentNode.ReplaceChild(commentedScript, scriptTag);\n        }	0
27740655	27740545	Retrieve an ASP.NET cookie without the [key]= part	string strcookie=cookievalue.Split('=')[1];	0
28972633	28907885	Setting a variable via dropdownlist in order to limit an index view	Category: @Html.DropDownList("category", "All")	0
1495517	1495504	Get current application physical path within Application_Start	protected void Application_Start(object sender, EventArgs e)\n {\n     string path = Server.MapPath("/");\n     //or \n     string path2 = Server.MapPath("~");\n     //depends on your application needs\n\n }	0
11486103	11486066	manually exit from typing mode of textbox in WP7	button.focus();	0
27738661	27702849	What is an application adapters for hosted application in CCA?	AIF(application intregation frame work)	0
19617421	19605864	How to run an exe from a button click	System.Diagnostics.Process.Start("iReb.exe");	0
20680839	20680606	How to change the header of a DataGrid column in code behind?	dataGrid.Columns[0].Header = "New Header for column 0";	0
5273063	5272952	LINQ-to-XML: Selecting specific node value	IEnumerable<XElement> softDrinks=\n    from item in menu.Descendants("Drink")\n    where item.Attribute("key") == "SoftDrink" \n    select item;	0
19590800	19590491	supply a fallback value for TryFindResource in WPF	public static class FrameworkElementExtensions\n{\n  public static Object TryFindResourceEx(this FrameworkElement el, Object resourceKey)\n  {\n    var result = el.FindResource(resourceKey);\n\n    if(result == null)\n    {\n      // fallback handling here\n    }\n\n    return result;\n  }\n}	0
17354637	17354583	Get next element of an array on each call to a function	private int textboxNumber;\n\nprivate void timer1_Tick(object sender, EventArgs e)\n{\n    string[] s = new string[4];\n\n    s[0] = textBox1.Text;\n    s[1] = textBox2.Text;\n    s[2] = textBox3.Text;\n    s[3] = textBox4.Text;\n\n    webBrowser1.Navigate(s[textboxNumber]);\n\n    textboxNumber++;\n    if (textboxNumber > 3)\n        textboxNumber = 0;\n}	0
14063619	14059085	Issuing HEAD request with IRestClient in ServiceStack	if (HttpMethods.AllVerbs.Contains(httpVerb.ToUpper()))\n    throw new NotSupportedException("Unknown HTTP Method is not supported: " + httpVerb);	0
1162036	1161427	Apply attribute to property get/set methods via batch file	setlocal enabledelayedexpansion\nset outfile=%1.copy\ndel "%outfile%"\nfor /f "delims=" %%x in (%1) do (\n    set line=%%x\n    if "!line: =!"=="get{" (\n    echo [System.Diagnostics.DebuggerStepThrough^(^)]>>%outfile%\n    )\n    if "!line: =!"=="set{" (\n    echo [System.Diagnostics.DebuggerStepThrough^(^)]>>%outfile%\n    )\n    echo.%%x>>%outfile%\n)	0
13802569	13798449	How to convert NSRect/CGRect back to RectangleF in MonoTouch?	for(uint i = 0; i < oHighlightAnnot.Rects.Count; ++i)\n{\n    IntPtr ptrRect = oHighlightAnnot.Rects.ValueAt(i);\n    var val = new NSValue(ptrRect);\n    var rect = val.RectangleFValue;\n}	0
7545074	7545064	Customized list in C#	class MyList<T> : IList<T>\n{\n    private List<T> list = new List<T>();\n\n    public void Add(T item)\n    {\n        // your implementation here\n    }\n\n    // Other methods\n\n    public void Clear() { list.Clear(); }\n    // etc...\n}	0
21900053	21899118	how add to list of structure in c#	public struct blocks\n{\n    public Int32 xb;\n    public Int32 yb;\n    public Int32 size;\n};\n\nnamespace test\n{\n\n    class Program\n    {\n        static List<blocks> blocks1;\n        static void Main(string[] args)\n        {\n            blocks1 = new List<blocks>();\n            for (int y = 1; y < 5; y++)\n            {\n                for (int x = 1; x < 5; x++)\n                {\n                    blocks newBlock = new blocks();\n\n                    newBlock.xb = x * 2;\n                    newBlock.yb = y * 2;\n                    newBlock.size = 2;\n\n                    blocks1.Add(newBlock);\n                }\n            }\n        }\n    }\n}	0
4951141	4951095	Index of each occurrence of word in sentence	foreach(Match m in Regex.Matches(mystring, "dear", RegexOptions.IgnoreCase))\n{\n   Debug.Writeline(m.Index);\n}	0
9614093	9614069	Confused about multi-threading in a loop for C#	foreach (KeyValuePair<int, int> kvp in dataDict)\n{\n    var pair = kvp;\n    Console.WriteLine("Ready for [" + pair.Key.ToString() + "]");\n    Task.Factory.StartNew(() => DoSomething(pair.Value, pair.Key));\n}	0
1504495	1504383	How to reference xml file locally?	string filePath = ConfigurationManager.AppSettings["settingName"];	0
3367332	3367286	Displaying a listbox of viewboxes	var newViewBox = new ViewBox();	0
10098009	10098000	How to raise custom event correctly?	// The event...\npublic EventHandler<FileDetectedEventArgs> NewFileDetected;\n\n// Note the naming\nprotected void OnNewFileDetected(FileDetectedEventArgs e)\n{\n    // Note this pattern for thread safety...\n    EventHandler<FileDetectedEventArgs> handler = this.NewFileDetected; \n    if (handler != null)\n    {\n        handler(this, e);\n    }\n}	0
17514372	17514338	How to wire up event with reflection	MyEvent += (EventHandler)Delegate.CreateDelegate(typeof(EventHandler), aType, method);	0
34089103	34088841	In CRM Dynamics 2013 how can I retrieve a list of accounts and create phone call activities against them for specific users	Guid[] users = new Guid[] { <id1>, <id2>, <id3>, <id4>};\n\nvar counter = 0;\n\n        foreach (Entity account in response.Entities)\n        {\n            PhoneCall phone = new PhoneCall();\n\n            ActivityParty _from = new ActivityParty();\n            phone.OwnerId =\n            _from.PartyId = new EntityReference("systemuser", users[counter % 4]);\n\n            ActivityParty _to = new ActivityParty();\n            _to.PartyId = account.ToEntityReference();\n\n            phone.From = new ActivityParty[] { _from };\n            phone.DirectionCode = true;\n            phone.Subject = "phone call trial";\n            phone.To = new ActivityParty[] { _to };\n            service.Create(phone);\n\n            counter++;  \n        }	0
20939010	20938886	Drag multi item to the same text box	private void textBox1_DragEnter(object sender, System.Windows.Forms.DragEventArgs e)	0
18482735	18482161	Appropriate approach to supplier integration	public abstract class SupplierBase<TRequest, TResponse>\n    {\n        protected abstract TRequest generateRequest();\n        protected abstract TResponse sendRequest (TRequest request);\n        protected abstract CommonResponse mapResponse (TResponse request);\n\n        public CommonResponse process(TRequest request)\n        {\n            return mapResponse(sendRequest(generateRequest()));\n        }\n    }\n\n    // an implementing class...\n    public class SupplierA:SupplierBase<RequestA, ResponseA>\n    {\n        protected override RequestA generateRequest()\n        {\n            return new RequestA();\n        }\n\n        protected override ResponseA sendRequest(RequestA request)\n        {\n            // call with the request and return the specific response\n        }\n\n        protected override CommonResponse mapResponse(ResponseA request)\n        {\n            // map the specific response to the common response\n        }\n    }	0
5982262	5982128	How to reset the MSCHart values	chart.Series["MySeries"].Points.Clear();	0
8057239	8054705	Detect design mode in "OnApplyTemplate" method - custom control	if (System.ComponentModel.DesignerProperties.IsInDesignTool) return;	0
3541495	3541476	Insert Null value In DB	if(FU2.PostedFile.ContentLength == 0) \n{\n    SqlParameter UploadedImage2 = new SqlParameter("@Logo", SqlDbType.VarBinary, System.DBNull.Value);\n    Com.Parameters.Add(UploadedImage2);\n}	0
34137821	34137533	Detect datatable date field and force date format in EPPlus export	...\nwsDt.Cells["A1"].LoadFromDataTable(dt, true, TableStyles.None);\n\nint colNumber = 0;\n\nforeach (DataColumn col in dt.Columns) \n{\n\n    if (col.DataType == typeof(DateTime))\n    { \n         wsDt.Column(colNumber++).Style.Numberformat.Format = "mm/dd/yyyy hh:mm:ss AM/PM"\n    }          \n}\n\nwsDt.Cells[wsDt.Dimension.Address].AutoFitColumns();\nResponse.BinaryWrite(pck.GetAsByteArray());	0
21660798	21660732	Create same control of one already declared	object newobjcet = Activator.CreateInstance(comboBox1.GetType());	0
13241532	13241352	Convert loop to LINQ	sdata[0].DailyReturn = 0.0;\nsdata.GetRange(1, sdata.Count - 1).ForEach(c => c.DailyReturn = (sdata[sdata.IndexOf(c)-1].AdjClose / c.AdjClose) - 1);	0
24609246	24605196	Create MultiPolygon SqlGeography from Polygon SqlGeographys	List<SqlGeography> areaPolygons = GetAreaPolygons()\nSqlGeography multiPoly = null;\n\nSqlGeographyBuilder sqlbuilder = new SqlGeographyBuilder();\nsqlbuilder.SetSrid(4326);\nsqlbuilder.BeginGeography(OpenGisGeographyType.MultiPolygon);\n\nforeach (SqlGeography geog in areaPolygons)\n{\n    sqlbuilder.BeginGeography(OpenGisGeographyType.Polygon);\n\n    for (int i = 1; i <= geog.STNumPoints(); i++)\n        {\n            if (i == 1)\n                sqlbuilder.BeginFigure((double)geog.STPointN(i).Lat, (double)geog.STPointN(i).Long);\n            else\n                sqlbuilder.AddLine((double)geog.STPointN(i).Lat, (double)geog.STPointN(i).Long);\n        }\n\n        sqlbuilder.EndFigure();\n        sqlbuilder.EndGeography();\n}\n\nsqlbuilder.EndGeography();\nmultiPoly = sqlbuilder.ConstructedGeography;	0
10396891	8306866	Xml code in my database	ds.ReadXml(xmlPath);	0
25269520	25267343	How to Read XML Child	XDocument document = XDocument.Parse(responseFromServer);\n            var value = document.Descendants().Single(i => i.Attribute("token") != null)\n                           .Attribute("token").Value;	0
10504821	10504791	generating completely random even numbers with C#	textBox4.Text = (2 * rand.Next(min / 2, max / 2)).ToString();	0
29815004	29814951	Cannot convert varchar value to int in stored procedure in SQL Server	create procedure [dbo].[CreateNewTicket]\n(\n @Practice_Id as varchar(40),\n)\n/* insert some rows into TICKET table */\n\nAs Begin\nDECLARE @prctid as int\nSELECT @prctid = id from PRACTICE_DETAIL where Practice_Name_Description = @Practice_Id;\nend \nGO	0
4101583	4101539	C# removing strings from end of string	string[] remove = { "a", "am", "p", "pm" };\n        string inputText = "blalahpm";\n\n        foreach (string item in remove)\n            if (inputText.EndsWith(item))\n            {\n                inputText = inputText.Substring(0, inputText.LastIndexOf(item));\n                break; //only allow one match at most\n            }	0
15876023	15875957	How to get Header text as required in CSV file in Windows Application?	IEnumerable<string> columnNames = Enumerable.Range(0, sdr.FieldCount)\n                                             .Select(i => sdr.GetName(i));\n\n CsvfileWriter.WriteLine(string.Join(",", columnNames.ToArray()));	0
13175534	13174877	password data not appear in edit mode	registerAdminPasswod.Attributes.Add("value", ad.Password);	0
645146	645144	C#, StringToEnum, can I make it a generic function out of this	public static T StringToEnum<T>(String value)\n{\n     return (T)Enum.Parse(typeof(T), value, true);\n}	0
15208877	15207608	RegEx to capture execution time with specific text afterwards	Total execution Time: ([\d.]+).*\r?\n.*\r?\n.*\[Step 1\s	0
33300345	33299835	How to apply Null-Conditional Operator on blank strings?	decimal d = String.IsNullOrEmpty(str) ? default(decimal) : Convert.ToDecimal(str);	0
9412363	9412277	Obtaining a dataset from a SQL Server database	string CnStr=@"put_here_connection_string";\nSqlDataAdapter adp=new SqlDataAdapter("select * from tableName",CnStr);\nDataSet ds=new DataSet();\nadp.Fill(ds,"TableName");	0
11215890	11215713	How to download a CSV file from an ASP page after user clicks a button	sb.AppendLine();\nResponse.Write(sb.ToString());\n\nResponse.End();	0
30448927	30448739	Configurable Serial Tracking Number Generation	CREATE PROCEDURE GetSequenceOfWareHouse\n    @WareHouse char(2)\nAS\nBEGIN\n    SET NOCOUNT ON;\n\n    DECLARE @Result table (Sequence int)\n\n    BEGIN Tran\n        UPDATE SequenceTable SET Sequence = Sequence + 1 \n            OUTPUT inserted.Sequence INTO @Result \n        WHERE WareHouse = @WareHouse AND Month = YEAR(GETDATE()) * 100 + MONTH(GETDATE())\n\n        IF NOT EXISTS(SELECT * FROM @Result)\n            INSERT SequenceTable (Sequence, WareHouse, Month) \n                OUTPUT inserted.Sequence INTO @Result \n            VALUES (1, @WareHouse, YEAR(GETDATE()) * 100 + MONTH(GETDATE()))\n\n    COMMIT Tran\n\n    SELECT Sequence FROM @Result\n\nEND\nGO\n\n\nCREATE Table SequenceTable\n(\n    Sequence int,\n    WareHouse char(2),\n    Month int,\n\n    unique (Sequence, WareHouse, Month)\n)	0
1443645	1443625	Need to change FromEmail String when sending Email through SMTPClient	MailAddress from = new MailAddress("ben@contoso.com", "Ben Miller");\n  MailAddress to = new MailAddress("jane@contoso.com", "Jane Clayton");\n  MailMessage message = new MailMessage(from, to);	0
9687821	9687781	Trying (unsuccessfully) to get a DataGridView to reflect changes to underlying data	this.dataGridViewControlTable.DataBind();	0
31514731	31513979	DispatcherTimer to run randomly in WPF	private DispatcherTimer _timer = new DispatcherTimer();\nprivate Random rand = new Random();\n\npublic void InitAndStartTimer()\n{\n    _timer.Tick += dispatcherTimer_Tick;\n    _timer.Interval = TimeSpan.FromSeconds(rand.Next(1, 10)); // From 1 s to 10 s\n    _timer.Start();\n}\n\nprivate void dispatcherTimer_Tick(object sender, EventArgs e)\n{\n    _timer.Interval = TimeSpan.FromSeconds(rand.Next(1, 10)); // From 1 s to 10 s\n    // Do your work.\n}	0
33073684	33073651	C# Validate input as double	double abalbeginVal;\nbool parsed = double.TryParse(aBalBeginS, out abalbeginVal);\nif (parsed && abalbeginVal >=0.0)\n{\n    // We're good\n}\nelse\n{\n    // Did not pass check\n}	0
3879489	3879463	Parse a Number from Exponential Notation	decimal d = Decimal.Parse("1.2345E-02", System.Globalization.NumberStyles.Float);	0
4159129	4158988	algorithm to find the correct set of numbers	double [] numbers = new numbers[200];\n  numbers[0] = 123;\n  numbers[1] = 456; \n\n  //\n  // and so on.\n  //\n\n  var n0 = numbers;\n  var n1 = numbers.Skip(1);\n  var n2 = numbers.Skip(2);\n  var n3 = numbers.Skip(3);\n\n  var x = from a in n0\n          from b in n1\n          from c in n2\n          from d in n3\n          where a + b + c + d == 2341.42\n          select new { a1 = a, b1 = b, c1 = c, d1 = d };\n\n  foreach (var aa in x)\n  {\n    Console.WriteLine("{0}, {1}, {2}, {3}", aa.a1, aa.b1, aa.c1, aa.d1 );\n  }	0
942509	942481	Refactoring advice for big switches in C#	public void OnEditorViewMouseDown(Point mousePos)\n{\n  currentTool.OnEditorViewMouseDown(mousePos);\n}	0
11171832	11171774	why use string constructor with char array for constants?	string str1 = "lang";\nstring str2 = "lang";\nstring str3 = new String("lang".ToCharArray());\n\nConsole.WriteLine(object.ReferenceEquals(str1, str2));   // Output: true\nConsole.WriteLine(object.ReferenceEquals(str1, str3));   // Output: false	0
9682642	9682247	How to properly close connection to access database	void Dispose()\n{\n  this.dbConnection.Dispose();\n}	0
14771096	14770733	Read files from Stream	Stream xmlStream = System.Web.HttpContext.Current.Request.Files[0].InputStream;\nStream txtStream = System.Web.HttpContext.Current.Request.Files[1].InputStream;	0
15090214	15089291	How to use UTF-8 encoding in iTextSharp PDF Stamper?	public const string FONT = "c:/windows/fonts/arialbd.ttf";\nBaseFont bf = BaseFont.CreateFont(FONT, BaseFont.IDENTITY_H, BaseFont.EMBEDDED);	0
3369394	3369294	Html Agility Pack - loop through rows and columns	foreach(HtmlNode cell in doc.DocumentElement.SelectNodes("//tr[@name='display']/td")\n{\n   // get cell data\n}	0
19709052	19708889	how to update a particular value in json?	dynamic jsonObject = Newtonsoft.Json.JsonConvert.DeserializeObject(jsonString);\njsonObject.Status = true;\nvar modifiedJsonString = Newtonsoft.Json.JsonConvert.SerializeObject(jsonObject);	0
21784661	21784138	Sending json object to ASP.net C# from Android	[System.Web.Services.WebMethod()]\npublic String demo(string personInfo)\n{\n    var jss = new System.Web.Script.Serialization.JavaScriptSerializer();\n    var aPerson = jss.Deserialize<Person>(personInfo);	0
25248044	25247696	How do I find week numbers of a given date range in C#	var d1 = new DateTime(2014, 1, 1);\n  var d2 = new DateTime(2014, 1, 14);\n  var currentCulture = CultureInfo.CurrentCulture;\n  var weeks = new List<int>();\n\n  for (var dt = d1; dt < d2; dt =dt.AddDays(1))\n   {\n      var weekNo = currentCulture.Calendar.GetWeekOfYear(\n                            dt,\n                            currentCulture.DateTimeFormat.CalendarWeekRule,\n                            currentCulture.DateTimeFormat.FirstDayOfWeek);\n       if(!weeks.Contains(weekNo))\n         weeks.Add(weekNo);\n  }	0
6102262	6102179	How can I discover current endpoints of my c# application programmatically?	// Automagically find all client endpoints defined in app.config\nClientSection clientSection = \n    ConfigurationManager.GetSection("system.serviceModel/client") as ClientSection;\n\nChannelEndpointElementCollection endpointCollection =\n    clientSection.ElementInformation.Properties[string.Empty].Value as ChannelEndpointElementCollection;\nList<string> endpointNames = new List<string>();\nforeach (ChannelEndpointElement endpointElement in endpointCollection)\n{\n    endpointNames.Add(endpointElement.Name);\n}\n// use endpointNames somehow ...	0
2042032	2041998	C#, NUnit: How to deal with testing of exceptions and deferred execution	public IEnumerable<Dog> GrowAll(this IEnumerable<Puppy> puppies)\n{\n    if(subjects == null)\n        throw new ArgumentNullException("subjects");\n\n    return GrowAllImpl(puppies);\n}\n\nprivate IEnumerable<Dog> GrowAllImpl(this IEnumerable<Puppy> puppies)\n{\n    foreach(var puppy in puppies)\n        yield return puppy.Grow();\n}	0
5353856	5353802	cannot convert lambda expression to Func<T,TResult> while trying pass around an IQueryable<T>	repo.GetAllFromQuery(\n    x => x.Products.Where(p => p.ID > 5),\n    y => Assert.IsTrue(y.Count > 0));	0
14879233	14879199	Quick way to initialize list of numbered strings?	Enumerable.Range(1, 10).Select(i => "This is string number " + i).ToList();	0
19435924	19435747	Constant color change using WPF	System.Windows.Threading.DispatcherTimer dt = new System.Windows.Threading.DispatcherTimer();\ndt.Interval = TimeSpan.FromSeconds(1); //or whatever interval you want\n\ndt.Tick += (s, e) =>\n{ \n    rects[r.Next(0,3)].Fill = red;\n}	0
3414692	3414240	WPF: Control Visibility from Database / Prerender Hook	public static T FindVisualChildByName<T>(DependencyObject parent, string name) where T : DependencyObject\n    {\n        for (int i = 0; i < VisualTreeHelper.GetChildrenCount(parent); i++)\n        {\n            var child = VisualTreeHelper.GetChild(parent, i);\n            string controlName = child.GetValue(Control.NameProperty) as string;\n\n            if (controlName == name)\n            {\n                return child as T;\n            }\n            else\n            {\n                T result = FindVisualChildByName<T>(child, name);\n                if (result != null)\n                {\n                    return result;\n                }\n            }\n        }\n\n        return null;\n    }	0
18724061	18720582	Creating a IEqualityComparer<IEnumerable<T>>	public class MyClass\n{\n    public int ID { get; set; }\n    public string Name { get; set; }\n}\n\npublic class MyClassComparer : IEqualityComparer<MyClass>\n{\n    public bool Equals(MyClass x, MyClass y)\n    {\n        return x.ID == y.ID;\n    }\n\n    public int GetHashCode(MyClass obj)\n    {\n        return obj.ID.GetHashCode();\n    }\n}\n\npublic class ExampleTest\n{\n    [Fact]\n    public void TestForEquality()\n    {\n        var obj1 = new MyClass { ID = 42, Name = "Brad" };\n        var obj2 = new MyClass { ID = 42, Name = "Joe" };\n\n        Assert.Equal(new[] { obj1 }, new[] { obj2 }, new MyClassComparer());\n    }\n}	0
11158122	11157690	Call stored procedures in Oracle from C#	begin INTEGRATION.UnoxDataFix(:input, :retval); end;	0
18051422	18051355	repeatedly using a Local Variable with `using` statement vs. repeatedly calling a Non-Local Variable ?	{\n  UdpClient udpclient = new UdpClient();\n  try\n  {\n   if (connect == true && MuteMic.Checked == false)\n   {\n\n           udpclient.Send(e.Buffer, e.BytesRecorded, otherPartyIP.Address.ToString(), 1500);\n\n   }\n  }\n  finally\n  {\n    if (udpclient!= null)\n      ((IDisposable)udpclient).Dispose();\n  }\n}	0
10888527	10888504	Is there a way to try to guess the date from a filename and, if unable, to gracefully fail?	File.GetCreationTime	0
634585	634416	Concatenating each non-empty parameter and its value	string GetQueryString(Expression<Func<String, string>> exprTree )\n { \n     // walk expreTree.  \n     // exprTree.Body.Left.Name would be the name of the variable\n     // exprTree.Body.Left.Value would be it value.\n }\n\n string q = GetQueryString((str1, s2, MyS, YourS) => str1 + s2 + MyS + YourS);	0
16477114	16476258	Winrt app failed on app cert kit because of financial.dll	financial.dll	0
12562179	12544893	altering QueryString parameters / values	public void QuerStrModify(string CurrQS_ParamName, string NewQs_paramName, string NewPar_Value, bool redirectWithNewQuerySettings = false)\n{\n\n    // reflect to readonly property \n    PropertyInfo isReadOnly = typeof(System.Collections.Specialized.NameValueCollection).GetProperty("IsReadOnly", BindingFlags.Instance | BindingFlags.NonPublic);\n\n    // make collection editable \n    isReadOnly.SetValue(this.Request.QueryString, false, null);\n\n    // remove \n    this.Request.QueryString.Remove(CurrQS_ParamName);\n\n    // modify \n    this.Request.QueryString.Set(NewQs_paramName, NewPar_Value);\n\n    // make collection readonly again \n    isReadOnly.SetValue(this.Request.QueryString, true, null);\n    string FullUrl = Request.Url.AbsolutePath;\n    if (redirectWithNewQuerySettings)\n    {\n        Response.Redirect(string.Join("?", FullUrl, this.Request.QueryString));\n    }\n\n}	0
1445129	1444922	html agility pack remove children	functionBarNode.ParentNode.RemoveChild(functionBarNode, false)	0
25917868	25814353	TableLayoutPanel: set number of columns dynamically when windows resized	private void groupBox2_SizeChanged(object sender, EventArgs e)\n    {\n        int avaiableWidth = this.groupBox2.Width;\n        int maxLableWidth = 150; //button width = 140 + 10 margin\n        this.tlpButtons.ColumnCount = avaiableWidth / maxLableWidth;\n\n        List<ColumnStyle> stylesToRemove = new List<ColumnStyle>();\n        foreach (ColumnStyle style in tlpButtons.ColumnStyles)\n            stylesToRemove.Add(style);\n        foreach (ColumnStyle style in stylesToRemove)\n            tlpButtons.ColumnStyles.Remove(style);\n\n        for (int i = 0; i < this.tlpButtons.ColumnCount; i++)\n        {\n            ColumnStyle c = new ColumnStyle();\n            c.SizeType = SizeType.Percent;\n            c.Width = Convert.ToSingle(Math.Floor((decimal)100 / (decimal)this.tlpButtons.ColumnCount));\n            this.tlpButtons.ColumnStyles.Add(c);\n        }\n        this.tlpButtons.Refresh();            \n    }	0
11686726	11668980	Check Uncheck Checkbox column in Devexpres grid in Winform	public frmLoad()\n    {\n\n\n        InitializeComponent();\n\n\n        string DisplayQuery = "Select * from TableName";\n         MasterDs = SqlHelper.ExecuteDataset(CommonClass.ConnectionString, CommandType.Text, DisplayQuery);\n        MasterDs.Tables[0].Columns.Add("FLAG", typeof(string));\n\n        MainGrid.DataSource = MasterDs.Tables[0];\n        gridview.PopulateColumns();\n\n        gridview.Columns["ID"].VisibleIndex = -1;\n        gridview.Columns["FLAG"].VisibleIndex = -1;\n\n        DevExpress.XtraEditors.Repository.RepositoryItemCheckEdit selectnew = new DevExpress.XtraEditors.Repository.RepositoryItemCheckEdit();\n        gridview.Columns["ColName"].ColumnEdit = selectnew;\n        selectnew.NullText = "";\n        selectnew.ValueChecked = "Y";\n        selectnew.ValueUnchecked = "N";\n        selectnew.ValueGrayed = "-";\n\n    }	0
9785697	9785650	Using a string builder, i've read a file.. How do i find if the given string is present in the file or not?	using (System.IO.StreamReader Reader = new System.IO.StreamReader("C://myfile2.txt"))\n{\n      StringBuilder Sb = new StringBuilder();\n      string fileContent = Reader.ReadToEnd();\n       if (fileContent.Contains("your search text"))\n           return true;\n       else\n           return false;\n}	0
22079184	22078593	Incrementing a registration number composed of strings and letter	class foo\n{\n    public static string ToRep(int Year,int Num)\n    {\n        StringBuilder SB = new StringBuilder(Year.ToString());\n        SB.Append(":");\n        int DecPart = Num % 1000;\n        int Base26Part = Num / 1000;            \n        for(int x = 0 ; x < 3 ; x++)\n        {\n            char NewChar =(char)( 'A'+ Base26Part % 26); \n            Base26Part /= 26;                \n            SB.Insert(3,NewChar); \n        }\n        SB.Append(DecPart.ToString("000"));\n        return SB.ToString(); \n    }\n}	0
24708099	24707915	How to access a generic page class property from a master template	public interface IEOPHasProject { int? ProjectId { get; } }\n\npublic class EOPKeuzelijst<TEntity>\n    : EntityOverviewPage<TEntity> where TEntity : EntityBase,\n    IRR_ProjectId_N,\n    IRR_ObjectTypeId_N,\n    IEOPHasProject\n{\n    public Int32? ProjectId { get; set; }\n    public Int32? ObjectTypeId { get; set; }\n\n    // No more info needed..\n}\n\n\npublic partial class Keuzelijsten_Template : System.Web.UI.MasterPage\n{\n    private IEOPHasProject page;\n    protected void Page_Load(object sender, EventArgs e)\n    {\n        this.page = (IEOPHasProject)this.Page;\n        this.page.ProjectId // will work\n\n        Response.Write(this.Page.Title);\n    }\n}	0
21629871	20853480	Prevent WP WebBrowser from over scrolling	public MainPage()\n    {\n        InitializeComponent();\n        this.CordovaView.DisableBouncyScrolling = true;\n        //Splash_Screen();\n    }	0
8639733	8639585	How to set x509certificate in a WCF client?	channelFactory.Credentials.ServiceCertificate.DefaultCertificate = new X509Certificate2(this.Certificate);	0
258373	258355	Reflecting local variables	string dir = ...todo...\n    try\n    {\n        // some code\n    }\n    catch (Exception ex)\n    {\n        ex.Data.Add("dir", dir);\n        throw;\n    }	0
7778024	7778002	How can I set as "auto" a control size by C#?	TextBox1.Width = Unit.Percentage(100);	0
15159375	15159335	Programmatically go back	if (this.NavigationService.CanGoBack)\n{\n    this.NavigationService.GoBack();\n}	0
17564226	17563342	want submenu on right mouse click of ToolStripMenuItem - C#	// new menu, if you're using designer you should have it already\nContextMenuStrip mnu = new ContextMenuStrip();\n\n// new tool strip item\nToolStripMenuItem mnuItem1 = new ToolStripMenuItem();\nmnuItem1.Text = "Some text 1";\nmnuItem1.Name = "mnuItem1";\n\n// new submenu item\nToolStripMenuItem mnuItem2 = new ToolStripMenuItem();\nmnuItem2.Text = "Some text 2";\nmnuItem2.Name = "mnuItem2";\n\n// connect them...\nmnuItem1.DropDownItems.Add(mnuItem2);\nmnu.Add(mnuItem1);	0
4851862	4851743	Looping collection to find minimum	string[] tests = new string[] { "test(1)", "test(2)", "test(3)" };\n  int minimum = int.MaxValue;\n\n  foreach(string test in tests)\n  {\n    int num = ExtractNumber(test);\n    if (num < minimum)\n      minimum = num;\n  }\n\n  //now you have minimum that hold the minimum;	0
10494539	10494445	message sent when a window is shown	private void Window_IsVisibleChanged(object sender, DependencyPropertyChangedEventArgs e)\n{\n  if ((bool)e.NewValue == true)\n  {\n     //Do what you need here\n  }\n}	0
23846034	23845648	Embed asp.net with SQL Server reading data and changing textbox field	while(reader.Read())\n{\n    TextBox1.Text = reader["QUALITIES"].ToString();\n}	0
10298856	10298563	How to find label value (database coloumn) of repeater and change text on repeater_ItemDataBound event	protected void repeaterPatientList_ItemDataBound(object sender, RepeaterItemEventArgs e)\n    {\n\n        Label lblbirthDate = (Label)e.Item.FindControl("lblPatientsBirthDate");\n        if(lblbirthDate!= null)\n        {\n           DateTime d = DateTime.Parse(lblbirthDate.Text);\n           lblbirthDate.Text = d.ToString("dd-MMM-yyyy");\n        }\n    }	0
6428733	6428670	How to fix an application that has a problem with decimal separator	Thread.CurrentThread.CurrentCulture	0
31005676	31005125	C# String to Dataset	public String GetBookList()	0
8527217	8526565	Email on predefined template via outlook C#	private void CreateItemFromTemplate()\n{\n    Outlook.Folder folder =\n        Application.Session.GetDefaultFolder(\n        Outlook.OlDefaultFolders.olFolderDrafts) as Outlook.Folder;\n    Outlook.MailItem mail =\n        Application.CreateItemFromTemplate(\n        @""~/Content/emailTemplate/emailTemplate.oft", folder) as Outlook.MailItem;\n    mail.Subject = "Congratulations";\n    mail.Save();\n}	0
2279424	2277773	Tips on setting the window state of a Windows Forms window	// create instances of your child forms\n    Form2 f2 = new Form2();\n    Form3 f3 = new Form3();\n    Form4 f4 = new Form4();\n    Form5 f5 = new Form5();\n\n    private void MDIParentForm1_Load(object sender, EventArgs e)\n    {\n        f2.Text = "subForm1";\n        f3.Text = "subForm2";\n        f4.Text = "subForm3";\n        f5.Text = "subForm4";\n\n        f2.MdiParent = this;\n        f3.MdiParent = this;\n        f4.MdiParent = this;\n        f5.MdiParent = this;\n\n        f2.Dock = DockStyle.Fill;\n        f3.Dock = DockStyle.Fill;\n        f4.Dock = DockStyle.Fill;\n        f5.Dock = DockStyle.Fill;\n\n        f2.Show();\n        f3.Show();\n        f4.Show();\n        f5.Show();\n    }	0
19569026	19568539	How to generate line chart from datatable c# winform	'Create & Format Chart\nDim oChart As Excel.Chart\n\noChart = oXL.Parent.Charts.Add\nWith oChart\n    .Name = "History"\n    .HasTitle = True\n    .ChartTitle.Font.ColorIndex = 11\n    .ChartTitle.Font.Bold = True\n    .ChartTitle.Font.Size = 12\n    .ChartTitle.Font.Name = "Arial"\n    .ChartTitle.Text = "Job History"\n    .ChartType = Excel.XlChartType.xlLine\n    .HasLegend = True\n    .SeriesCollection(1).XValues = "=Sheet1!$A$4:$A$6"\n    .SeriesCollection(1).Name = "=Sheet1!$B$3"\n    .SeriesCollection(2).Name = "=Sheet1!$C$3"\n    .SeriesCollection(3).Name = "=Sheet1!$D$3"\nEnd With	0
17877779	17858712	Image to string	foreach (Article article in NewsList.Result.Articles)\n{\n    NewsListBoxItem NLBI = new NewsListBoxItem();\n    NLBI.Title.Text = article.Title;\n    NLBI.Date.Text = US.UnixDateToNormal(article.Date.ToString());\n    NLBI.id.Text = article.Id.ToString();\n    if (article.ImageURL != null)\n    {\n        BitmapImage image = new BitmapImage(new Uri(article.ImageURL));\n        image.ImageOpened += (s, e) =>\n            {\n                byte[] bytearray = null;\n                using (MemoryStream ms = new MemoryStream())\n                {\n                    WriteableBitmap wbitmp = new WriteableBitmap(image );\n                    wbitmp .SaveJpeg(ms, wbitmp.PixelWidth, wbitmp.PixelHeight, 0, 100);\n                    bytearray = ms.ToArray();\n                }\n                string str = Convert.ToBase64String(bytearray);\n            };\n        NLBI.Thumbnail.Source = image;\n    }\n    NewsListBox.Items.Add(NLBI);\n}	0
14030022	14012950	Get treenode from contextmenu-item eventHandler	TreeNode needed = TreeViewX.SelectedNode;	0
6923927	6923763	How to get CPU frequency in c#	var searcher = new ManagementObjectSearcher(\n            "select MaxClockSpeed from Win32_Processor");\n foreach (var item in searcher.Get())\n {\n      var clockSpeed = (uint)item["MaxClockSpeed"];\n }	0
8412701	8412610	List add extension with properties	public static class TestModelListExtensions\n{\n    public static void Add(this List<TestModel> list, int test1, string test2)\n    {\n        list.Add(new TestModel { Test1 = test1, Test2 = test2 });  \n    }\n}\n\nclass Program\n{\n\n    static void Main(string[] args)\n    {\n        List<TestModel> list = new List<TestModel>();\n        list.Add(1, "hello");\n    }\n}	0
10749684	10749654	Access Resources on Runtime and get Strings	String str = context.getResources().getString(R.string.NewOrder);	0
17788006	17787923	How to check folder type in Outlook	if (item.GetType() == typeof( Outlook.MailItem )) {\n    Outlook.MailItem mi = (Outlook.MailItem)item;	0
28429708	28429592	I don't know how to get rows from excel file using Range	(Excel.Worksheet)xlWorkBook.Worksheets.get_Item(cmbSheetName.SelectedIndex + 1);	0
1948614	1948585	How do I connect to a local Socket in C#?	Mono.Unix.UnixEndPoint	0
7360021	7359973	Better pattern than nested if statements for flow control	if (FileHandler.CheckIfNewFilesExist(sourceFolderPath)\n    && FileHandler.MoveFolder(sourceFolderPath, temporyFolderPath)\n    && CSVHandler.AppendUniqueIdToCSV(temporyFolderPath, filesToBeAppended))            \n{\n    FileHandler.CopyFolder(temporyFolderPath, finalFolderPath);\n}	0
13960016	13959920	In C#, why do interface implementations have to implement a another version of a method explicitly?	public interface IFoo<T> where T : IFoo<T>\n{\n    T Bar();\n}\n\npublic class Foo : IFoo<Foo>\n{\n    public Foo Bar()\n    {\n        //...\n    }\n}	0
16810079	16809822	Reduce excel generation time while dumping data from Datable to Excel	var fieldNames = dt.Columns.Cast<DataColumn>()\n                           .Select(x => x.ColumnName).ToArray();	0
6314757	6314640	Getting wrong data from LINQ to Entities query	List<cat> lst = (from x in objEntity.cat\nwhere objEntity.cat_ven_rel.where(y => y.ven.ven_id==venid).select(y => y.cat_id).contains(x.cat_id)\nselect x).ToList();	0
14309379	14309348	writing c# for loop to page	MyLit.Text += i.ToString + "<BR />"	0
24726587	24726572	How do you get someone's IP in ASP.NET?	Request.UserHostAddress	0
1804767	1804765	insert text between 2 controls	tableCell.Controls.Add(DropDownListOraInizio);    \ntableCell.Controls.Add(new LiteralControl(":"));      \ntableCell.Controls.Add(DropDownListMinutoInizio);	0
4922622	4922577	How can I check if a sequence of values is correctly ordered?	private static bool isValid(params Action[] actions)\n{\n  for (int i = 1; i < actions.Length; i++)\n    if (actions[i-1].TimeStamp >= actions[i].TimeStamp)\n      return false;\n  return true;\n}\n\nAssert.IsTrue(isValid(a1,a2,...,an));	0
5028417	5028391	Change datagridview cell color by clicking in c#(winform)	private void GridView_CellClick(object sender, DataGridViewCellEventArgs e){\n\n        DataGridViewCellStyle CellStyle = new DataGridViewCellStyle();\n        CellStyle.BackColor = Color.Red;\n        dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Style = CellStyle;\n\n    }	0
12591862	12591790	How do I make a request to an API Controller from another Controller in MVC4?	protected IRestResponse GetResponse(int a, int b)\n    {\n        var client = new RestClient\n        {\n            BaseUrl = "http://localhost:8888/api/FooController"\n        };\n        var request = new RestRequest\n        {\n            DateFormat = DataFormat.Xml.ToString(),\n            Resource = "Add",\n            Method = Method.GET\n        };\n        request.AddParameter("application/json",\n            JsonSerializer.JsonSerialize(new {a, b}),\n            ParameterType.RequestBody);\n        return client.Execute(request);\n    }	0
3366143	3366123	SQL CE 3.5 - Writing to a database	using (SqlCeConnection connect = new SqlCeConnection("Data Source=C:\\Users\\mike\\Documents\\database.sdf"))\n    {\n        connect.Open();\n\n        string text = "test";\n        int num = 0;\n\n        using (SqlCeCommand command = new SqlCeCommand("insert into Data Table values (@Value, @Text)", connect))\n        {\n           command.Parameters.Add("@Value", SqlDbType.NVarChar, num);\n           command.Parameters.Add("@Text", SqlDbType.NVarChar, text);\n           command.ExecuteNonQuery();\n        }\n    }	0
15762967	15762828	Datagridview's rowindex keeps resetting after filling dataset with a tableadapter	int rowindex=datagridview.CurrentRow.Index;\nthis.gASFLESSENTableAdapter.Fill(this.dataSet1.GASFLESSEN);\ndatagridview.Rows[rowindex].Selected=true	0
5455564	5454227	Using pre-existing iqueryable to filter another iqueryable on Entity Framework	var filteredcategories = FilterSites(siteWord).SelectMany(s => s.Categories);	0
33216666	33216617	Implementing asyncronous tasks recalled on time intervals	Task.Delay	0
19391631	19391079	How can i use display information in a label acording to min and max values i put in a textbox c# wpf	int text = int.Parse(TextBoxName.text);\nif(text>50 && text<60)\n{\n  LableName.text="Good";\n}	0
21575816	21575053	Slice a C#-Hashset	int batchSize = 1024;\n\nforeach (var batch in myHashSet.Batch(batchSize))\n{\n    foreach (var item in batch)\n    {\n        ...\n    } \n}	0
14106194	14106152	Display data from a database without specifying columns	StringBuilder sb = new StringBuilder(1024); /* arbitrary size */\nwhile (reader.read())\n{\n    for (int i = 0; i < reader.FieldCount; i++)\n    {\n        sb.Append(reader.GetName(i));\n        sb.Append(": ");\n        sb.Append(reader[i]);\n    }\n    sb.Append("<br />");\n}\nlblResult.Text = sb.ToString();	0
2623560	2622913	Query JSON String	public T getFromJSON<T>(String sel, String jSon)\n    {\n        String[] id = sel.Split('.');\n        Object tmp = jSon;\n\n        for (int i = 0; i < id.Length; i++)\n        {\n            tmp = tmp.ToString().Split(new string[] { "\"" + id[i] + "\":" }, StringSplitOptions.None)[1];\n        }\n\n        Boolean isString = false;\n        if (tmp.ToString().StartsWith("\""))\n        {\n            tmp = tmp.ToString().Substring(1);\n            isString = true;\n        }\n\n        tmp = tmp.ToString().Split(new char[] { '}', ']', '"' }, StringSplitOptions.None)[0];\n\n        if (!isString && tmp.ToString().EndsWith(","))\n            tmp = tmp.ToString().Substring(0, tmp.ToString().Length - 1);\n\n        if (typeof(T) == typeof(Int32))\n            tmp = Int32.Parse(tmp.ToString());\n\n        return (T)tmp;\n    }	0
32903358	32902874	to write a two words to csv which when opened will show as two lines in one excel column	"\"Hallo" + (char)10 + "World\""	0
27572651	27572279	using connection string at runtime	SqlConnectionStringBuilder sqlStringBuilder = new SqlConnectionStringBuilder();\nsqlStringBuilder.Database = "database name":\nsqlStringBuilder.Password = "password";\nsqlStringBuilder.UserID = "userid";\n// other properties\n\nEntityConnectionStringBuilder entityStringBuilder = new EntityConnectionStringBuilder();\nentityStringBuilder.ProviderConnectionString = sqlBuilder.ConnectionString;\nentityStringBuilder.Provider = "System.Data.MySqlClient";\nentityStringBuilder.Metadata = "resx//*/YourDbContext.csdl|resx//*/YourDbContext.ssdl|resx//*/YourDbContext.msl";\n\nMyDbContext dbContext = new MyDbContext(entityStringBuilder.ConnectionString);	0
13952839	13952804	Set Column Header Name in XAML- WPF	AutoGenerateColumns="True"	0
14227592	14227537	How can I create semi dynamic byte array	static byte[] Get(byte num)\n    {\n        byte[] a = new byte[num + 2];\n        a[0] = 0x88;\n        a[1] = num;\n        return a;\n    }	0
11631468	11631330	c# dynamically pass string method at run time for string manipulation	var method = "ToLower()";\nvar methodInfo = typeof(String).GetMethod(method);\nvar string = "foo";\nstring.GetType().InvokeMember(....);	0
12801093	12748402	Textbox in data repeater made invisible does not mantain its view during scroll	if (((Label)dataRepeater.CurrentItem.Controls["DataTypeLabel"]).Text    == "AutoIncrement")                  \n{                      \n\n ((TextBox)dataRepeater.CurrentItem.Controls["ValueTextBox"]).Visible = false;             \n\n}      \n\nelse\n{\n ((TextBox)dataRepeater.CurrentItem.Controls["ValueTextBox"]).Visible = true;         \n}	0
9945685	9945628	How can i pass/use private variables froma class in Form1 with a public function?	public List<float> PointX { get { return Point_X; } }\npublic List<float> PointY { get { return Point_Y; } }	0
12776085	12775669	how to add image in Rich TextBox in VB.NET	Image img = Image.FromFile(filename); //if you want to load it from file...\nClipboard.SetImage(img);            \nrichTextBox1.Paste();\nrichTextBox1.AppendText("your text");	0
20510933	20510629	Data strings not Comparing	string dateNow = DateTime.Now.ToString("dd/MM/yyyy");\n\nstring dbcommand = "SELECT log.logID, log.datetime, log.startfloor, log.destination, log.status FROM log WHERE format(log.datetime,'dd/MM/yyyy') = '" + dateNow + "'";	0
16133124	16132983	How main WPF window knows when secondary WPF window is closed	public void CreateNewWindow()\n   {\n       Window wind=new Window();\n       wind.Closing+=yourClosingHandler;\n   }\n\n\n\n   void yourClosingHandler(object sender, CancelEventArgs e)\n   {\n     //do some staff\n   }	0
33700569	33700325	Linq to XML Select All Parent and Child Items	var allCats = categories.Descendants("child-cat")\n    .Select(c => new\n    {\n        parentId = c.Parent.Parent.Element("parent-id").Value,\n        parentName = c.Parent.Parent.Element("parent-name").Value,\n        childId = c.Element("child-id").Value,\n        childName = c.Element("child-name").Value\n    })\n    .ToList();	0
20916677	20916482	Concat arrays at a certain index with LINQ?	Array.Copy(groups, 0, names, at,groups.Length);	0
5787262	5787072	How do I parse constructor parameter to ViewModel using empty codebehind file	IDatabase _db	0
24612861	24612726	C# change multiple labels by looping	private void SetSensorUnitLabels(GroupBox currentGB, string newUnit)\n{\n    foreach (Label ctrl in currentGB.Controls.OfType<Label>())\n    {\n       ctrl.Text = newUnit;\n    }\n}\n\n\nSetSensorUnitLabels(groupBoxSensor1, units.celsius);\nSetSensorUnitLabels(groupBoxSensor2, units.celsius);	0
24661638	24660140	how to iterate over json data recursively	string S = JSON;\njavascriptserializer js = new javascriptserializer();\nRootObject o = js.deserialize<RootObject>(S);\n\ndim S a string=JSON 'your json string\ndim jsas new javascriptserializer\ndim o as RootObject=js.deserialize(of RootObject)(s)	0
15667893	15667817	how do i can first click changing button image and second click show preview image (first image for button)?	int ImageNum = 1;\n\n    private void button1_MouseDown(object sender, MouseEventArgs e)\n    {\n        if (ImageNum == 1)\n        {\n            button1.Image = Image2;\n            ImageNum = 2;\n        }\n        else\n        {\n            button1.Image = Image1;\n            ImageNum = 1;\n        }\n    }	0
23512086	23511778	How to call code from SQL in C#	using (SqlCommand cmd = new SqlCommand("MyStoredProcedure", connection))\n{\n    cmd.CommandType = CommandType.StoredProcedure;\n    cmd.Parameters.AddWithValue("@myParameter1", value);\n    ...\n\n    using (SqlDataReader reader = cmd.ExecuteReader())\n    {\n       ...\n    }\n}	0
11025140	11020426	How to programmatically refresh wpf c#?	ObservableCollection<AppointmentDTO> _appointments;\npublic ObservableCollection<AppointmentDTO> Appointments\n{\n    get\n    {\n        return _appointments;\n    }\n    set\n    {\n        if (_appointments != value)\n        {\n            if (_appointments != null)\n                _appointments.CollectionChanged -= Appointments_CollectionChanged;\n\n            _appointments = value;\n\n            if (PropertyChanged != null)\n                PropertyChanged(this, new PropertyChangedEventArgs("HasSchedule"));\n\n            if (_appointments != null)\n                _appointments.CollectionChanged += Appointments_CollectionChanged;\n        }\n    }\n}\n\nvoid Appointments_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)\n{\n    if (PropertyChanged != null)\n        PropertyChanged(this, new PropertyChangedEventArgs("HasSchedule"));\n}	0
22426199	22426162	In c#, if I have already declared an array of length n, how can I add another element on to it, making it of length (n+1)?	List<Form> Runners = new List<Form>();\n\n...\n\nRunners.Add(app);	0
29130507	29129324	C# XML Read All Child Nodes Of A Specific Node	textBox1.Text = xNode.ParentNode.ChildNodes.SelectSingleNode("age").InnerText;	0
27500766	27496058	Emgu: Setting up CUDA with C#	using System.Threading;\nusing System.Threading.Tasks;\n\nParallel.For(0, facesDetected.Length, i =>\n            {\n                try\n                {\n                // Code in here\n                }\n                catch\n                {\n                }\n            });	0
23227079	23223413	Link SQL Server Table Into Access	string path = "path to Access database";\nDAO.Database dd;\nDAO.DBEngine db = new DAO.DBEngine();\nDAO.TableDef tdf - new DAO.TableDef();\ndd.db.OpenDatabase(path);\ntdf = dd.CreateTableDef();\ntdf.Name = "Whatever you want the linked table to be named";\ntdf.Connect = "ODBC;Driver=SQL Server;Server=<Server Name>;Database=<DB NAME>;Trusted_Connection=YES";\ntdf.SourceTableName = "Whatever the SQL Server Table Name is";\ndd.TableDefs.Append(tdf);	0
7492282	7476536	Only add to List if there is a match	StreamWriter sw2 = new StreamWriter(saveFile2.FileName);\nBoolean partMatch = false;\nBoolean isAMatch = false;\nList<string> newLines = new List<string>();\nstring[] splitDataBaseLines = dataBase2FileRTB.Text.Split('\n');\n\nforeach (var item in theOtherList)\n{\n    foreach (var line in splitDataBaseLines)\n    {\n        if (line.StartsWith("Component : "))\n        {\n            partNumberMatch = line.Split(':');\n            partNumberMatch[1] = partNumberMatch[1].Remove(0,2);\n            partNumberMatch[1] = partNumberMatch[1].TrimEnd('"');\n\n            if (partNumberMatch[1].Equals(item.PartNumber))\n            {\n                isAMatch = true;\n                sw2.WriteLine();\n            }\n\n            partMatch = true;\n        }\n\n        if (line.Equals(""))\n        {\n            partMatch = false;\n            isAMatch = false;\n        }\n\n        if (partMatch == true && isAMatch == true)\n            sw2.WriteLine(line);\n    }\n}\nsw2.Close();	0
22552289	22537082	nHibernate generate Guid for Id but property as string	public class User : IUser\n{\n  public virtual Guid Id { get; set; }\n  string IUser.Id{get{return this.Id.ToString();}}\n  public virtual string UserName { get; set; }\n}	0
22512227	22511758	How to properly resolve RedirectToAction from throwing Object Not Set To Instance	public ActionResult Membership()\n{\n     var memberDetails = MemberDetails.GetMembershipDetails(userid);\n\n     var memberLevel = memberDetails.MemberLevel;\n     switch (memberLevel)\n     {\n         default:\n         case 0:\n             return View("Basic", memberDetails);\n         case 1:\n             return View("Gold", memberDetails);\n         case 2:\n             return View("Platinum", memberDetails);\n     }\n}	0
14094550	14094388	In Windows Phone 8, How can i get the Background Color property of a button?	Color MyColor = ((SolidColorBrush)btn.Background).Color;	0
15623108	15623031	How to read a SQL Function Value By SQL Data Reader in C#	string leftCount = dr["Left Count"].ToString();\nstring rightCount = dr["Right Count"].ToString();	0
34071337	34069618	mailto attachments in Windows 10	Windows.ApplicationModel.Email.EmailMessage	0
449598	449513	Removing characters from strings with LINQ	public static string Remove(this string s, IEnumerable<char> chars)\n{\n    return new string(s.Where(c => !chars.Contains(c)).ToArray());\n}	0
12478614	12474369	Show the user how many remaining chars left to him on a memoEdit	void me_EditValueChanging(object sender, DevExpress.XtraEditors.Controls.ChangingEventArgs e)\n{\n   var memo = (sender as MemoEdit);\n   var maxChars = memo.Properties.MaxLength;\n   lblContactWithCharCount.Text = memo.Text.Length + "/" + maxChars;\n}	0
3647216	3646309	Updating a 2nd window control from events in an object created in the 1st window	BackgroundWorker bgWorker = new BackgroundWorker() { WorkerReportsProgress=true};\nbgWorker.DoWork += (s, e) => {\n    // Load here your file/s\n    // Use bgWorker.ReportProgress(); to report the current progress\n};\nbgWorker.ProgressChanged+=(s,e)=>{\n    // Here you will be informed about progress \n    //  (if bgWorker.ReportProgress() was called in DoWork)\n};\nbgWorker.RunWorkerCompleted += (s, e) => {\n    // Here you will be informed if the job is done\n};\nbgWorker.RunWorkerAsync();	0
3721048	3720946	Adding Items To A ListView From A Different Thread? (Cross-thread operation not valid)	private delegate void AddItemCallback(object o);\n\nprivate void AddItem(object o)\n{\n    if (this.listView.InvokeRequired)\n    {\n        AddItemCallback d = new AddItemCallback(AddItem);\n        this.Invoke(d, new object[] { o });\n    }\n    else\n    {\n        // code that adds item to listView (in this case $o)\n    }\n}	0
1820605	1819381	How to add a Hyperlink to a dynamic gridview column	protected void grdData_RowDataBound(object sender, GridViewRowEventArgs e)\n    {\n        if (e.Row.RowType == DataControlRowType.DataRow)\n        {\n            HyperLink link = new HyperLink();\n            link.Text = "This is a link!";\n            link.NavigateUrl = "Navigate somewhere based on data: " + e.Row.DataItem;\n            e.Row.Cells[ColumnIndex.Column1].Controls.Add(link);\n        }\n    }	0
14181400	14181315	passing the data to the selected cell of datagridview	private void editToolStripMenuItem_Click(object sender, EventArgs e)\n{\n form2 f2 = new form2();\n f2.label1.Text = dataGridView1.SelectedCells[0].Value.ToString();\n f2.ShowDialog();\n dataGridView1.SelectedCells[0].Value = f2.textBox1.Text;\n}\n\nprivate void button1_Click(object sender, EventArgs e)\n{\n    DialogResult = DialogResult.OK;\n}	0
4848027	4847993	How to set the DataGridViewCell to automatically word wrap?	DataGridView.AutoSizeRowsMode = DataGridViewAutoSizeRowsMode.AllCells	0
16622160	16604667	Log4net not inserting data into table - neither shows any error	log4net.Config.XmlConfigurator.Configure(new System.IO.FileInfo(sFIleName + "\\log4net.xml"));	0
7076786	7075816	How to use Enums with Dynamic Linq?	houses.AsQueryable<House>()\n    .Where("MainRoom.Type = ConsoleApplication2.RoomType.Kitchen")	0
13456235	13456031	Find the node that has no children. If it has any <span> children, just ignore it	var nodes  = doc.DocumentNode\n            .SelectNodes("//div[@class='address' and h3='Postadress']/div[@class='post-address']");	0
2742726	2742704	need to get total rows of a grid	gridView.Rows.Count\n\ngridView.SelectedIndex  -- gives the index of the current row.	0
19123010	19118881	force to bring excel window to the front?	app.ActiveWindow.Activate();	0
30289563	30289229	When removing model data from a db everything but the primary key is getting deleted, how can i remove all of it?	void RemoveExercises(UserExerciseViewModel model, int id)\n{\n    var userExerciseViewModel = (UserExerciseViewModel)(Session["UserExerciseViewModel"]);\n    foreach (int selected in model.RequestedSelected)\n    {\n        if (model.RequestedSelected != null)\n        {\n            User user = db.Users.Find(id);\n            RegimeItem item = db.RegimeItems.Find(selected);\n            item.RegimeExercise = this.GetAllExercises().FirstOrDefault(i => i.ExerciseID == selected); //--this removes the regimeexercise\n            user.RegimeItems.Remove(item); //deletes the user's regimeitem\n            db.RegimeItems.Remove(item); //removes the regimeitem itself \n        }\n    }\n    db.SaveChanges();\n}	0
17445223	17445197	C# How to Detect excel 2003 professional edition is installed?	ManagementObjectSearcher mos = new ManagementObjectSearcher("SELECT * FROM Win32_Product");\n                foreach (ManagementObject mo in mos.Get())\n                {\n                if (mo["Name"] != null)\n                {\n                    string ProductName = mo["Name"].ToString();\n                }\n\n            }	0
1733645	1730032	Getting a byte array from out of process C++ COM to C#	byte[] buffer = new byte[100];\nIntPtr ptr = Marshall.AllocHGlobal( sizeof(int) );\nstream.Read( buffer, 100, ptr );	0
3148406	3148242	How to add child node to the root element in an XML file using C#	XmlElement XEle = XDOC.CreateElement("Child");\nXEle.SetAttribute("Name", Str[Index]);\nTestChild.AppendChild(XEle);\nRootNode.AppendChild(XEle.Clone());	0
15485382	15485122	InvalidArgument=Value of '0' is not valid for 'index'. Parameter name: index	people.RemoveAt(listView1.SelectedItems[0].Index); // removes item from people LIST.\nlistView1.Items.Remove(listView1.SelectedItems[0]); // removes item/person from LISTVIEW	0
6392699	6392653	fastest way to create Average array from multiple arrays of numbers	float[] sums = new float[4];\n\nfor(int i = 0; i < 4; i++)\n{\n    sums[i] = (array1[i]+ array2[i] + array3[i] + array4[i])/4;\n}	0
19305114	19305008	How to sense a network connection and trigger an event	NetworkChange.NetworkAvailabilityChanged	0
20305151	20305026	How to create a json array in aspx	string json = context.Response.Write(Json(new { \n    sEcho = 1, \n    iTotalRecords = "57", \n    iTotalDisplayRecords = "57", \n    aaData = new List<List<String>>\n    { new List<String>{ "Gecko", "Firefox 1.0", "Win 98+ / OSX.2+", "1.7", "A" }}\n}, JsonRequestBehavior.AllowGet));	0
19081489	19079023	Get SIZE of String in iOS 7	var tv = new UITextView() {\n    Text = "Some text",\n    Font = UIFont.PreferredBody\n};\n//Pass in a maximum size (in this case, vastly larger than needed)\nvar neededSize = tv.SizeThatFits(new SizeF(1000, 1000));\nConsole.WriteLine(neededSize);	0
24650259	24650109	How to change the DateTime format in a JQuery view of a C#\.NET web application?	value="@Model.LastUpdated.ToShortDateString()"	0
7018855	6983609	Regenerate Code-First database without adding any data	Database.SetInitializer(new DropCreateDatabaseAlways<MyDbContext>());         \nusing (var myContext = MyDbContext.GetContext("connectionString")) \n{           \n    context.Database.Initialize(force: true);      \n}	0
5411390	5409904	C# - using TableAdapter to return a single value from stored procedure returns null	DECLARE @r int\nSET @r = 7\nSELECT @r	0
31895547	31895460	Find items in multiple list?	if (List1.Any(o=>o.Name == selectedObject)\n{\n    //do...\n}\nelse if (List2.Any(o=>o.Name == selectedObject)\n{\n    //do...\n}\nelse if (List3.Any(o=>o.Name == selectedObject)\n{\n    //do...\n}	0
25617872	25617809	How to add comma into number in c#	123123123123.ToString("#,#", new NumberFormatInfo() { NumberGroupSizes = new[] { 2 } })	0
22786151	22785445	Deserialize json into class in C#	user =  new JavaScriptSerializer().Deserialize<A>( a );	0
6446425	6446296	Querying a join table using LINQ	from e in myContext.Events\nwhere e.ID = 123\nselect new { \n    Event = e,\n    UserIDs = (from u in e.Users select u.ID)\n}	0
8026617	8026600	Split double into two int, one int before decimal point and one after	string s = inputValue.ToString("0.00", CultureInfo.InvariantCulture);\nstring[] parts = s.Split('.'); \nint i1 = int.Parse(parts[0]);\nint i2 = int.Parse(parts[1]);	0
28044366	28044346	Dynamically return fields of variable structure in C#	struct_type.GetType().GetFields();	0
14925590	14925415	Convert Hebrew chars to English	Dictionary<char,char>	0
15667810	15667776	Creating a view model with an object or properties	public class ProductViewModel : IProduct\n{\n    public int Id { get; set; }\n    public int CategoryId { get; set; }\n    [StringLength(50)]\n    public string ProductName { get; set; }\n    public DateTime DateAdded { get; set; }\n    [StringLength(50)]\n    public string AddedBy { get; set; }\n}	0
16789413	16789336	C# Check if a List is a part of another List	bool results =  query2.All(i=>query1.Contains(i));	0
32069399	32068264	after encrypting with aes my file is one block longer	myAes.Padding = PaddingMode.None;	0
764904	764869	C# Console App + Event Handling	RegisterClass(...);\nCreateWindow(...);\nShowWindow(...);  // probably not in your case\nwhile (GetMessage(&msg, NULL, 0, 0)) {\n  TranslateMessage(&msg);\n  DispatchMessage(&msg);\n}	0
13435831	13435797	Redis transactions in Booksleve	using(var tran = conn.CreateTransaction())\n{\n    valsPending = tran.Hashes.GetAll(db, key);\n    tran.Keys.Remove(db, key);\n    await tran.Execute();\n    var vals = await valsPending;\n    // iterate dictionary in "vals", decoding each .Value with UTF-8\n}	0
3168381	3168375	Using the iterator variable of foreach loop in a lambda expression - why fails?	foreach (var type in types)\n{\n   var newType = type;\n   var sayHello = \n            new PrintHelloType(greeting => SayGreetingToType(newType, greeting));\n   helloMethods.Add(sayHello);\n}	0
1570451	1570422	Convert String to SecureString	var s = new SecureString();\ns.AppendChar('d');\ns.AppendChar('u');\ns.AppendChar('m');\ns.AppendChar('b');\ns.AppendChar('p');\ns.AppendChar('a');\ns.AppendChar('s');\ns.AppendChar('s');\ns.AppendChar('w');\ns.AppendChar('d');	0
5548796	5548623	Row Count for WPF DataGrid?	DataGrid.Items.Count	0
3670885	3670588	Two way binding with UI quirks	var binding = this.textBox1.DataBindings.Add("Text", MyObject, "AValue", true);\nbinding.Format += (s, args) =>\n    {\n        int i = (int)args.Value;\n        if (i <= 0)\n        args.Value = "";\n    };	0
9778077	9778054	How does asynchronous request work for server side validation	[Remote]	0
4508394	4508288	C# Array number sorting	string[] valnames = rk2.GetValueNames();\nvalnames = valnames.OrderBy (s => int.Parse(s)).ToArray();\n\nfor (int i= 0 ; i < balnames.Lenght ; i++)\n{\n    k = valenames[i];\n    if (k == "MRUListEx")\n    {\n        continue;\n    }\n    Byte[] byteValue = (Byte[])rk2.GetValue(k);\n\n    UnicodeEncoding unicode = new UnicodeEncoding();\n    string val = unicode.GetString(byteValue);\n\n    richTextBoxRecentDoc.AppendText("\n" + i + ") " + val + "\n");\n}	0
20528939	20522918	wpf - Duplicate Animation on Same Control	foreach (TextBlock aBlock in theTextBlocks)\n  {\n    // Check for existing TranslateTransform\n    var translation = aBlock.RenderTransform as TranslateTransform;\n    if (translation == null)\n    {\n      aBlock.RenderTransform  = new TranslateTransform(30, 0);\n    }\n    translation = aBlock.RenderTransform as TranslateTransform;\n    var anim = new DoubleAnimation();\n    anim.By = 100;\n    anim.Duration = TimeSpan.FromSeconds(3);\n    anim.EasingFunction = new PowerEase { EasingMode = EasingMode.EaseOut };\n\n     anim.Completed += delegate\n    {\n      if (queue.Count != 0)\n        Create_TextBlock(this, null);\n      else\n        button1.Content = "off";\n    };\n     translation.BeginAnimation(TranslateTransform.YProperty, anim, HandoffBehavior.Compose);\n     button1.Content = "on";\n  }	0
6440324	6439667	How to remove rows in data grid view where checkbox is checked?	for (int i = dataGridView1.Rows.Count -1; i >= 0 ; i--)\n{\n    if ((bool)dataGridView1.Rows[i].Cells[0].FormattedValue)\n    {\n        dataGridView1.Rows.RemoveAt(i);\n    }\n}	0
25662023	25659037	When converting a code from unicode to ansi code we get ? as first character	class StackOverflow\n   {\n      byte[] unibytes;  // To be replaced by your data\n\n      public void JustTesting()\n      {\n         string s;\n\n         // Single-step these under the debugger, examine s after each attempt to see what works\n         s = Encoding.Unicode.GetString(unibytes);\n         s = Encoding.UTF8.GetString(unibytes);\n         s = Encoding.BigEndianUnicode.GetString(unibytes);\n\n         // Once you have the correct decoding, re-encode to code page 865\n         byte[] asciiLikeByteArray = Encoding.GetEncoding(865).GetBytes(s);\n      }\n   }	0
5945084	5945038	C#: projection - accessing a given string property in a collection of objects in the same way as a List<string>	Assert.IsTrue(Enumerable.SequenceEqual(result.unchangedItems.Select( x=> x.LMAA_CODE), \n                                        expectedunchangedItems));	0
23862544	23862011	Update in Entity Framework 6 without a roundtrip	SHEntity.Configuration.ValidateOnSaveEnabled = false;	0
13031747	9429211	How to get the tab ID from url in DotNetNuke	DotNetNuke.Entities.Tabs.TabController objTab = new DotNetNuke.Entities.Tabs.TabController(); \n\nDotNetNuke.Entities.Tabs.TabInfo objTabinfo = objTab.GetTabByName("Pagina", this.PortalId);\n\nint Tabid = objTabinfo.TabID;	0
6375931	6371587	Lost in multitenant Windsor Castle configuration	container.Register(Component.For<IFrmInvoice>().ImplementedBy<IFrmInvoice>());	0
32251922	32251762	getting issue with conversion from string to DateTime	var input = "08-26-2015 10:14:57.898Z";\nvar date = DateTime.ParseExact(input, "MM-dd-yyyy hh:mm:ss.fff'Z'", CultureInfo.InvariantCulture);	0
14812052	14811752	How to repeat actions after key is hold for a certain amount of time?	if (IsPressed())\n{\n    // Key has just been pushed\n    if (!WasPressed())\n    {\n        // Store the time\n        pushTime = GetCurrentTime();\n\n        // Execute the action once immediately\n        // like a letter being printed when the button is pressed\n        Action();\n    }\n\n    // Enough time has passed since the last push time\n    if (HasPassedDelay())\n    {\n        Action();\n    }   \n}	0
17711768	17711746	I am trying to figure out how to convert roman numerals into integers	public class RomanNumeral\n    {\n        public static int ToInt(string s)\n        {\n              var last = 0;\n              return s.Reverse().Select(NumeralValue).Sum(v =>\n              {                    \n                var r = (v >= last)? v : -v;\n                last = v;\n                return r;\n              });\n        }\n\n        private static int NumeralValue(char c)\n        {\n            switch (c)\n            {\n                case 'I': return 1;\n                case 'V': return 5;\n                case 'X': return 10;\n                case 'L': return 50;\n                case 'C': return 100;\n                case 'D': return 500;\n                case 'M': return 1000;                    \n            }\n            return 0;\n        }\n    }	0
20858857	20858707	Is it possible to Update UI from 2 background workers	private void worker_timerProgressChanged(object sender, ProgressChangedEventArgs e)\n    {\n       Dispatcher.Invoke(() => \n       {\n          time_left_textblock.Text = "" + schedule.TS.Subtract(elapsedTS).ToString(@"dd\.hh\:mm\:ss");\n       });\n    }	0
19116233	19116173	Newbie how to raise/trigger events in C#	public void Disconnect()\n{\n    _isconnected = false;\n    OnDisconnected();\n}	0
6935671	6935326	Deserializing JSON in ASP.NET C#	[DataContract]\npublic class Result\n{\n    [DataMember(Name = "recipe")]\n    public Recipe Recipe { get; set; }\n}\n\n[DataContract]\npublic class Recipe\n{\n    [DataMember]\n    public string thumb { get; set; }\n\n    [DataMember]\n    public string title { get; set; }\n\n    [DataMember]\n    public string source_url { get; set; }\n}	0
16574811	16574716	c# Trying to get byte[] data from an object in an Array	byte[] byteArray = myArray.GetValue(i)[0];	0
28584013	28578743	Inserting a row in database from DataGridview and Textfield	OleDbConnection con = new OleDbConnection(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=D:\naresh\My stuff\Thal tre tsks trim\Thalassemia\Data\thalsemia.accdb");\ncon.Open();\n\nfor (int i = 0; i < dataGridView1.Rows.Count; i++)\n\n{\n\n   OleDbCommand cmd= new OleDbCommand("INSERT INTO table1(name,number,salory,) VALUES\n ('"+dataGridView1.Rows[i].Cells["Column1"].Value+"','"+dataGridView1.Rows[i].Cells["Column2"].Value+"',\n'"+dataGridView1.Rows[i].Cells["Column3"].Value+" ' ",con);\n\n   cmd.ExecuteNonQuery();\n\n}\n\ncon.Close();	0
2407913	2407905	Get a folder name from a path	string a = new System.IO.DirectoryInfo(@"c:\server\folderName1\another name\something\another folder\").Name;	0
3730086	3729899	Opening a WinForm with TopMost=true but not having it steal focus?	protected override bool ShowWithoutActivation\n{\n    get { return true; }\n}	0
8840055	8827987	Executing SSIS task from C# application	var task = (TaskHost)package.Executables["Your Package Name"];\n\ntask.Properties["Any Property"].SetValue(task, "Property Value");	0
29256695	29256561	LINQ to SQL query with multiple contained strings	var result = data.Where(x => subStrings.Any(z => x.Contains(z))).ToList();	0
12671386	12668255	how to handle the key pressed inside another key click event in c#	public enum EntryState\n        {\n            Default,\n            Power\n        }\n\n        private EntryState _state = EntryState.Default;\n\n        private void buttonxn_Click(object sender, RoutedEventArgs e)\n        {\n            textBlock1.Text = textBlock1.Text + "x^";\n            _state = EntryState.Power;\n        }\n\n        private void button1_Click(object sender, RoutedEventArgs e)\n        {\n            if (_state == EntryState.Power)\n                textBlock1.Text = textBlock1.Text + "\x2070";\n            else\n                textBlock1.Text = textBlock1.Text + "1";\n        }	0
27174878	27174471	How to group dates and associated state	var result = states.GroupBy(x => x.Date)\n                   .Select(x => new { State = String.Join(",",x.Select(z => z.State)), \n                                              Date = x.Key.ToShortDateString() });	0
2253966	2253947	How can I get values from Html Tags?	HtmlDocument doc = new HtmlDocument();\n doc.Load("file.htm");\n foreach(HtmlNode link in doc.DocumentElement.SelectNodes("//a[@href"])\n {\n    HtmlAttribute att = link["href"];\n    att.Value = FixLink(att);\n }\n doc.Save("file.htm");	0
1631859	1348687	Group Tree PDF Export in Crystal Reports	CrystalDecisions.Shared.PdfFormatOptions options = new CrystalDecisions.Shared.PdfFormatOptions();\n        options.CreateBookmarksFromGroupTree = true;	0
20946774	20946469	Get a selected Row of DataGridView as a DataRow	int rw = dataGridView1.CurrentRow.Index\nDataRow PassingSessionInfo;\nPassingSessionInfo = ((dataGridView1.DataSource) as DataTable).Rows[rw];	0
568496	568483	Replacing a DateTime.MinValue in a DataGridView	if ((DateTime)(resultsGrid.CurrentRow.Cells["DateOfBirth"].Value) == DateTime.MinValue)\n            {\n                 // Set cell value to ""\n            }	0
33402908	33402633	How to set properties of a List<Class> in C#	var list = from l1 in LIST1\n    join l2 in LIST2 on l1.ID equals l2.ID\n    select new {\n        l1.ID,\n        l1.Item,\n        l1.Name,\n        l2.Color\n    }\n    .ToList()	0
1571506	1571068	AddHour / AddMinute store within a ListItem	// ---- Create a new list\n            List<string> appointmentTimes = new List<string>();\n\n            // ---- If information is pulled back\n            if (myResults != null)\n            {\n                TimeSpan time = TimeSpan.FromMinutes(30);\n\n                DateTime FirstTime = Convert.ToDateTime(myResult.firstStart);\n                DateTime LatestTime = Convert.ToDateTime(myResult.lastEnd);\n\n                while (FirstTime < LatestTime )\n                {\n                    appTimes.Add(FirstTime .ToString());\n                    FirstTime += time;\n                }\n            }	0
5912131	5912074	Mapping multiple columns to an array with NHibernate	public class MyClass {\n  public virtual int Id { get; set; }\n  protected virtual decimal Price1 { get; set; }  \n  protected virtual decimal Price2 { get; set; }  \n  protected virtual decimal Price3 { get; set; }  \n//...\n  public decimal[] Prices \n  { get \n    {\n      return new decimal[] {Price1, Price2, Price3};\n    }\n  }\n}	0
23131509	23131224	To delete a particular row in grid view	gvInvoice.DataSource = dtCurrentTable;\n  gvInvoice.DataBind()	0
9561363	9479276	How to duplicate image using BitmapData	Bitmap mask = Image.FromFile("../../Data/mask.bmp") as Bitmap;\n        BitmapData data = mask.LockBits(new Rectangle(0, 0, (int)mask.PhysicalDimension.Width, (int)mask.PhysicalDimension.Height), ImageLockMode.ReadWrite, PixelFormat.Format8bppIndexed);\n        int bytes = Math.Abs(data.Stride) * mask.Height;            \n        byte[] outPut = new byte[bytes];\n        Marshal.Copy(data.Scan0, outPut, 0, bytes);\n        Marshal.Copy(outPut, 0, data.Scan0, bytes);\n        mask.UnlockBits(data);\n\n        Bitmap test = new Bitmap(mask.Width, mask.Height, PixelFormat.Format8bppIndexed);\n        test.Palette = mask.Palette;\n        BitmapData testData = test.LockBits(new Rectangle(0, 0, mask.Width, mask.Height), ImageLockMode.ReadWrite, PixelFormat.Format8bppIndexed);\n        Marshal.Copy(outPut, 0, testData.Scan0, bytes);\n        test.UnlockBits(data);\n        test.Save("test.jpg");	0
28150043	28149779	LINQ get last position of special char	var QueueList = (from q in context.queues                                        \n                 select new { \n                             Qid = q.id, \n                             Qname = q.name \n                 }).ToList()\n    .Select(x => new {\n         Qid = x.Qid, \n         Qname = x.Qname.Substring(x.Qname.LastIndexOf(":") + 1) \n    });	0
6088313	6088287	Reverse an array without using reverse method of array	for (int i = 0; i < arr.length / 2; i++)\n{\n   int tmp = arr[i];\n   arr[i] = arr[arr.length - i - 1];\n   arr[arr.length - i - 1] = tmp;\n}	0
29569844	29565643	Selenium C# finding alert and verifying text	var errorMessage = driver.FindElement(By.XPath("//div[contains(@class, 'alert')]"));\n        Assert.IsTrue(driver.PageSource.Contains("The username and/or password entered are invalid."));	0
15405936	15316199	Working with dataset rows	foreach (DataRow row in dsGetAvailUsers.Tables[0].Rows)\n{\n    var item = new Dokument();\n    int i = 0;\n    item.Label = new Hashtable();\n    item.array = new Hashtable();\n    foreach (DataColumn _col in dsGetAvailUsers.Tables[0].Columns) \n    {\n        item.Label.Add(i, _col.ColumnName);\n        item.array.Add(_col.ColumnName,row[i].ToString());\n        ++i;\n    }\n    listDokument.Add(item);\n    RunOnUiThread (() => {DokumentAdapter.Add (item); });\n}	0
8490173	8490129	How to get the cookie value in asp.net website	if(Request.Cookies["key"]!=null)\n{\n   var value=Request.Cookies["key"].Value;\n}	0
27569424	27569273	Convert a Hex String to comma separated Hex String c#	string temp = "aaff4455";\n    string temp2 = "";\n    int size = temp.Length;\n\n    for (int i = 0; i < size; i += 2)\n    {\n        temp2 += temp.Substring(i, 2);\n        if ((i+2) < size)\n            temp2 += ",";\n    }	0
3240229	3240201	in datagridview how to 2 column that will freeze?	dataGridView1.Columns["columnname"].Frozen = true;\ndataGridView1.RightToLeft = Enabled;	0
23546994	23546843	C# Windows Form set value of selectedIndex comobox	modifyCityUserComboBox.SelectedValue=userDto.GetIdCity();	0
4123321	4123274	How to get reverse of a series of elements using Enumarable in C#?	Enumerable.Range(0, Max).OrderByDescending(x => x).ToDictionary(x => (Max - x).ToString(), x => x >= limit ? "None" : x.ToString());	0
9842585	9841696	How to download XML with RestClient?	namespace RestSharp\n{\n    public static class RestSharpEx\n    {\n        public static Task<string> ExecuteTask(this RestClient client, RestRequest request)\n        {\n            var tcs = new TaskCompletionSource<string>(TaskCreationOptions.AttachedToParent);\n\n            client.ExecuteAsync(request, response =>\n            {\n                if (response.ErrorException != null)\n                    tcs.TrySetException(response.ErrorException);\n                else\n                    tcs.TrySetResult(response.Content);\n            });\n\n            return tcs.Task;\n        }\n    }\n}	0
17617710	17617594	How to get some values from a JSON string in C#?	string source = "{\r\n   \"id\": \"100000280905615\", \r\n \"name\": \"Jerard Jones\",  \r\n   \"first_name\": \"Jerard\", \r\n   \"last_name\": \"Jones\", \r\n   \"link\": \"https://www.facebook.com/Jerard.Jones\", \r\n   \"username\": \"Jerard.Jones\", \r\n   \"gender\": \"female\", \r\n   \"locale\": \"en_US\"\r\n}";\ndynamic data = JObject.Parse(source);\nConsole.WriteLine(data.id);\nConsole.WriteLine(data.first_name);\nConsole.WriteLine(data.last_name);\nConsole.WriteLine(data.gender);\nConsole.WriteLine(data.locale);	0
1227942	1227773	sharepoint save a date to a date field	using (SPSite site = new SPSite("http://YOUR URL"))\n{\n  using (SPWeb web = site.OpenWeb()) \n  {\n    SPList list = web.Lists["news"];\n\n    SPListItem item = list.Items.Add();\n    DateTime dt = DateTime.Now;\n\n    item["Title"] = "Test";\n    item["Expires"] = dt;\n\n    item.Update();\n  }\n}	0
25674972	25674701	One-sided configuration with custom column names	public class Person\n{\n        public int? HomeAddressID { get; set; }\n        private Address _homeAddress;\n        public Address HomeAddress\n        {\n            get { return _homeAddress; }\n            set\n            {\n                _homeAddress= value;\n                HomeAddressID = value != null ? (int?)value.HomeAddressID : null;\n            }\n        }\n}\n\npublic class PersonConfiguration : EntityTypeConfiguration<Person>\n{\n    HasOptional(a => a.HomeAddress).WithMany().HasForeignKey(p => p.HomeAddressID);\n}	0
33660999	33660683	C# Parse Dynamic JSON string	var jObj = JObject.Parse(json);\nforeach (JProperty element in jObj.Children())\n{\n    string propName = element.Name;\n    var propVal = (string)element.Value;\n}	0
26794599	26794568	Stored Procedure Unsuccessful Insertion message Show	try\n{\n    // run the query\n    cmd.ExecuteNonQuery();\n    lblInserted.Text = "Inserted:" + count;\n    // MessageBox.Show("Inserted");\n    lblInserted.Font = new System.Drawing.Font(lblInserted.Font, FontStyle.Bold);\n    lblInserted.ForeColor = System.Drawing.Color.Green;\n    count++;\n    dataGridViewDisplayPanel.Rows[i].Cells[nextCell - 1].Style.BackColor = Color.Green;\n    dataGridViewDisplayPanel.Rows[i].Cells[nextCell - 1].Value = "Inserted Successfully";\n}\ncatch (Exception ee9)\n{\n    // Deal with the error\n    MessageBox.Show("Oops, it failed");\n}	0
27457584	27457184	In .NET WinForms, How to Make a Borderless Form with a Height less than 34?	protected override void OnLoad(EventArgs e) {\n        base.OnLoad(e);\n        this.ClientSize = new Size(\n            this.ClientSize.Width,\n            OKButton.Bottom + OKButton.Margin.Bottom\n        );\n    }	0
6717434	6717369	Change DataTable Column Value	protected void GridView1_DataBound(object sender, EventArgs e)\n        {\n            foreach (GridViewRow row in GridView1.Rows)\n            {\n                for (int i = 0; i < row.Cells.Count - 1; i++)\n                {\n                    if (row.Cells[i].Text == "0")\n                    {\n                        row.Cells[i].Text = "";\n                    }\n                }\n            }\n        }	0
31533385	31532947	How to generate deployment files for ASP.NET project without Visual Studio IDE?	msbuild C:\PathToYourSolution.sln /p:DeployOnBuild=true /p:PublishProfile=Test	0
14010002	14009922	Editing xml file with c#	var doc = XDocument.Parse(xmlString);\n\nvar passwordParams = doc.Root.Elements("Params").SingleOrDefault(e => (string)e.Attribute("Key") == "Password");\n\nif(passwordParams != null)\n{\n    passwordParams.Attribute("Value").Value = newPasswordString;\n    passwordParams.Element("Variable").Element("Value").Value = ewPasswordString;\n}	0
15580506	15580398	C# enum how to check if a description exists in the enum	bool isPresent = Enum.GetValues(typeof(LicenseTypes))\n                     .Select(e => e.GetDescription())\n                     .Contains("A License");	0
29026879	29011575	Multiple instances of a UserControl with DependencyProperty	private static void OnValueChanged(DependencyObject sender, DependencyPropertyChangedEventArgs args)\n    {\n        GraphBar gb = sender as GraphBar;\n        // do something here, such as: gb.DataRec.Width = 15;\n    }	0
1757284	1757271	Is there a way to create and render asp controls to a html string in the code-behind?	using(var sw = new System.IO.StringWriter()) // SW is a buffer into which the control is rendered\nusing(var writer = new HtmlTextWriter(sw))\n{\n    myControl.RenderControl(writer);\n    return sw.ToString(); // This returns the generated HTML.\n}	0
29392535	29392205	WPF - DependencyProperty ignoring setter with side-effects on change	public static readonly DependencyProperty ItemsSourceProperty = DependencyProperty.Register(\n        "ItemsSource", typeof(IEnumerable), typeof(AccountSelector), new UIPropertyMetadata((d, e) =>\n        {\n            if (e.NewValue == null) return;\n\n            var s = d as AccountSelector;\n            var list = e.NewValue as IEnumerable;\n\n            if (list == null || s == null) return;\n            if (s.UseComboBox)\n                s.AccCombo.ItemsSource = list;\n            else\n                s.AccComplete.ItemsSource = list;                \n        }));\n    public IEnumerable ItemsSource\n    {\n        get\n        {\n            return (IEnumerable)GetValue(ItemsSourceProperty);\n        }\n        set\n        {\n            SetValue(ItemsSourceProperty, value);\n        }\n    }	0
6093479	6093402	How can I convert a Unicode value to an ASCII string?	byte array	0
17730583	17730560	How to foreach though TableRows	foreach (TableRow row in mytable.Rows)	0
6869514	6856774	PowerPoint Add-In: Programatically publish Slide as Presentation	presentation.Slides[slide.SlideIndex].Export(<path>)	0
20288162	20281651	QueryOver in NHibernate with children nullable	// these will server as fully-type representatives, and aliases\nShop shop = null;\nCity city = null;\nMyDTO dto = null;\n\n// shop query\nvar query = session.QueryOver<Shop>(() => shop);\n// if needed a reference to criteria of the city\nvar cityPart = query.JoinQueryOver(() => shop.City // reference\n    , () => city // alias\n    , JoinType.LeftOuterJoin); // left join\n\n// SELECT Clause\nquery.SelectList(list => list\n    .Select(() => shop.Id)\n        .WithAlias(() => dto.Id)\n    .Select(() => shop.Name)\n        .WithAlias(() => dto.Name)\n\n    // Conditional here\n    .Select(Projections.Conditional(\n                Restrictions.Where(() => city.NameES== null),\n                Projections.Constant("---", NHibernateUtil.String),\n                Projections.Property(() => city.NameES)\n        ))\n        .WithAlias(() => dto.NameEs)\n    );\n\nvar result = query\n    .TransformUsing(Transformers.AliasToBean<MyDTO>())\n    .List<MyDTO>();	0
4748037	4747985	How do I format numbers differently based on their value in C#?	String.Format("{0:D2}", myInt);	0
6833662	6833511	C# - Adding two numbers from a RichTextBox and a TextBox	string[] Values = richTextBox1.Text.Split(new char[]{'\r','\n'});\n            richTextBox1.Clear();\n            foreach (string Value in Values)\n            {\n                richTextBox1.Text += (Convert.ToDouble(Value) + Convert.ToDouble(textBox1.Text))+"\r\n";\n\n        }	0
27266493	27265378	checking fields in csv for a number	bool hasnumeric = ColumnString.Any(t => char.IsNumber(t));\nif(hasnumeric== true)\n{\n//colomnString has at least one numeric character\n}else{\n//colomnString doesn't have any numeric characters\n}	0
5838941	5838918	Evaluate C# string with math operators	Expression e = new Expression("(4+8)*2");\nDebug.Assert(24 == e.Evaluate());	0
7296966	7296956	how to list all sub directories in a directory	Directory.GetDirectories("yourpath");	0
17892488	17890720	Remove all XML Attributes with a Given Name	XDocument xdoc = XDocument.Parse(xml);\nforeach (var node in xdoc.Descendants().Where(e => e.Attribute("foo")!=null))\n{\n    node.Attribute("foo").Remove();\n}\n\nstring result = xdoc.ToString();	0
13802186	13802054	Select a cell value from GridView asp.net c#	protected void GridView1_RowCommand(object sender, System.Web.UI.WebControls.GridViewCommandEventArgs e)\n   {\n        if (e.CommandName=="MyCommand")\n        {    \n             int row = int.Parse(e.CommandArgument.ToString());\n             var cellText= gvOwner.Rows[row].Cells[1].Text.Trim();\n        }\n   }	0
28480517	28476257	DataBinding Failure using Custom Dependency Properties	Path="(Helpers:DataGridTextSearch.SearchValue)"	0
13591120	13591030	Datagridview only shows column name	Form1_Load(object sender, System.EventArgs e) \n{ \n       GetData("select * from Customers"); \n       dataGridView1.DataSource = bindingSource1; \n}	0
11305644	11305477	Advice for loading application options	[Serializable()]\npublic class Defaults\n{\n    public string Description { get; set; }\n    public double Tolerance { get; set; }\n    public string Units { get; set; }\n }\n\ninternal class FormDefaults\n{\npublic void LoadSettings()\n    {\n      string kfileString = @"C:\Default_Settings.xml";\n\n      var q = from el in XElement.Load(kfileString).Elements()\n                select new FormDefault()\n                {\n                    Description = el.Element("InstrumentDescription").Value,\n                    Tolerance = Double.Parse(el.Element("InstrumentMassTolerance").Value),\n                    Units = el.Element("InstrumentMassUnits").Value,\n\n                };\n        }\n    }\n}	0
19614613	19614543	Using switch statement and reading data from SqlDataAdapter in C#	DataRow row = dt.Rows[0];\nint temp = Convert.ToInt32(row["Location"].ToString());\n\nswitch (temp)\n{\n    case 1:\n    lblStage.Text = temp.ToString() + " has been completed";\n    break;\n\n    case 2:\n    lblStage.Text = temp.ToString() + " has been completed";\n    break;\n\n    default:\n    // Perform altrenative, default logic\n    break;\n}	0
20563077	20562833	How to deserialize xml to List<T>	[XmlRoot("root")]\npublic class FooWrapper {\n    [XmlElement("foo")]\n    public List<Foo> Items {get;set;}\n}	0
22498797	22498596	How to close a window from another class?	public void CloseMainWindowNow()\n{\n  var mainWindow = (Application.Current.MainWindow as MainWindow);\n  if (mainWindow != null)\n  {\n    mainWindow.Close();\n  }\n}	0
29280913	25926385	Insert datetime parameter to access datebase ODBC	cmd.Parameters.Add("@send_date", OleDbType.DBTimeStamp).Value = DateTime.Parse(dati.ToString());	0
18232240	18232185	Get All Records of Monday from Database	var mondayRecords = ctx.SomeTable.Where(\n       row => row.SomeDateField.DayOfWeek == DayOfWeek.Monday);	0
19199125	19198572	How to map Integer to String with AutoMapper 3 and Entity Framework	public class LookupProfile : Profile\n{\n    protected override void Configure()\n    {\n        CreateMap<Lookup, SelectListItem>()\n            .ForMember(dest => dest.Value, opt => opt.MapFrom(src => SqlFunctions.StringConvert((double)src.LookupId)))\n            .ForMember(dest => dest.Text, opt => opt.MapFrom(src => src.Value));\n\n    }\n}	0
13919703	13919641	How to convert a double value to a DateTime in c#?	DateTime.FromOADate(myDouble)	0
14464135	14464019	Regular expressions: obtain substring between two slashes?	Uri url = new Uri("http://stackoverflow.com/questions/ask/index.php");\nstring s = string.Join("", url.Segments.Take(url.Segments.Length - 1)).Trim('/');	0
22985911	22985564	Disable a button and an event if a form is open	if(FormClienteAberto())\n{\n    thatButton.Visible = false;\n    thatDataGridView.RowHeaderMouseClick -= thatRowHeaderMouseClickEventHandler;\n}	0
7261254	7261161	Ensure safety of submited Html by the client, in server side	string input = ...\nstring safeOutput = AntiXss.GetSafeHtmlFragment(input);	0
11346018	11345592	TDD - writing tests for a method that iterates / works with collections	emptyListReturnsMinusOne()\nsinglePassingElementReturnsZero()\nnoPassingElementsReturnsMinusOne()\nPassingElementMidlistReturnsItsIndex()	0
31318199	31317246	Convert JSON to XML with invalid node names	byte[] bytes = new byte[value.Length * sizeof(char)];\n        Buffer.BlockCopy(value.ToCharArray(), 0, bytes, 0, bytes.Length);\n        XmlReader reader = JsonReaderWriterFactory\n            .CreateJsonReader(bytes, new XmlDictionaryReaderQuotas());\n        result = XDocument.Load(reader);\n        if (result.Root != null)\n        {\n            result\n                .Root\n                .Descendants()\n                .Attributes()\n                .Where(a => a.IsNamespaceDeclaration)\n                .Remove();\n            foreach (var descendant in result.Root.Descendants()) {\n                descendant.Name = descendant.Name.LocalName; \n            }\n        }	0
1500468	1496577	Round-tripping SubSonic DAL objects with WCF	// WCF server side\npublic void SaveAllMyObjects(MyObjectCollection objs)\n{\n   MyObjectCollection fakeColl = new MyObjectCollection();\n   foreach (var oneObj in objs)\n   {\n       var oneFakeObj = new MyObject();\n       oneFakeObj.Id = oneObj.Id;    // Primary key\n       // Pretend oneFakeObj was just loaded from the DB\n       oneFakeObj.IsNew = False;\n       oneFakeObj.IsLoaded = True;\n       // Copy all column values\n       foreach (var col in MyObject.Schema.Columns)\n       {\n           oneFakeObj.SetColumnValue(col.ColumnName, oneObj.GetColumnValue(col.ColumnName));\n       }\n       fakeColl.Add(oneFakeObj);\n  }\n  fakeColl.SaveAll();\n}	0
8612623	8612580	how to know next primary key value of table without inserting record in sql server?	CREATE TABLE #Table (\n        ID INT IDENTITY(1,1),\n        Val INT\n)\n\nINSERT INTO #Table SELECT 1\nINSERT INTO #Table SELECT 2\nINSERT INTO #Table SELECT 3\n\nSELECT * FROM #Table\n\nDELETE FROM #Table WHERE ID >= 2\n\nSELECT * FROM #Table\n\nSELECT IDENT_CURRENT('#Table')\n\nDROP TABLE #Table	0
33414727	33414658	How to use text from a TextBox as a file name?	StreamWriter stream = new StreamWriter(Username + ".txt");	0
13070027	13069839	Add an index to duplicate elements of a string list in C#	var strings = new string[] { "A", "B", "C", "D", "A", "B", "E", "F", "A" };\n\nDictionary<string, int> counts = new Dictionary<string, int>();\nfor (int i = 0; i < strings.Length; ++i)\n{\n    if (counts.ContainsKey(strings[i]))\n        strings[i] = string.Format("{0} ({1})", strings[i], counts[strings[i]]++);\n    else\n        counts.Add(strings[i], 1);\n}	0
32400774	32400549	Convert List<Objects> to List<String> based on property fed in at runtime	class Program\n{\n    static List<Animal> animals = new List<Animal>();\n\n    static void Main(string[] args)\n    {\n        animals.Add(new Animal() { Age = 3, Name = "Terry", Type = "Tiger" });\n        animals.Add(new Animal() { Age = 1, Name = "Bob", Type = "Badger" });\n        animals.Add(new Animal() { Age = 7, Name = "Alfie", Type = "Dog" });\n\n        GetList("Age").ForEach(Console.WriteLine);\n\n        Console.Read();\n    }\n\n    public static List<string> GetList(string property)\n    {\n        return animals.Select(o => o.GetType().GetProperty(property).GetValue(o).ToString()).ToList();\n    }\n}\n\nclass Animal\n{\n    public string Name { get; set; }\n    public string Type { get; set; }\n    public int Age { get; set; }\n}	0
28919809	28919446	RegisterStartupScript in a loop	ClientScriptManager cs = Page.ClientScript;\n        string csName = "MyScript";\n        Type csType = this.GetType();\n\n        for(int i = 1; i <= 10; i++)\n        {\n            string currentName = string.Format("{0}{1}", csName, i);\n            if (!cs.IsStartupScriptRegistered(csType, currentName))\n            {\n                string csText = string.Format("myFunction('{0}');", i);\n                cs.RegisterStartupScript(csType, currentName, csText, true);\n            }\n        }	0
7066255	7065613	Right listbox event to handle changes in listbox? (C#)	private BindingList<string> myList = new BindingList<string>();\nprivate bool isDirty;\n\npublic Form1()\n{\n  InitializeComponent();\n\n  myList.Add("aaa");\n  myList.Add("bbb");\n  myList.Add("ccc");\n  myList.ListChanged += new ListChangedEventHandler(myList_ListChanged);\n\n  listBox1.DataSource = myList;\n}\n\npublic void myList_ListChanged(object sender, ListChangedEventArgs e)\n{\n  isDirty = true;\n}\n\nprivate void button1_Click(object sender, EventArgs e)\n{\n  MessageBox.Show("IsDirty = " + isDirty.ToString());\n  myList.Add("ddd");\n  MessageBox.Show("IsDirty = " + isDirty.ToString());\n}	0
21869459	21869195	Displaying float SQL Datatypes	ships.Height = Convert.ToSingle(shipReader["HeightTest"]);	0
2361350	849330	How do you hide a column in a datagrid using the .net compact framework 3.5	// Order date column style\n        DataGridColumnStyle cust_id = new DataGridTextBoxColumn();\n        cust_id.MappingName = "cust_id";\n        cust_id.HeaderText = "ID";\n        //**************************************\n        //Hide Customer ID\n        cust_id.Width = -1;\n        //**************************************\n        ts.GridColumnStyles.Add(cust_id);\n\n        // Shipping name column style\n        DataGridColumnStyle cust_name = new DataGridTextBoxColumn();\n        cust_name.MappingName = "cust_name";\n        cust_name.HeaderText = "Customer";\n        cust_name.Width = 500;\n        ts.GridColumnStyles.Add(cust_name);\n\n        GridView1.TableStyles.Add(ts);	0
3149026	3148893	How to read value of an attribute defined in app.config?	using System.Configuration;\nusing System.ServiceModel.Configuration;\n\nClientSection clientSettings = ConfigurationManager.GetSection("system.serviceModel/client") as ClientSection;\n\nstring address = null;\n\nforeach(ChannelEndpointElement endpoint in clientSettings.Endpoints)\n{\n   if(endpoint.Name == "XXX")\n   {\n      address = endpoint.Address.ToString();\n      break;\n   }\n}	0
13474381	13455325	Get Default Value Description in Crystal	foreach (ParameterFieldDefinition param in clsCrystal.cryRtp.DataDefinition.ParameterFields)\n{\n    if (param.Name.Equals("ShowUp"))\n    {\n        foreach (ParameterValue parameterValue in param.DefaultValues)\n        {\n            if (!parameterValue.IsRange)\n            {\n                ParameterDiscreteValue parameterDiscreteValue = (ParameterDiscreteValue)parameterValue;\n                MessageBox.Show(parameterDiscreteValue.Description);\n            }\n        }\n    }\n}	0
13878732	13878590	Parsing inner nodes from an xml using Linq	var items = xdoc.Descendants("ItemDate")\n    .Select(e => new ItemDate\n    {\n        Date = e.FirstNode.ToString(),\n        Type = e.Element("ItemType").FirstNode.ToString(),\n        Url = e.Element("ItemType").Element("ItemUrl").Value,\n        Title = e.Element("ItemType").Element("ItemUrl").Attribute("title").Value\n    })\n    .ToList();	0
7470671	7470512	How to fetch users from an Active Directory Organisational Unit having '//' in its name	ou=Turbo\/\/Boost	0
25159858	25159798	How to play a sound without creating a Media Element in Xaml (Windows phone 8)?	Stream stream = TitleContainer.OpenStream("sounds/bonk.wav");\nSoundEffect effect = SoundEffect.FromStream(stream);\nFrameworkDispatcher.Update();\neffect.Play();	0
29327936	29327775	OrderByDescending with a date from another table(s)	(...)\n.OrderByDescending(o => \n   o.tbl_Application.tbl_ApplicationChanges\n      .Where(ac => ac.ApplicationID == o.ApplicationID)\n      .OrderByDescending(ac => ac.ChangeDate)\n      .First()\n      .Select(ac => ac.ChangeDate)\n)\n(...)	0
15648299	15648204	store each value of foreach loop into string array	List<string> elements = new List<string>();\nforeach(xmlnode anode in somecollection)\n{\n  elements.Add("string");\n}	0
1488310	1488306	Date format issue between in app and windows with c#	DateTime? dt = null;\n    dt = DateTime.ParseExact(postdate[i], "MM/dd/yyyy", System.Globalization.CultureInfo.CurrentCulture);	0
17201514	17201415	Why is Snoop for WPF crashing when we try attaching it to our application?	Debug -> Exceptions	0
25075059	25075003	Convert Array to custom object list c#	myArray.Select(array => new Portfolio { Field1 = array[0], Field2 = array[1] }).ToList()	0
5329524	5278860	Using WMI to identify which device caused a Win32_DeviceChangeEvent	ManagementEventWatcher watcher;\n            string queryStr =\n                "SELECT * FROM __InstanceCreationEvent " +\n                "WITHIN 2 "\n              + "WHERE TargetInstance ISA 'Win32_PnPEntity'"\n\n            watcher = new ManagementEventWatcher(queryStr);\n            watcher.EventArrived += new EventArrivedEventHandler(DeviceChangeEventReceived);\n            watcher.Start();	0
4012753	4011702	How to call a JavaScript function multiple times in a loop on page reload with ASP.NET	Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "Delete" + counter.ToString(), "<script language='javascript'>$(document).ready(function() {deletePatient(" + id + ");});</script>");	0
4893842	4892890	How to colorize Categories for an Outlook AppointmentItem	Private Shared ReadOnly CATEGORY_TEST As String = "Custom Overdue Activity"\n\n' This method checks if our custom category exists, and creates it if it doesn't.\nPrivate Sub SetupCategories()\n    Dim categoryList As Categories = Application.Session.Categories\n    For i As Integer = 1 To categoryList.Count\n        Dim c As Category = categoryList(i)\n        If c.Name.Equals(CATEGORY_TEST) Then\n            Return\n        End If\n    Next\n\n    categoryList.Add(CATEGORY_TEST, Outlook.OlCategoryColor.olCategoryColorDarkOlive)\nEnd Sub	0
14151548	14151421	How to copy the contents of a Multiline textbox to the clipboard in C#?	Clipboard.Clear();    //Clear if any old value is there in Clipboard        \nClipboard.SetText("abc"); //Copy text to Clipboard\nstring strClip = Clipboard.GetText(); //Get text from Clipboard	0
12623646	12623555	Linq with sum with nullable int	(from surveyResult in\n surveyResultsFromChats\nwhere surveyResult.FirstScoreNPS.HasValue && surveyResult.GroupID == gr && \nsurveyResult.FirstScoreNPS >= 9\n   select surveyResult.FirstScoreNPS).\nSelect(score => score.Value ?? 0).Sum();	0
6604740	6604503	Overriding a non-generic interface property with a generic one	public abstract class EntityConductor<T> : IEntityViewModel<T>\n    where T : class, ICLEntity\n{\n    public T Entity { get; set; }\n\n    ICLEntity IEntityViewModel.Entity\n    {\n        get { return Entity; }\n        set { Entity = (T)value; }\n    }\n}	0
26064709	26052070	Difference in size for same file, read on Windows XP & Windows 7	private void ImageToStream(Stream stream, string imgPath)\n        {\n            FileStream fileStream = new FileStream(imgPath,\n                                    FileMode.Open, FileAccess.Read);\n            byte[] buffer = new Byte[checked((uint)Math.Min(4096,\n                                 (int)fileStream.Length))];\n            int bytesRead = 0;\n            while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)\n                stream.Write(buffer, 0, bytesRead);\n        }	0
4778320	4778306	I anticipate slowness in this algorithm to check for vowels	Regex.IsMatch(sentence, "[aoeui]");	0
9533882	9533584	How to XDocument.Save writing escape chars	XDocument document = new XDocument();\nvar xmlFromDb = "<xml>content</xml>";\nusing (var stream = new MemoryStream(Encoding.UTF8.GetBytes(xmlFromDb))) \n{\n     using (var reader = XmlReader.Create(stream)) {\n          reader.MoveToContent();\n          document.Add(XElement.ReadFrom(reader));\n     }\n}	0
9083950	9083755	simple login page and dynamically hiding controls based on session variable	protected void Page_Load(object sender, EventArgs e)\n{\n    if (!IsPostBack)\n    {\n        Session["admin"] = null;\n    }\n    Set_Control_State();\n}\n\nprotected void btnLogin_Click(object sender, EventArgs e)\n{\n    String admin = (String)(Session["admin"]) ?? "";\n    if (admin.Equals("true"))\n    {\n        Session["admin"] = null;\n    }\n    else\n    {\n        Session["admin"] = "true";\n    }\n    Set_Control_State();\n}\n\nprotected void Set_Control_State()\n{\n    String admin = (String)(Session["admin"]) ?? "";\n\n    if (admin.Equals("true"))\n    {\n        btnLogin.Text = "Log Out";\n        Label2.Visible = true;\n        TextBox2.Visible = true;\n        Button2.Visible = true;\n    }\n    else\n    {\n        btnLogin.Text = "Log In";\n        Label2.Visible = false;\n        TextBox2.Visible = false;\n        Button2.Visible = false;\n    }\n}	0
25906545	25906357	Getting XElement with specified Title in c#	var xd = XDocument.Parse(xml);\n\nxd.Root.Elements("Service") // Enumerate the service elements\n    .Where \n    (\n        x=>\n        (string)x.Element("TITLE") == "Collect Call and SMS"\n    )                       // Find the ones you are interested in\n    .Remove();              //Remove them from the document	0
11079862	11079719	Deleting column data in List Views	int totalItems = logListView.Items.Count;\nfor(int i=0; i<totalItems ; i++){\n    // Column B is at index 1\n    logListView.Items[i].SubItems[1].Text = string.Empty;\n}	0
27486299	27413876	How to save user last login date if he was logged in with external login provider using ASP .Net Identity?	UserManager.FindAsync(loginInfo.Login)	0
5565860	5565827	How to find the desktop on any user computer?	var desktopPath = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);	0
25014706	24995999	keep table(rows) together with OpenXML SDK 2.5	Table table = wordDoc.MainDocumentPart.Document.Body.AppendChild(new Table());\n\nTableRow row1 = table.AppendChild(new TableRow());\nTableCell cell1 = row1.AppendChild(new TableCell());\nParagraph para1 = cell1.AppendChild(new Paragraph());\nPreviousParagraphProperties prop1 = para1.AppendChild(new PreviousParagraphProperties());\nKeepNext k = prop1.AppendChild(new KeepNext());\nRun run1 = para1.AppendChild(new Run());\nrun1.AppendChild(new Text("This is some long text"));\n\nTableRow row2 = table.AppendChild(new TableRow());\nTableCell cell2 = row2.AppendChild(new TableCell());\nParagraph para2 = cell2.AppendChild(new Paragraph());\nPreviousParagraphProperties prop2 = para1.AppendChild(new PreviousParagraphProperties());\nKeepNext k2 = prop2.AppendChild(new KeepNext());\nRun run2 = para2.AppendChild(new Run());\nrun2.AppendChild(new Text("This is some even longer text"));	0
1290562	1290538	Regex return value between two values?	string input = "this is a :::test??? string";\n    Match match = Regex.Match(input, @":::(\w*)\?\?\?");\n    if (match.Success)\n    {\n        Console.WriteLine(match.Groups[1].Value);\n    }	0
1419092	1419069	How can I reproduce a SHA512 hash in C# that fits the PHP SHA512?	using System.Security.Cryptography\n\npublic static string HashPassword(string unhashedPassword)\n{\n    return BitConverter.ToString(new SHA512CryptoServiceProvider().ComputeHash(Encoding.Default.GetBytes(unhashedPassword))).Replace("-", String.Empty).ToUpper();\n}	0
9013528	9013473	ASP.NET Check if Selected User in ListBox is in Role	if(Roles.IsUserInRole(UserListBox.SelectedItem.Value,"Administrator"))\n    {\n      //\n    }	0
25940732	25449580	How can I display a line chart with only 1 data point	foreach (Series ser in mainChart.Series)\n{\n   ser.Points.AddY(ser.Points[0].YValues[0]);\n}	0
19352763	19352147	Average Datatable DateTime rows by TIME only	using System;\nusing System.Data;\nusing System.Linq;\n\n...\n\nvar results = from row in ds.Tables[0].AsEnumerable()\n    group row by ((DateTime) row["TheDate"]).TimeOfDay\n    into g\n    select new\n            {\n                Time = g.Key,\n                AvgValue = g.Average(x => (int) x["TheValue"])\n            };	0
8808039	8807995	How to find the exact occurance of a string in HTML file	Regex re = new Regex("\\b" + Regex.Escape(mykeyWord) + "\\b", RegexOptions.IgnoreCase);\nint count = re.Matches(innerDocument.DocumentNode.InnerText).Count;	0
15369432	15369219	Unable to create a constant value in a linq query	var accountDetailIds = holder.AccountDetails.Select(a => a.Id);\nvar holderAccounts = db.AccountDetails\n    .Include(p => p.BranchDetail)\n    .Where(p => accountDetailIds.Contains(p.Id));	0
18297394	18297341	Extract phone number from text	String s = "abc055667788abc";\nstring phoneNumber;\nforeach(char c in s)\n{\n    if(Char.isNumber(c) || c == " " || c == "+")\n    {\n        phoneNumber = phoneNumber + c;\n        minimumDigits++;\n        if(minimumDigits >= 9)\n        {\n            NumberDetected(phoneNumber);\n        }\n    }\n    else\n    {\n        minimumDigits = 0;\n    }\n}\n\nNumberDetected(string rawNumber)\n{ \n    int plusses = 0;\n    foreach(char c in rawNumber)\n    {\n        if(c == "+")\n        {\n            plusses++;\n        }\n    }\n    if(plusses <= 1)\n    {\n        if(rawNumber.StartsWith("+")\n        {\n            NumberDone(rawNumber);\n        }\n    }\n    else\n    {\n        MessageBox.Show("Number contained too many plusses!");\n    }\n}	0
3439085	3438788	Access to Sql Server via ODBC from C# : ERROR [IM002] [Microsoft][ODBC Driver Manager] Data source name not found and no default driver specified	Driver={SQL Server Native Client 10.0};Server=xxx;Database=zzz;Trusted_Connection=yes;	0
18127457	18126896	Best way to implement calling a constructor from another constructor?	public class MyFileClass\n{\n    public MyFileClass(FileInfo info)\n    {\n        // do work\n    }\n\n    public MyFileClass(string url, string description)\n        : this(GetFileInfo(url, description))\n    { \n        // do more work\n    }\n\n    static FileInfo GetFileInfo(string url, string description)\n    {\n        return new FileInfo();\n    }\n}	0
1588918	1588908	Creating a collection of all classes that inherit from IBlahblah	var blahs = assembly.GetTypes()\n                    .Where(t => typeof(IBlahblah).IsAssignableFrom(t));	0
24068292	24068239	How to prevent the first character to be a number	if (tbTableName.Text.Length > 0 && char.IsNumber(tbTableName.Text[0]))\n    tbTableName.Text = tbTableName.Text.Substring(1);	0
566193	566185	Cast int to byte[4] in .NET	BitConverter.GetBytes	0
18009518	18007765	foreach looping only displaying last value of gridview	protected void GWCase_SelectedIndexChanged(object sender, EventArgs e)\n{\n  int idx = GWCase.SelectedIndex; //add this line in\n  string detail = GWCase.DataKeys[idx].Values[0].ToString();\n  string propertydetail = GWCase.DataKeys[idx].Values[1].ToString();\n  string suspectdetail = GWCase.DataKeys[idx].Values[2].ToString();\n\n  tbdetails.Text = detail;\n  tbproperty.Text = propertydetail;\n  tbsuspect.Text = suspectdetail;\n}	0
27366420	27366386	If statement for multiples of an variable	if ((gameScore % 480) == 0)	0
4317905	4317813	How to access form control from within ToString method of nested struct	public partial class Form1 : Form \n{ \n public struct OrderLineItem \n    { \n     string someString; \n     int index; \n     Form1 parentForm;\n\n     internal OrderLineItem(Form1 parentForm)\n     {\n         this = new OrderLineItem();\n         this.parentForm = parentForm;\n     }\n\n     string ToString() \n     {\n         if (parentForm == null)\n             return string.Empty;\n         else\n             return someString + parentForm.sizeComboBox.Items[index].ToString();\n     }   \n    } \n}	0
15869316	15869180	How to assert a Linq collection with unit test	IList expectedNumberCollection = new List<object>{\n new {Numbers = new List<int>{5},Remindar=0},\n new {Numbers = new List<int>{8},Remindar=3}, \n new {Numbers = new List<int>{14,9},Remindar=4}\n};	0
6515992	6515933	get and set the value of controls inside a panel which is itself inside a tableLayout Panel	foreach ( Control panel in this.tableLayoutPanel ) {\n    foreach ( Control ctrl in panel) {\n        // etc..\n    }\n}	0
5060792	5060488	How to Freeze Top Row and Apply Filter in Excel Automation with C#	// Fix first row\nworkSheet.Activate();\nworkSheet.Application.ActiveWindow.SplitRow = 1;\nworkSheet.Application.ActiveWindow.FreezePanes = true;\n// Now apply autofilter\nExcel.Range firstRow = (Excel.Range)workSheet.Rows[1];\nfirstRow.Activate();\nfirstRow.Select();\nfirstRow.AutoFilter(1, \n                    Type.Missing, \n                    Excel.XlAutoFilterOperator.xlAnd, \n                    Type.Missing, \n                    true);	0
13425227	13424751	How do I add another project (assembly) from my solution to the set of CompilerParameters.ReferencedAssemblies?	compilerParameters.ReferencedAssemblies.Add(typeof(InterfaceType).Assembly.Location);	0
2314896	2314861	Shutting down a multithreaded application	myThread.IsBackground = true;	0
32731470	32695596	Delete host from dns zone	bool DeleteRecordFromDns(string ZoneName, string dnsServerName, string recordName)\n    {\n        try\n        {\n            string Query = string.Format("SELECT * FROM MicrosoftDNS_AType WHERE OwnerName = '{0}.{1}'", recordName, ZoneName);\n            ObjectQuery qry = new ObjectQuery(Query);\n            ManagementScope scope = new ManagementScope(@"\\" + dnsServerName + "\\root\\MicrosoftDNS");\n            scope.Connect();\n            ManagementObjectSearcher s = new ManagementObjectSearcher(scope, qry);\n            ManagementObjectCollection col = s.Get();\n            if (col.Count > 0)\n            {\n                foreach (ManagementObject obj in col)\n                {\n                    obj.Delete();\n                }\n                return true;\n            }\n            else\n            {\n                return false;\n            }\n\n        }\n        catch (Exception)\n        {\n            return false;\n        }\n    }	0
33242998	33240901	Using OnValidateIdentity to perform additional validation on cookie data	return Task.FromResult<int>(0);	0
3511610	3511503	How to refresh a grid while a storedproc is running for long time from codebehind	SqlCommand cmd = new SqlCommand("Your query", connection)\ncmd.BeginExecuteNonQuery()	0
13482560	13431356	Binding to 3rd-party library in Monotouch - mapping uint8_t * and uint8_t **	[DllImport ("__Internal")]\nextern static int MWB_scanGrayscaleImage (byte[] pp_image, int lenX, int lenY, out IntPtr pp_data);\npublic static int ScanGrayscaleImage (byte[] image, int lenX, int lenY, out byte[] data)\n{\n    IntPtr pp_data;\n\n    int result = MWB_scanGrayscaleImage (image, lenX, lenY, out pp_data);\n    if (result > 0) {\n        data = new byte[result];\n        Marshal.Copy (pp_data, data, 0, result);\n        Marshal.FreeHGlobal (pp_data); // I think this is what you want...\n    } else {\n        data = null;\n    }\n\n    return result;\n}	0
33668903	33668842	How to add a Case statement to my LINQ Query	CurrentStatus = row.EndDate >= DateTime.Now && row.StartDate <= DateTime.Now ? "Active": row.StartDate >=  DateTime.Now ? "Pending": "Closed";	0
17562262	17538996	Get attributes assigned to property of a Type using an instance of that property	[JsonConverter(typeof(SerializeOnlyWhatIWantOnThisPropertyConverter))]	0
19991456	19984063	Databinding updating with outdated values	Text="{Binding intBauer, UpdateSourceTrigger=PropertyChanged}"	0
25040947	25040782	Initialize a xml class obtained from Edit, Paste Special, Paste XML as Classes	XmlSerializer serializer = new XmlSerializer(typeof(Items));\n\n// Declare an object variable of the type to be deserialized.\nItems i;\n\nusing (Stream reader = new FileStream(filename, FileMode.Open))\n{\n    // Call the Deserialize method to restore the object's state.\n    i = (Items)serializer.Deserialize(reader);          \n}	0
22635376	22635042	How to get column values from datatable to textbox?	while(dt.Rows.Count>0)\n{\ntxtGroupName.Text=dt.Rows[0]["column_name"].ToString();\n}	0
23690522	23690270	Saving images to server	string s1 = @"D:\Projects\*************\****\img\logos\image1.png";            \nstring s2 = "~/****/" + s1.Substring(s1.IndexOf("img")).Replace("\\", "/");\n// use s2 as src attribute for img	0
2580997	2580989	How to create a table in outlook mail body programmatically	MailMessage msg = new MailMessage("From@Email.com", "To@Email.com");\nmsg.IsBodyHTML = true;\nmsg.Subject = "Subject line here";\nmsg.Body = "html goes here";\n\nSmtpClient mailClient = new SmtpClient("YourEmailServer");\nmailClient.Send(msg);	0
13145208	13145049	how do I reference a workspace directory in Visual Studio	private const String = "./testFile1.xml";	0
1630591	1630579	Convert from Array to ICollection<T>	class Foo {}\n\nFoo [] foos = new Foo [12];\nICollection<Foo> foo_collection = foos;	0
26407651	26407426	Linq-to-Sql filtering for dates of last element	(from f in MyDc.Fruits\ngroup f by f.BasketID into g\nwhere TheBasketIDs.Contains(g.Key)\n&& g.OrderByDescending(gg=>gg.HarvestDate).First().HarvestDate <= TheDate\nselect g.First().BasketID).ToList();	0
1213353	1213339	Save file with appropriate extension in a Save File prompt	SaveFileDialog dlg = new SaveFileDialog();\ndlg.DefaultExt = "dat";\ndlg.AddExtension = true;	0
19371892	19371668	How to find if a GeoCoordinate point is within boundaries	public static Boolean isWithin(this GeoCoordinate pt, GeoCoordinate sw, GeoCoordinate ne)\n{\n   return pt.Latitude >= sw.Latitude &&\n          pt.Latitude <= ne.Latitude &&\n          pt.Longitude >= sw.Longitude &&\n          pt.Longitude <= ne.Longitude\n}	0
15048202	14964707	How to alter a table using SMO	string connns = ConfigurationManager.AppSettings["conn"];\n                SqlConnection sqlConn = new SqlConnection(ConfigurationManager.AppSettings["conn"]);\n                SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder(connns);\n                string password = builder.Password;\n                string userid = builder.UserID;\n                ServerConnection smoConn = new ServerConnection();\n                smoConn.ServerInstance = sqlConn.DataSource;\n                instanceServer = new Server(smoConn);\n                instanceServer.ConnectionContext.LoginSecure = false;\n                instanceServer.ConnectionContext.Login = userid;\n                instanceServer.ConnectionContext.Password = password;\n                projectDatabase = instanceServer.Databases[sqlConn.Database];	0
25029886	25027202	How to query the database table with no primary key	[Table("Completion")]\npublic class CompletionsModel\n{\n    [Column(Order = 0), Key]\n    public int UserId { get; set; }\n\n    [Column(Order = 1), Key]\n    public string PRD_NUM { get; set; }\n\n    public DateTime CompletionDate { get; set; }\n\n    public virtual CourseModel PRD { get; set; }\n    public virtual StudentModel UserProfile { get; set; }\n}	0
14354468	14354396	unit test parser with large string input	using (var stream = Assembly.GetExecutingAssembly()\n       .GetManifestResourceStream(typeof(YourUnitTest), filename))\nusing(var reader = new StreamReader(stream))\n{\n    var fileContent = reader.ReadToEnd();\n}	0
6798780	6798547	How to execute command in a C# Windows console app?	System.Diagnostics.Process proc;\n\n            cmd = @"strCmdLine = "/C xxxxx xxxx" + args[0] + i.ToString();\n\n            proc = new System.Diagnostics.Process();\n            proc.EnableRaisingEvents = false;\n            proc.StartInfo.FileName = "cmd";\n            proc.StartInfo.Arguments = cmd;\n            proc.Start();	0
3890118	3864775	Creating a non blocking observable extension method that returns a default item for an empty sequence	public static IObservable<T> DefaultIfEmpty<T>(this IObservable<T> src, T defaultValue)\n{\n  return src\n    .Materialize()\n    .Select((n, i) => (n.Kind == NotificationKind.OnCompleted && i == 0)\n                ? new Notification<T>[]\n                {\n                  new Notification<T>.OnNext(defaultValue), \n                  new Notification<T>.OnCompleted()\n                }\n                : new[] {n})\n    .SelectMany(ns => ns)\n    .Dematerialize();\n}	0
3450562	3450044	How to get a result based on Id with NHibernate	public Wrapper GetWrapper(int siteId, string actionName)\n    {\n        Wrapper wrapper = _session.CreateCriteria<Wrapper>()\n            .Add<Wrapper>(x => x.SiteId == siteId)\n            .Add<Wrapper>(x => x.Action == actionName)\n            .List<Wrapper>().FirstOrDefault();\n\n        return wrapper;\n    }	0
6057664	6056004	Using .NET Rx to observe property changed with Action events	public static class RxExt\n{\n    public static IObservable<T> FromMyEvent<T>(this IProperty<T> src)\n    {\n        return System.Reactive.Linq.Observable.Create<T>((obs) =>\n        {\n            Action eh = () => obs.OnNext(src.Value);\n            src.ValueChanged += eh;\n            return () => src.ValueChanged -= eh;\n        });\n    }\n}	0
14066592	14066045	C# or VB scaling the text being sent to a printer	Private Sub PrintTextControl_PrintPage(\n    ByVal sender As System.Object, \n    ByVal e As System.Drawing.Printing.PrintPageEventArgs) \n    Handles PrintTextControl.PrintPage\n    '.....\n    Dim scaleMatrix As New Matrix()\n    scaleMatrix.Scale(0.8, 1)\n    e.Graphics.Transform = scaleMatrix\n    e.Graphics.DrawString("Hello World", font1, Brushes.Black, x, y, strFormat)\n    '.....\nEnd Sub	0
9619892	9619746	How do I to get the current cell position x and y in a DataGridView?	form_date.Location = paygrid.PointToScreen(\n   paygrid.GetCellDisplayRectangle(e.ColumnIndex, e.RowIndex, false).Location);	0
31676318	31674383	Change the table that Orchard reads from	public double Latitude\n{\n    get { return Record.Latitude; }\n    set { Record.Latitude = value; }\n}	0
24557597	24557144	Unable to locate checkbox control inside repeater	CheckBox checkBox = skuItm.FindControl("LineQuantity") as CheckBox;	0
5387588	5381495	how to retrieve content based paragraph from the word file using open xml and c#4.0?	using(WordprocessingDocument document = WordprocessingDocument.Open(documentStream, true)){\n    foreach(Paragraph p in document.MainDocumentPart.Document.Body.Descendants<Paragraph>().Where<Paragraph>(p => p.InnerText.Equals("SOME TEXT")){\n        // Do something with the Paragraphs.\n    }\n}	0
26325918	26316752	Need a query where list doesn't contain an item of another list	ParseQuery<ParseGame> query = from remoteGame in new ParseQuery<ParseGame>()\n                              select remoteGame;\nquery = query.WhereNotContainedIn("Players", localPlayers);	0
1446261	1431723	How do you validate a clr property after it has been updated instead of before when implementing IDataErrorInfo?	public string FirstName\n{\n    get { return _firstName; }\n    set\n    {\n        if (this.PropertyChanged != null)\n        {\n            this.PropertyChanged\n                (this, new PropertyChangedEventArgs("FirstName"));\n        }\n        _firstName = value;\n    }\n}	0
27072898	27068100	Find a GameObject and check if the user has clicked on it	bool bClicked = false;\n void OnMouseDown()\n {\n     Debug.Log(gameObject.name + " is clicked");        \n     bClicked = true;\n }	0
19994155	19994021	Compressing a folder on a network path using DotNetZip	using (ZipFile myZip = new ZipFile())\n{\n    myZip.AddDirectory(@"\\ABC.XYZ.com\d$\WebSite\", "WebSite");\n    myZip.Save(@"\\ABC.XYZ.com\d$\Test.zip");\n}	0
4951481	4949403	Getting HMACSHA1 correctly on iPhone using openssl	SHA_CTX shaContext;\nSHA1_Init(&shaContext);     \nSHA1_Update(&shaContext, inStrg, lngth );\nSHA1_Final(result, &shaContext);	0
8428793	8427208	Can I use Visual Studio's Data Source Configuration Wizard to connect to the YouTube api?	XmlReader Reader = XmlReader.Create("https://gdata.youtube.com/feeds/api/standardfeeds/top_rated");\nSyndicationFeed Feed = SyndicationFeed.Load(Reader);\n\nforeach (var Item in Feed.Items)\n{\n    Console.WriteLine(Item.Title.Text);\n    Console.WriteLine(Item.Id);\n    Console.WriteLine();\n}\n\nReader.Close();	0
13066700	13066646	Parse XML and fill string with element value	string xml = @"<string xmlns=""http://www.webserviceX.NET"">\n    <NewDataSet> <Table> <AtomicWeight>196.967</AtomicWeight> </Table> </NewDataSet>\n    </string>";\n\nvar xDoc = XDocument.Parse(xmlstr); //or XDocument.Load(filename)\nXNamespace ns = "http://www.webserviceX.NET";\nstring atomicWeight = xDoc.Descendants(ns + "AtomicWeight").First().Value;	0
16438496	16437404	Creating efficient code for generating xml with xdocument	string xml;\n\nusing (StringWriter sw = new StringWriter())\n{\n  using (XmlWriter xw = XmlWriter.Create(sw, new XmlWriterSettings() { Indent = true }))\n  {\n    xw.WriteStartDocument();\n    xw.WriteStartElement("Root");\n    foreach (HtmlElement el in webBrowser1.Document.GetElementsByTagName("TEXTAREA"))\n    {\n      xw.WriteStartElement("Item");\n      xw.WriteElementString("GUID", el.Id);\n      xw.WriteElementString("Type", el.GetAttribute("type").ToUpper());\n      // write further elements the same way\n      xw.WriteEndElement();\n    }\n    xw.WriteEndElement();\n    xw.WriteEndDocument();\n  }\n  xml = sw.ToString();\n}	0
20931535	20931503	How to split a string to get desired integer value?	String fee =  "Receipt No: 000203680000140052568711 Amount: AED 53.00";\n  String[] words = fee.Split();\n  String aed = words[words.Length - 1]; // <- "53.00"	0
3258265	3257361	Building an ObjectContext in EF Code First CTP4	var modelBuilder = new ModelBuilder();\nvar dbModel = modelBuilder.CreateModel();\nvar ctx = dbModel.CreateObjectContext<ObjectContext>(connection);	0
22910172	22909601	Rendering of controls in a moving panel	private void button1_Click(object sender, EventArgs e)\n{\n    if (menuHidden)\n    {\n        menu.BringToFront();\n        for (int i = 0; i < menu.Size.Width; i++)\n        {\n            menu.Location = new Point(menu.Location.X + 1, 0);\n            System.Threading.Thread.Sleep(Convert.ToInt32(textBox1.Text));\n            Refresh(); // <-----------------------\n        }\n    }\n    else\n    {\n        for (int i = 0; i < menu.Size.Width; i++)\n        {\n            menu.Location = new Point(menu.Location.X - 1, 0);\n            System.Threading.Thread.Sleep(Convert.ToInt32(textBox1.Text));\n            Refresh(); // <-----------------------\n        }\n    }\n    menuHidden = !menuHidden;\n}	0
29857326	29524069	Pass value from a Repeater row to a textbox on button click in asp.net C#	Button button = (sender as Button);\n    string commandArgument = button.CommandArgument;\n    RepeaterItem item = button.NamingContainer as RepeaterItem;\n    var workText = (Label)item.FindControl("workName1") as Label;\n    string work = workText.Text;\n    string text = workDetails1.Text;\n    if (text == "   ")\n        text = "";\n\n    if (text == "")\n    {\n        if (!text.Contains(work))\n        {\n            text +="\u2022 " + work;\n            workDetails1.Text = text;\n        }\n    }\n    else if (!string.IsNullOrEmpty(work))\n    {\n        if (!text.Contains(work))\n        {\n            text += "\n\u2022 " + work;\n            workDetails1.Text = text;\n        }\n        else\n        {\n            workDetails1.Text = text;\n        }\n    }\n    UpdatePanel4.Update();	0
24438870	24183244	Serilog machine name enricher for rolling file sink	outputTemplate: "{Timestamp:HH:mm} [{Level}] {MachineName} ({ThreadId}) {Message}{NewLine}{Exception}"	0
11214669	11214628	Unable to Highlight Text in a TextBox	textBox1.HideSelection = false;\ntextBox1.Select(0, textBox1.Text.Length);	0
932395	932390	How do I save an Image from an url?	System.Net.WebClient wc = new System.Net.WebClient();\n\nwc.DownloadFile("http://www.domin.com/picture.jpg", @"C:\Temp\picture.jpg");	0
29971668	29971401	C# compare a list of IDs to each ID in a list of objects using LINQ	List<int> ints = new List<int> () { 1, 2, 3, 4, 5};\n\n  // For better performance when "ints" is long\n  HashSet<int> ids = new HashSet<int>(ints);\n\n  List<someObjectType> objects = new List<someObjectType> () { {1, "one"}, {6, "six"}, {45, "forty-five"} };\n\n  // if any matched?\n  boolean any = objects\n    .Any(item => ids.Contains(item.id));\n\n  // All that match\n  var objectsThatMatch = objects\n    .Where(item => ids.Contains(item.id));	0
5722846	5722581	AutoFixture - how do I call a method, how to set a private setter of an autoproperty?	fixture.Customize<MyClass>(c => \n    c.Do(mc => \n        mc.SetAssignableId(fixture.CreateAnonymous<int>())));	0
23283340	23283127	How to view console in SharpDevelop?	using System;\nusing System.Diagnostics;\nusing System.Windows.Forms;\n\nnamespace TestApp\n{\n    class MainForm : Form\n    {\n        private Random rd;\n        private const int buttonsCount = 42;\n\n        public MainForm()\n        {\n            rd = new Random();\n            Text = "Click on me!";\n        }\n\n        protected override void OnClick(EventArgs e)\n        {\n            compMode();\n        }   \n\n        public void compMode()\n        {\n            int rn = rd.Next(1, buttonsCount);\n            Debug.WriteLine("rn is {0}", rn);\n        }\n\n        public static void Main(string[] args)\n        {\n            Application.Run(new MainForm());\n        }\n    }\n}	0
18241078	18240918	C# Double Nullable with MySQL INSERT	var HotelList = \n       String.Join(",", Hotel.Select(m => String.Format("('{0}',{1},{2})",\n       MySqlHelper.EscapeString(m.Name),  m.MinRate.HasValue?("'"+m.MinRate.Value.ToString()+"'"):"NULL", m.MaxRate.HasValue?("'"+m.MaxRate.Value.ToString()+"'"):"NULL")));	0
31343965	31343865	How to add querystring values with RedirectToAction method that is pointing to a new Area?	return RedirectToAction("Login", "Account", new { area = "", timeout = "true" });	0
14959865	14959824	Convert List into Comma-Separated String	Console.WriteLine(String.Join(",", new List<uint> { 1, 2, 3, 4, 5 }));	0
31638958	31638915	Take each lines as group in c# using linq	var blocks = File.ReadLines(filename)\n                    .Select((s, i) => new { s, i })\n                    .GroupBy(x => x.i / 25)\n                    .Select(g => String.Join(" ", g.Select(x => x.s)))\n                    .ToList();	0
30265494	30264928	Save Textbox.text to a new Batchfile on my pc by button click	System.IO.File.WriteAllLines(@"D:\MyBatchFile.bat", ScriptWindow.Text);	0
3980551	3980469	Multiple client endpoints to the same WCF service	var endpoint = ApplicationSettings.IsRemote ? Resources.RemoteEndPoint: Resources.LocalEndPoint;\nvar service = new MyWCFService(new BasicHttpBinding(), new Endpoint(endpoint));	0
26586449	26585858	c# listbox with control names to change properties	// Get the selected text from the ListBox.\nstring name = ControlBox1.GetItemText(ControlBox1.SelectedItem);\n\n// Find the control that matches that Name. Assumes there is only ever 1 single match.\nControl control = ProjectPanel.Controls.Find(name, true).FirstOrDefault();\n\n// Set properties of the Control.\ncontrol.Name = "new name";\n\n// If you know it's a Label, you can cast to Label and use Label specific properties.\nLabel label = control as Label;\nlabel.Text = "some new text";	0
17178102	16869749	How to set the forecolor of a label control to match the selected outlook theme?	HKCU\Software\Microsoft\Office\12.0\Common\Theme	0
11729034	11728979	importing special characters	Microsoft.VisualBasic.FileIO	0
27471829	27471779	How to deserialize a JSON string so I can loop it in C#?	public class RequestPrivilege\n{\n    [JsonProperty("Fachr")]\n    public string Fachr { get; set; }\n\n    [JsonProperty("PrivId")]\n    public string PrivId { get; set; }\n}\n\n[HttpPost]\npublic string RequestPrivilege(string allRequests)\n{  \n    [...]\n    List<RequestPrivilege> allRequestsObj = JsonConvert.DeserializeObject<List<RequestPrivilege>>(allRequests);\n    [...]\n}	0
9610212	9610143	Putting data in dataset into datatable?	DataSet results = new DataSet();\nresults = excelReader.AsDataSet();\nresults.Tables["Sheet1"].TableName = "test";	0
10935066	10935020	C# - increment number and keep zeros in front	int i = 1;\nstring s = i.ToString().PadLeft(40, '0');	0
32009089	32008952	Syntax for mapping c# class types to Linq2Sql stored procedure input parameters	public partial class DataContext\n{\n     public someResult UpdatePerson(Person p)\n     {\n         return this.UpdatePerson(p.Name, p.Age);\n     }\n}	0
9108003	9093364	Sort several duplicate values in DataTable to one row	var grouped = from myRow in myDataTable.AsEnumerable()\n              group myRow by myRow.Field<int>("TIMESTAMP");\n\nforeach (var timestamp in grouped)\n{\n    string[] myRow = new string[5];\n    myRow[0] = timestamp.Key.ToString();\n\n    int i = 1;\n    foreach (var value in timestamp)\n    {\n      myRow[i] = value.Field<double>("VALUE").ToString();\n      i++;\n      if (i > 4)\n          break;\n    }\n\n    mySortedTable.Rows.Add(myRow);\n}	0
22615383	22614454	How to determine if a string contains a specific date in any format?	CultureTypes[] mostCultureTypes = new CultureTypes[] {\n            CultureTypes.NeutralCultures, \n            CultureTypes.SpecificCultures, \n            CultureTypes.InstalledWin32Cultures, \n            CultureTypes.UserCustomCulture, \n            CultureTypes.ReplacementCultures, \n            };\nCultureInfo[] allCultures;\nDateTime dt = new DateTime(1962, 01, 22);\n\n// Get and enumerate all cultures.\nallCultures = CultureInfo.GetCultures(CultureTypes.AllCultures);\nforeach (CultureInfo ci in allCultures)\n{\n    // Display the name of each culture.\n    Console.WriteLine("Culture: {0}", ci.Name);\n    Thread.CurrentThread.CurrentCulture = ci;\n    Console.WriteLine("Displaying short date for {0} culture:",\n                        Thread.CurrentThread.CurrentCulture.Name);\n    Console.WriteLine("   {0} (Short Date String)",\n                        dt.ToShortDateString());\n    Console.WriteLine();\n}	0
33104534	33104280	XML Reading Issue	XmlNode jobNo = itemNode.SelectSingleNode("field[@name='JobNo']");	0
4311927	4311874	How to pass csharp binding variable to Javascript function	OnClientClick="<%# string.Format("passAccessory('{0}');", Container.DataItem("variable")) %>"	0
20808136	20804798	Resolving dependency in Unity	container.RegisterType<IUserRepository>                \n           (new ContainerControlledLifetimeManager(),\n           new InjectionFactory(c => new UserEntityRepository \n              (new DefaultDataContextFactory<SampleDataContext>())));	0
17045317	17045263	how to create an hyperlink field programatically in a gridview, its setting 2 links	var firstCell = e.Row.Cells[0];\n firstCell.Controls.Clear();\n firstCell.Controls.Add(new HyperLink { "URL", "URL"});	0
9006679	9006374	Adding a Console via Programm logic	namespace TestService \n{\n   static class Program\n   {\n        [DllImport("kernel32.dll")]\n        static extern bool AllocConsole();\n\n        /// <summary>\n        /// The main entry point for the application.\n        /// </summary>\n        static void Main()\n        {\n            if (!Environment.UserInteractive)                                \n            {\n                ServiceBase[] ServicesToRun;\n                ServicesToRun = new ServiceBase[] \n                { \n                    new Service1() \n                };\n                ServiceBase.Run(ServicesToRun);\n            }\n            else \n            {\n                AllocConsole();\n                //Start Code that interfaces with console.\n            }           \n         }        \n     }\n }	0
16228372	16228108	How to update a line in a text file?	class TestClass\n{\n    static void Main(string[] args)\n    {\n        // not really good names for what it's worth\n        WritingMethod();\n        UpdatingMethod();\n    }\n}	0
6290231	6284056	Dragging a WPF user control	private TranslateTransform transform = new TranslateTransform();\n        private void root_MouseMove(object sender, MouseEventArgs e)\n        {\n            if (isInDrag)\n            {\n                var element = sender as FrameworkElement;\n                currentPoint = e.GetPosition(null);\n\n                transform.X += currentPoint.X - anchorPoint.X;\n                transform.Y += (currentPoint.Y - anchorPoint.Y);\n                this.RenderTransform = transform;\n                anchorPoint = currentPoint;\n            }\n        }	0
24443218	24443031	C# Convert List<string> to Dictionary<string, string> LINQ	string Json = "['1','value1','2','value2','3','value3']";\nvar json = Newtonsoft.Json.JsonConvert.DeserializeObject<List<string>>(Json);\n\nvar result = json.Select((v, i) => new {value = v, index = i})\n                 .Where(o => o.index%2 == 0)\n                 .ToDictionary(o => o.value, o => json[o.index + 1]);\n\nforeach (var pair in result)\n{\n    Console.WriteLine("key: {0}, value: {1}", pair.Key, pair.Value);\n}	0
1195854	1195829	Do I have to Close() a SQLConnection before it gets disposed?	// System.Data.SqlClient.SqlConnection.Dispose disassemble\nprotected override void Dispose(bool disposing)\n{\n    if (disposing)\n    {\n        this._userConnectionOptions = null;\n        this._poolGroup = null;\n        this.Close();\n    }\n    this.DisposeMe(disposing);\n    base.Dispose(disposing);\n}	0
2165483	2165269	C# How to design panel for later use..(Settings screen)	public partial class Form1 : Form {\n    public Form1() {\n        InitializeComponent();\n        treeView1.AfterSelect += new TreeViewEventHandler(treeView1_AfterSelect);\n    }\n    private UserControl mActivePanel;\n\n    void treeView1_AfterSelect(object sender, TreeViewEventArgs e) {\n        UserControl newPanel = null;\n        switch (e.Node.Index) {\n            case 0: newPanel = new UserControl1(); break;\n            case 1: newPanel = new UserControl2(); break;\n            // etc...\n        }\n        if (newPanel != null) {\n            if (mActivePanel != null) {\n                mActivePanel.Dispose();\n                this.Controls.Remove(mActivePanel);\n            }\n            newPanel.Dock = DockStyle.Fill;\n            this.Controls.Add(newPanel);\n            this.Controls.SetChildIndex(newPanel, 0);\n            mActivePanel = newPanel;\n        }\n    }\n}	0
19621227	19407116	Sorting DataGridView based on cell Tags	e.SortResult = Convert.ToInt32(dataGridView1[e.Column.Index,e.RowIndex1].Tag).CompareTo(Convert.ToInt32(dataGridView1[e.Column.Index,e.RowIndex2].Tag));	0
21571351	21571198	How to use linq and string.EndsWith(<1 of N items in an array>)	if (a.Any(yourString.EndsWith))\n{\n    //your string ends with one of those endings.\n}	0
6923737	6923459	How to subscribe to application shutdown event in class library	using System.Windows.Forms;\n\npublic class B\n{\n    public B()\n    {\n        Application.ApplicationExit += new EventHandler(Application_ApplicationExit);\n    }\n\n    void Application_ApplicationExit(object sender, EventArgs e)\n    {\n        //do cleanup of your class\n    }\n}	0
12836480	12836374	Using transactions with linq to entities	using(var context = new XYZContext())\n  {   \n      context.Database.Connection.Open();\n      using (TransactionScope s = context.Connection.BeginTransaction())\n      {\n\n          Int32 count = (from xyz in context.XYZs\n                           where xyz.Name == "SameName"\n                           select xyz.Name).Count();\n          Assert.AreEqual(count, 1);\n          s.Commit()\n        }\n   }	0
1155432	1155418	How do I position a DataGridView to a specific row (so that the selected row is at the bottom)?	if (dataGridView.FirstDisplayedScrollingRowIndex + dataGridView.DisplayedRowCount(false) <= selectedRowIndex)\n{\n    dataGridView.FirstDisplayedScrollingRowIndex =\n        selectedRowIndex - dataGridView.DisplayedRowCount(false) + 1;\n}	0
5352834	5350100	How to get an XML value out of another XML value at C#	using System.Data;\n\nDataSet dataSet = new DataSet();\ndataSet.ReadXml(xmlFullPath, XmlReadMode.Auto);\nDataRow[] dataRows = dataSet.Tables["user"].Select("hwid like 'BFEB-FBFF-0000-06FD-C87C-FA30'");\nif (dataRows.Length == 0)\n    return;\nstring sUser = dataRows[0]["userName"].ToString();	0
22277764	22277752	Inserting into multiple columns access databse	AccessDataSource1.InsertCommand = "\nINSERT INTO [CoursesTaken] (StudentID, CourseID) \nVALUES ('" + TextBox1.Text + "', '" + TextBox2.Text + "');";   \nAccessDataSource1.Insert();AccessDataSource1.DataBind();	0
1556282	1556011	How do you change specific data in a datatable column?	foreach (DataRow row in dt.Rows)\n{\n  row["ColumnName"] = "changed"; //Not changing it?!\n}	0
32204993	32204674	How do i get rid of an extra row created by Datagrid	CanUserAddRows = False	0
23650930	23650767	Getting a value from datatable	var results = from myRow in myDataTable.AsEnumerable()\n                  where myRow.Field<int>("RowNo") == 1\n                  select myRow;	0
9914083	9912846	Calling a method in a FACTORY class when application is closed/disposed without using Application's Dispose() method	Public Class MyFactory \n    Public Shared/Static theStuffICreated as List(Of Stuff)\n    Shared/Static Sub New()\n        AddHandler AppDomain.CurrentDomain.ProcessExit, AddressOf ApplicationExitHandler \n    End Sub\n\n    Public Shared/Static Sub ApplicationExitHandler(ByVal s As Object, e As EventArgs)\n        RemoveHandler AppDomain.CurrentDomain.ProcessExit, AddressOf ApplicationExitHandler\n        ThingsToDoWhenClassIsDestroyed()\n    End Sub \n\n    Public Shared/Static Sub Create(...) \n         ... \n    End Sub \n\n    Public Shared/Static Sub ThingsToDoWhenClassIsDestroyed() \n         ... \n    End Sub\n\nEnd Class	0
5552746	5552735	Finding all integers that exist in list1 that don't exist in list2 with fewest lines of code?	list1.Except(list2)	0
7384999	7383855	how to save data from this partial view into Vehicle_driver Table?? using Entity framework	public Vehicle_driver Assign(Driver d, Vehicle v, DateTime start, DateTime end) {\n  using (MyContext context = new MyContext()) {\n    Vehicle_driver assignment = context.CreateObject<Vehicle_driver>();\n    assignment.VEHICLE_ID = v.ID;\n    assignment.DRIVER_ID = d.ID;\n    assignment.SERVICE_START_DATE = start;\n    assignment.SERVICE_END_DATE = end;\n    context.Vehicle_drivers.AddObject(assignment);\n    context.SaveChanges();\n    return assignment;\n  }\n}	0
7899393	7899088	How to Create a dynamic class and add it to project	Project/Properties/BuildEvents/Pre-build event command line	0
945589	945545	How do I determine the colour mode of an uploaded image in ASP.Net	Image img = Image.FromStream( yourFileUpload.PostedFile.InputStream );	0
13249025	13248971	Resolve HostName to IP	IPHostEntry hostEntry;\n\nhostEntry= Dns.GetHostEntry(host);\n\n//you might get more than one ip for a hostname since \n//DNS supports more than one record\n\nif (hostEntry.AddressList.Length > 0)\n{\n      var ip = hostEntry.AddressList[0];\n      Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);\n      s.Connect(ip, 80);\n}	0
12669395	12669284	Convert DataPoint to Point	//if the distance from the parent node (p) to the neighbor node is less than the transmit power, then draw \nif (Math.Sqrt(Math.Pow((p.XValue - pts[j].XValue), 2) + Math.Pow((yval - yValNeighbors), 2)) <= intTransPower)\n{\n    var point = new System.Drawing.Point((int)p.XValue, (int)p.YValue); \n    gr.Graphics.DrawLine(pen, point, pts[j);\n}	0
4529859	4527285	print output for each value of i,j	MessageBox.Show("Shortest distance from" + i + " to " + j + " isnnt: " + str_intvalues);	0
27104164	27104089	What is my mistake in implementing Foreign Key with EF 6?	public class Person\n{\n    public int Id { get; set; }\n    public virtual ICollection<Anime> DirectedAnimes { get; set; }\n}\n\npublic class Anime\n{\n    public int Id { get; set; }\n    public int DirectorId { get; set; }\n    public virtual Person Director { get; set; }\n}	0
14950270	14817296	Read pixels from a rectangle in an OpenGL texture	public Bitmap GetBitmap()\n{\n    int fboId;\n    GL.Ext.GenFramebuffers(1, out fboId);\n    CheckGLError();\n    GL.Ext.BindFramebuffer(FramebufferTarget.FramebufferExt, fboId);\n    CheckGLError();\n    GL.Ext.FramebufferTexture2D(FramebufferTarget.FramebufferExt, FramebufferAttachment.ColorAttachment0Ext, TextureTarget.Texture2D, TextureId, 0);\n    CheckGLError();\n\n    Bitmap b = new Bitmap(Width, Height);\n    var bits = b.LockBits(new Rectangle(0, 0, Width, Height), ImageLockMode.WriteOnly, System.Drawing.Imaging.PixelFormat.Format32bppArgb);\n    GL.ReadPixels(Rect.Left, Rect.Top, Width, Height, OpenTK.Graphics.OpenGL.PixelFormat.Bgra, PixelType.UnsignedByte, bits.Scan0);\n    GL.Ext.BindFramebuffer(FramebufferTarget.FramebufferExt, 0);\n    GL.Ext.DeleteFramebuffers(1, ref fboId);\n    b.UnlockBits(bits);\n\n    return b;\n}	0
10123694	10121949	Get root config files path inside dll	Configuration config;\n\n        if (System.Web.HttpContext.Current != null &&\n            System.Web.HttpContext.Current.Request.PhysicalPath.Equals(String.Empty) == false)\n        {\n            config = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration(HttpRuntime.AppDomainAppVirtualPath);\n        }\n        else\n        {\n            config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);\n        }	0
28311901	28311641	Separate Legends for Multiple ChartAreas in Single Chart	// Add a second legend\n            Legend secondLegend = new Legend("Second");\n            secondLegend.BackColor = Color.FromArgb(((System.Byte)(220)), ((System.Byte)(255)), ((System.Byte)(255)), ((System.Byte)(255)));\n            secondLegend.BorderColor = Color.Gray;\n            secondLegend.Font = this.Chart1.Legends["Default"].Font;\n\n            this.Chart1.Legends.Add(secondLegend);\n\n            // Associate Series 2 with the second legend \n            this.Chart1.Series["Series 2"].Legend = "Second";	0
20049385	20049264	Add 'expand details' button on Devexpress gridcontrol cell	private void buttonEdit1_ButtonPressed(object sender, ButtonPressedEventArgs e) {\n    ButtonEdit editor = (ButtonEdit)sender;\n    int buttonIndex = editor.Properties.Buttons.IndexOf(e.Button);\n    if (buttonIndex == 0) \n    {\n       MessageBox.Show("Aditional details");\n    }\n}	0
22913397	22913296	convert a DateTime to Oracle DateTime	DateTime input = new DateTime(...);\nOracleDateTime result = (OracleDateTime) input;\n...	0
3615411	3615311	create a generic method that sorts List<T> collections	private List<T> SortList<T>(List<T> collection, SortOrder order, string propertyName) where T : class\n        {\n            if (order == SortOrder.Descending)\n            {\n                return collection.OrderByDescending(cc => cc.GetType().GetProperty(propertyName).GetValue(cc, null)).ToList();\n            }\n\n            return collection.OrderBy(cc => cc.GetType().GetProperty(propertyName).GetValue(cc, null)).ToList();\n        }	0
21918101	21916167	expire cache at specific time	ctx.Cache.Insert("stmodel", stModel, null,\n             MyClass.getSpecificDateTime(), System.Web.Caching.Cache.NoSlidingExpiration, System.Web.Caching.CacheItemPriority.Default, OnCachedItemRemoved);\n\n public static DateTime getSpecificDateTime()\n    {\n        TimeSpan currentTime = DateTime.Now.TimeOfDay;\n        DateTime newTime = DateTime.Now;\n\n        if (currentTime.Hours < 7){\n            newTime = newTime.Date + new TimeSpan(7, 0, 0);\n        }else if (currentTime.Hours < 11){\n            newTime = newTime.Date + new TimeSpan(11, 0, 0);\n        }else if (currentTime.Hours < 15) {\n            newTime = newTime.Date + new TimeSpan(15, 0, 0);\n        }else if (currentTime.Hours < 19){\n            newTime = newTime.Date + new TimeSpan(19, 0, 0);\n        }else {\n            newTime = DateTime.Now.AddDays(1);\n            newTime = newTime.Date + new TimeSpan(7, 0, 0);\n        }   \n\n        return newTime;\n    }	0
19507136	19499521	Listbox or Textbox in GridView	this.myGridView.ShowingEditor += (sender, args) => \n{ \n    var gridView = sender as GridView;\n\n    if(null != gridView)\n    {\n        var currentRowHandle = gridView.FocusedRowHandle;\n        var currentType = gridView.Rows[currentRowHandle].GetType();\n\n        if(currentType == typeof(TypeA))\n        {\n             //Make a ListBox\n        }\n\n        if(currentType == typeof(TypeB))\n        {\n            //Make a TextBox\n        }\n    }\n}	0
26518216	26517155	Port VS2010 CodeGenerator extension to VS2013	[ProvideBindingPath]	0
28164946	28164746	Add property to all objects of json array	var extendedEmployees = employees.Select(employee => new\n                        {\n                            employee.Id,\n                            employee.Name, \n                            Department = "Computer Science",\n                        }\n\nvar json = JsonConvert.Serialize(extendedEmployees)	0
8240980	8240861	Compare value to array of strings using StartsWith	var result =  myCollection.Where(c =>  \n                           exceptions.All(e => \n                                       !c.Property[3].Value.StartsWith(e));	0
1723406	1723262	Validating a Timezone String and Returning it as Minutes	string tz = userList.Rows[0][1].ToString().Trim();\n//Timezones can take the form of + or - followed by hour and then minutes in 15 minute increments.\nMatch tzre = new Regex(@"^(\+|-)?(0?[0-9]|1[0-2])(00|15|30|45)$").Match(tz);\nif (!tzre.Success)\n{\n    throw new\n        myException("Row 1, column 2 of the CSV file to be imported must be a valid timezone: " + tz);\n}\nGroupCollection tzg = tzre.Groups;\ntz = (new TimeSpan(int.Parse(tzg[1].Value + tzg[2].Value), int.Parse(tzg[3].Value), 0).TotalMinutes).ToString();	0
24323352	24323175	Interface variable not able to access all class methods	class MySecondName:ILastName\n{\n    public string SecondName()\n    {\n        return "Michael";\n    }\n    public string LastName()\n    {\n        return "Dutt";\n    }\n}\n\nILastName obj;\nint i = new Random().Next() % 2;\nif (i == 0) obj = new MyName();\nelse obj = new MySecondName();	0
24722497	24602727	ToolStrip with custom ToolStripControlHost makes tab order focus act weird	public override bool Focused {\n    get { return _textBox.Focused; }\n}	0
13006456	13006411	Concatenate a constant string to each item in a List<string> using LINQ	List<string> yourList = new List<string>() { "X1", "Y1", "X2", "Y2" };\nyourList = yourList.Select(r => string.Concat(r, 'y')).ToList();	0
15274694	15271621	How to display/put a button inside an ObjectListView column?	// assign an ImageList containing at least one image to SmallImageList\nobjectListView1.SmallImageList = imageList1;\n\n// always display image from index 0 as default image for deleteColumn\ndeleteColumn.ImageGetter = delegate {\n    return 0;\n};	0
24682356	24564120	Issue when trying to read multiplte entity resultsets from a stored procedure	var entities = Context.ObjectContext.Translate<MyEntity>(reader, "MyEntities", MergeOption.AppendOnly);	0
20203341	20201586	create a toolstrip for each toolstripbutton located on a main toolstrip	this.Controls.Add(cts);\ncts.BringToFront();	0
18058168	18058069	populate combobox with datatable select query	cboxClientSite.DataSource = parentfrm._ClientsSites.Select(@"client_id = " + cboxClientName.SelectedValue).CopyToDataTable();	0
12428313	12410865	EnumerableCollectionView to ListCollectionView with DataGrids	private void PerformCustomSort(DataGridColumn column) {\n        ListSortDirection direction = (column.SortDirection != ListSortDirection.Ascending) ? ListSortDirection.Ascending : ListSortDirection.Descending;\n        column.SortDirection = direction;\n\n        List<DataGridRow> dgRows = new List<DataGridRow>();\n        var itemsSource = dataGrid1.ItemsSource as IEnumerable;\n\n        foreach (var item in itemsSource) {\n            DataGridRow row = dataGrid1.ItemContainerGenerator.ContainerFromItem(item) as DataGridRow;\n            if (null != row) {\n                dgRows.Add(row);\n            }\n        }\n\n        ListCollectionView lcv = new ListCollectionView(dgRows);\n        SortOrders mySort = new SortOrders(direction, column);\n        lcv.CustomSort = mySort;\n        dataGrid1.ItemsSource = lcv;\n    }	0
14388723	14388582	Combining similar methods	public static int Calculate(DateTime startDate, DateTime endDate)\n{\n    string sql = @"SELECT SUM(timestamp) \n                   FROM table1 \n                   WHERE date BETWEEN @startDate AND @endDate";\n    using(var con=new SqlConnection(connectionString))\n    using (var cmd = new SqlCommand(sql, con))\n    {\n        con.Open();\n        cmd.Parameters.AddWithValue("@startDate", startDate);\n        cmd.Parameters.AddWithValue("@endDate", endDate);\n        int sum = (int)cmd.ExecuteScalar();\n        return sum;\n    }\n}	0
15258796	15257327	Fluent XML translation using dynamic type	payload.Name.Value	0
5336905	5336858	How to redirect to action from JavaScript method?	function DeleteJob() {\n    if (confirm("Do you really want to delete selected job/s?"))\n        window.location.href = "your/url";\n    else\n        return false;\n}	0
3132013	3131986	WebRequest is getting generated from another IP instead my system IP?	request.Proxy = GlobalProxySelection.GetEmptyWebProxy();	0
11293220	11292940	Stored procedure output parameter asp.net c#	int errorId = 0;\n\nusing(SqlConnection sqlConnection = new SqlConnection(connectionString))\n{\n    using(SqlCommand cmd = new SqlCommand("YourStoredProcedureName", sqlConnection))\n    {\n    cmd.CommandType=CommandType.StoredProcedure;\n    SqlParameter parm=new SqlParameter("@username", SqlDbType.VarChar); \n    parm.Value="mshiyam";\n    parm.Direction =ParameterDirection.Input ; \n    cmd.Parameters.Add(parm); \n\n    SqlParameter parm2=new SqlParameter("@path",SqlDbType.VarChar); \n    parm2.value = "Some Path";\n    parm2.Direction=ParameterDirection.Output;\n    cmd.Parameters.Add(parm2); \n\n\n    SqlParameter parm3 = new SqlParameter("@errorId",SqlDbType.Int);\n    parm3.Direction=ParameterDirection.Output; \n    cmd.Parameters.Add(parm3); \n\n    sqlConnection.Open(); \n    sqlConnection.ExecuteNonQuery();\n\n    errorId = cmd.Parameters["@errorId"].Value; //This will 1 or 0\n   }\n\n}	0
23023985	23023833	C# WPF How to set MainWindow.contentControl.Content from already opened UserControl	(Application.Current.MainWindow.FindName("contentControl") as ContentControl).Content = new MyUserControlNEW();	0
19341615	19340455	How to pass dictionary items to a function in C#	public static MvcHtmlString ActionMenuItem(\n    this HtmlHelper htmlHelper,\n    String linkText,\n    String actionName,\n    String controllerName,\n    String iconType = null,\n    string classCustom = null,\n    params KeyValuePair<string, string>[] subMenus)\n{ ... }\n\nvar dict = new Dictionary<string, string>()\n{\n    { "a", "b" },\n    { "c", "d" },\n};\n\n*.ActionMenuItem(*, *, *, *, *, dict.ToArray());	0
15896481	15737294	How to get datagrid cell object form its template field wpf	public static T FindAncestor<T>(DependencyObject dependencyObject)\n        where T : class\n     {\n        DependencyObject target = dependencyObject;\n        do\n        {\n            target = VisualTreeHelper.GetParent(target);\n        }\n        while (target != null && !(target is T));\n        return target as T;\n       }	0
11694205	11694121	Listing DataTable values	List<string> test = new List<string>();\n\nforeach (DataRow row in id.Rows)\n{\n   test.Add(row[0].ToString());\n}\n\nMessageBox.Show(String.Join(",", test.ToArray()));	0
22508974	22498005	Convert YYYY.(MM/12) Using Custom Date Formats	var someDateString = "2014.25";\nif(someDateString.Contains(".")) {\n    var parts = someDateString.Split('.');\n    var year = Int32.Parse(parts[0]);\n    var secondsPerYear = DateTime.IsLeapYear(year) ? 31622400 : 31536000;\n    var seconds = Double.Parse(parts[1])/100 * secondsPerYear;\n    var newDate = new DateTime(year, 1, 1).AddSeconds(seconds);\n}	0
15960165	15958691	Query first element in all columns in a jagged array	string[][] table = new string[][] { \n    new string[] { "ID", "Name", "Age" }, \n    new string[] { "1", "Jim", "25" },\n    new string[] { "2", "Bob", "30" },\n    new string[] { "3", "Joe", "35" }\n};\n\n//get index of column to look at\nstring columnName = "Name";\nvar columnIndex = Array.IndexOf(table[0], columnName, 0);\n\n// skip the title row, and then skip columns until you get to the proper index and get its value\nvar results = table.Skip(1).Select(row => row.Skip(columnIndex).FirstOrDefault());\n\nforeach (var result in results)\n{\n    Console.WriteLine(result);\n}	0
11877870	11877779	How to add data to the listbox by clicking Save Button :	private void button1_Click(object sender, EventArgs e)\n{\n    listBox1.Items.Add(textBox1.Text);\n    listBox1.Items.Add(textBox2.Text);\n    listBox1.Items.Add(textBox3.Text);\n    listBox1.Items.Add(textBox4.Text);\n}\n\nprivate void listBox1_SelectedIndexChanged(object sender, EventArgs e)\n{\n    /*listBox1.Items.Add(textBox1.Text);\n    listBox1.Items.Add(textBox2.Text);\n    listBox1.Items.Add(textBox3.Text);\n    listBox1.Items.Add(textBox4.Text);*/\n}	0
13132085	13131793	Display Ballon Tip on Button Click	public partial class Form1 : Form\n{\n    public Form1()\n    {\n        InitializeComponent();\n    }\n\n    private void Form1_Load(object sender, EventArgs e)\n    {\n        toolTip1.IsBalloon = true;\n        toolTip1.Popup += new PopupEventHandler(toolTip1_Popup);\n        toolTip1.SetToolTip(textBox1, "");\n    }\n\n    void toolTip1_Popup(object sender, PopupEventArgs e)\n    {\n        if (toolTip1.GetToolTip(e.AssociatedControl) == "")\n            e.Cancel = true;\n\n    }\n\n    private void timer1_Tick(object sender, EventArgs e)\n    {\n        timer1.Stop();\n        toolTip1.RemoveAll();\n\n    }\n\n    private void textBox1_Validating(object sender, CancelEventArgs e)\n    {\n        int temp;\n        if (!int.TryParse(textBox1.Text, out temp))\n            showTip("Validation Error", (Control)sender);\n\n    }\n\n    private void showTip(string message, Control destination)\n    {\n        toolTip1.Show(message, destination);\n        timer1.Start();\n    }\n}	0
6659436	6659334	Exporting DataGrid in MVVM way	public string ToCsv(IEnumerable items)\n{\n    var csvBuilder = new StringBuilder();\n    var properties = typeof(T).GetProperties().Where(prop => Columns[prop.Name].FileSize.IsVisible).OrderBy(prop => Column[prop.Name].FileSize.Index).ToArray();\n\n    foreach (T item in items)\n    {\n        string line = string.Join(",",properties.Select(p => p.GetValue(item, null));\n        csvBuilder.AppendLine(line);\n    }\n    return csvBuilder.ToString();\n}	0
1406804	1403984	How to redraw Node in TreeView (WinForms)	using (Graphics g = Graphics.FromHwnd(Tree.Handle))\n{\n    TreeNode node = myBlinkyNode;\n    if (node != null)\n    {\n        using(Region myRegion = new Region(node.Bounds))\n            myRegion.Xor(xorRect);\n    }\n}	0
6686585	6686482	How to translate SQL statement with multiple join conditions based on subquery to LINQ	var results = from id in db.IDTable\n              join n in db.NameTable on id.Id equals n.IDTableID\n              where n.Id = (\n                  from n2 in db.NameTable\n                  where n2.IDTableID = 11\n                  orderby n2.DateInserted desc\n                  ).First()\n              select new { id, n };	0
3105225	3105158	Design guidelines for Enumeration	class Currency\n{\n     public static reaonly IEnumerable<Currency> Currencies = new List<Currency>\n     {\n         new Currency { Name = "USD", CurrencySign = "$" },\n         new Currency { Name = "EUR", CurrencySign = "???" }\n     }\n\n     public string Name {get; private set;}\n\n     public string CurrencySign {get; private set;}\n\n     public override ToString() { return Name; }\n}	0
4190590	4190533	How to find substring from string without using indexof method in C#?	class Program\n{\n    static void Main(string[] args)\n    {\n        string str = "abcdefg";\n        string substr = "cde";\n        int index = IndexOf(str, substr);\n        Console.WriteLine(index);\n        Console.ReadLine();\n    }\n\n    private static int IndexOf(string str, string substr)\n    {\n        bool match;\n\n        for (int i = 0; i < str.Length - substr.Length + 1; ++i)\n        {\n            match = true;\n            for (int j = 0; j < substr.Length; ++j)\n            {\n                if (str[i + j] != substr[j])\n                {\n                    match = false;\n                    break;\n                }\n            }\n            if (match) return i;\n        }\n\n        return -1;\n    }\n}	0
21544554	19402801	How to apply filter to DataView with Multiple "AND" conditions	List<string> selectedAddress = new List<string>();\nprotected DataView GetSelectedItems()\n{\n    DataView dvResult = new DataView(dtresult);\n    string query = "";\n    int count = selectedAddress.Count();\n\n    for (int j = 0; j < selectedAddress.Count; j++)\n    {\n        string val = selectedAddress[j].ToString() + ",";\n        query += val;\n    }\n\n    query = query.Remove(query.Length - 1);\n    dvResult.RowFilter = "ID IN(" + query + ")";\n    return dvResult;\n}	0
24213553	24213293	Representing a small number of static objects	if (user == "mary")	0
18812877	18811467	Extract KeyCode from KeyData	Keys code = keyData & Keys.KeyCode;	0
10633423	10633137	Sending Mail with an attachment using SMTP	MailMessage message = new MailMessage(new MailAddress(txtSenderMail.Text, txtSenderName.Text), new MailAddress(txtToAdd.Text);\n                message.IsBodyHtml = true;\n                message.Subject = txtSubject.Text;\n                message.Body = txtMail.Text;\n                message.Priority = MailPriority.High;\n                SmtpClient smtp = new SmtpClient(YOUR SMTP ADDRESS, YOUR SMTP PORT);\n                smtp.EnableSsl = false;\n                smtp.UseDefaultCredentials = false; //you can use this line if you have your own SMTP server if not set it **True** (also you can get server address of your internet service company. like mine is: smtp.datak.ir  but it only works on your own computer not Web server. webservers could have SMTP too.) \n                smtp.Send(message);	0
5493504	5493403	Get DropDown Values from Database Table	var description = Request.Form["txtProduct"].ToString();\nusing (SqlConnection _con = new SqlConnection(getProdValue))\nusing (SqlCommand cmd = new SqlCommand("SELECT UnitPrice FROM Products WHERE Description = '" + description "'", _con))\n{\n    cmd.Connection.Open();\n    var unitPrice = cmd.ExecuteScalar();\n    txtUnitPrice.Text= unitPrice.ToString("###,###0.000");       \n}	0
9033051	9032936	Ignoring the null value in XML Serialization	public SubscriptionProductIdentifierType[] SubscriptionProductIdentifier {\n    get {\n        return this.subscriptionProductIdentifierField.Where(s=>s!=null).ToArray();\n    }\n...\n}	0
25919187	25892460	How to search for a file in DataGgridView which is without database	(dataGridView1.DataSource as DataTable).DefaultView.RowFilter\n            = string.Format(@"`Drawing Number` LIKE '%{0}%' OR `Release Path` LIKE '%{0}%'", textBox1.Text);\n        dataGridView1.Focus();\n        textBox1.Focus();\n        int rowCount = dataGridView1.BindingContext[dt].Count;\n        if (rowCount == 0)\n        {\n            MessageBox.Show("No results");\n        }	0
24426989	24425796	Can client credentials be read from within service implementation?	OperationContext.Current.ServiceSecurityContext.PrimaryIdentity.Name	0
692466	677850	Create custom generic list with bitmapimage	public class ImageLoader\n{\n    string mediaid;\n    BitmapImage thumbnail;\n\n    public string MediaId\n    {\n        get { return mediaid; }\n        set { mediaid = value; }\n    }\n\n    public BitmapImage Thumbnail\n    { \n        get { return thumbnail; } \n        set { thumbnail = value; } \n    }\n\n    public ImageLoader(string mediaid, BitmapImage b)\n    {\n        this.mediaid = mediaid;\n        this.thumbnail = b;\n    }\n}	0
21486476	21486408	How to merge xml app.config files outside of the build process	D:\Utils\WebConfigTransformRunner.exe App.config App.production.config App.config	0
3292285	3292262	How do I pass model values as javascript function parameters from inside an asp.net mvc Html helper such a Html.Radio?	onClick = String.Format("setData('{0}', '{1}')", item.Association, item.ReviewData)	0
20392736	20392666	C# How do you query a subset of a Dictionary's entries based on the Value's type using Linq?	Dictionary<string, int> IntData = Data.Where(k => k.Value is int)\n   .ToDictionary(kv => kv.Key, kv => (int) kv.Value);	0
7743624	7743593	How can i get the type name value of an object as a string?	string myString = object.GetType().ToString();	0
33785687	33785476	loop ienumerable and get values	var joinPreRes = from t1 in db.preguntas_respuestas\n                          join t2 in db.respuesta1\n                          on t1.id_respuesta equals t2.id\n                          where t1.id_pregunta == id\n                          group new\n                          {\n                              t1.id,\n                              t1.id_respuesta,\n                              t2.respuesta_visual,\n                              t2.respuesta_valor\n                          } by t1.id into GroupedItems\n                          select GroupedItems;\n\n\nforeach (var a in joinPreRes)\n{\n    // a.Key   is the t1.id\n\n    foreach (var subItem in a)\n    {\n        // subItem.id_respuesta   <-   other fields/properties\n        // subItem.respuesta_valor   <-   other fields/properties\n    }\n}	0
3787619	3787561	How to ensure certain properties are always populated when returning object from DAL?	public class QuestionExtended : Question\n{\n    public QuestionExtended(IEnumerable<Option> options) : base()\n    {\n        OptionList = new List<Option>(options);\n    }\n\n    public List<Option> OptionList { get; private set;}\n}	0
15091622	15091300	POSTing JSON to URL via WebClient in C#	var baseAddress = "http://www.mysite.com/1.0/service/action";\n\n        var http = (HttpWebRequest)WebRequest.Create(new Uri(baseAddress));\n        http.Accept = "application/json";\n        http.ContentType = "application/json";\n        http.Method = "POST";\n\n        string parsedContent = <<PUT HERE YOUR JSON PARSED CONTENT>>;\n        ASCIIEncoding encoding = new ASCIIEncoding();\n        Byte[] bytes = encoding.GetBytes(parsedContent);\n\n        Stream newStream = http.GetRequestStream();\n        newStream.Write(bytes, 0, bytes.Length);\n        newStream.Close();\n\n        var response = http.GetResponse();\n\n        var stream = response.GetResponseStream();\n        var sr = new StreamReader(stream);\n        var content = sr.ReadToEnd();	0
17558211	17557991	PresentationFramework in Silverlight 5	public interface IMultiValueConverter\n  {   \n      object Convert(object[] values, Type targetType, object parameter, \n                      CultureInfo culture);\n\n      object[] ConvertBack(object value, Type[] targetTypes, object parameter,\n                           CultureInfo culture);       \n  }	0
5768008	5740190	How to execute PowerShell scripts in C# using the Task Parallel Library	internal Task RunScript(PowerShell powerShell, Runspace runspace, Script script, IDictionary parameters = null, Action<ICollection<PSObject>> callback = null, object state = null)\n    {\n        SetupScriptRun(powerShell, runspace, script, parameters);\n\n        return Task.Factory.StartNew<ICollection<PSObject>>((o) =>\n            {\n                var results = powerShell.Invoke();\n                LogWarningsAndErrors(powerShell, runspace, script, parameters);\n\n                if (callback != null)\n                {\n                    callback(results);\n                }\n\n                return results;\n            }, state);\n    }	0
26995842	26979000	CORS enabled Web API fails to add header	The collection of headers 'accept,content-type' is not allowed	0
25949202	25947992	Difficulties generating a matrix table with LINQ	someDateTime.Month.ToString("MMMM")	0
14810846	14810817	Enum to int casting for array index	inputs[(int)Phonemes.Phoneme0][(int)Features.PhonemeID] = 1;	0
12239544	12238826	How to make an event: click on random area in ListView?	void listview1_MouseUp(object sender, MouseEventArgs e)\n    {\n        ListViewItem item = listview1.GetItemAt(e.X, e.Y);\n        ListViewHitTestInfo info = listview1.HitTest(e.X, e.Y);\n\n        if ((item != null) && (info.SubItem != null))\n        {\n            //item.SubItems.IndexOf(info.SubItem) gives the column index\n            MessageBox.Show(item.SubItems.IndexOf(info.SubItem).ToString());\n        }\n    }	0
20432042	20431926	Incrementing the value of item in list<keyvaluepair<string, int>> if key already exists	var dict = new Dictionary<string, int>(StringComparer.OrdinalIgnoreCase);\nif(dict.ContainsKey(name))\n{\n   dict[name] += 1;\n}\nelse\n{\n   dict[name] = 1;\n}	0
10675898	10675857	Failed To Convert Parameter Value From A String To A Int32	command.Parameters.Add("@storeCode", SqlDbType.Int).Value = Convert.ToInt32(storeCode);	0
18014032	17992398	How to upload PhotoResult to a server?	byte[] imgArray = new byte[(int)appGlobal.appData.selectedPhoto.ChosenPhoto.Length];\nappGlobal.appData.selectedPhoto.ChosenPhoto.Position = 0;\nappGlobal.appData.selectedPhoto.ChosenPhoto.Read(imgArray, 0, (int)appGlobal.appData.selectedPhoto.ChosenPhoto.Length);\nappGlobal.appData.selectedPhoto.ChosenPhoto.Seek(0, SeekOrigin.Begin);\n\nrequest.AddFile("image", imgArray, "image");	0
23755633	23754954	How I can filter a Xml File with a Attribute?	// string group = GetGroup(xmlpath, "Hessen"); // returns KV-IT\n// string group2 = GetGroup(xmlpath, "Berlin"); //DBG_Update\n\nprivate string GetGroup(string xml, string id)\n{\n    XDocument document;\n    XElement element;\n\n    try\n    {\n        document = XDocument.Load(xml);\n\n        element = document.Elements("Permissiongroup").Elements(("Permission")).FirstOrDefault(t => t.Attribute("id").Value == id);\n\n        if (element != null)\n        {\n            return element.Attribute("display").Value;\n        }\n        else\n        {\n            return string.Empty;\n        }\n    }\n    catch (Exception ex)\n    {\n        return null;\n    }\n    finally\n    {\n        document = null;\n        element = null;\n    }\n\n}	0
14237041	14230437	How to pass the DTO having property of Type Exception from RIA service	[DataContract]\npublic Class DTO\n{\n    [DataMember]\n    public Exception ex {get;set;}\n}	0
32772437	32772271	Parse URL with Regex C#	var uri = new Uri("blahblahblah.aspx?NUMBER=8798494651&FULLNAME=Ronald");\nvar query = HttpUtility.ParseQueryString(uri.Query);\n\nvar var1 = query.Get("NUMBER");\nvar var2 = query.Get("FULLNAME");	0
9306473	9306443	How can I find out why my XML file is already in use?	writer.Close();	0
30867800	30867703	Load all user controls of a form on start	for(int i=1; i < tabControlName.TabPages.Length; i++)\n    tabControlName.SelectedIndex = i;\ntabControlName.SelectedIndex = 0;	0
32166310	32166205	dynamic generating variable in C#	List<List<int>> myList = new List<List<int>>();\n\nint NoOfItems = Convert.ToInt32(txt.Text);\n\nfor(int i=0;i<NoOfItems;i++)\n{\n   myList.Add(new List<int>();)\n}	0
24746264	24746170	Implicit conversion of method to Func in C#	Func<int, IEnumerable<int>> f = Compose<int,IEnumerable<int>,IEnumerable<int>>(printAll, g);	0
28773128	28705498	GridView Edit - Check Row Color	if (GridView1.Rows[e.NewEditIndex].BackColor != Color.SeaGreen &&\n                GridView1.Rows[e.NewEditIndex].BackColor != Color.IndianRed)\n        {\n            e.Cancel = true;\n            errorLabel.Text = "Please scan roll before updating QtyRun";\n        }\n        else\n        {\n            //do something else\n        }	0
6344500	6344382	ASPX Page (vb.net) with dynamic controls created at runtime	Dim strValueOfDynamicControl As String = CType(YourPlaceHolder.FindControl("IdOfDynamicallyAddedControl"), TextBox).Text	0
28262367	28261901	How can i fill a value from one my domain model to my edit model?	var countryViewModel = context.Country.Select(c => new CountryEditModel\n    {\n        Code = c.Code,\n        Name = c.Name,\n        id = c.id\n    }).ToList();	0
7065892	7065132	How to convert this stored procedure to simple query	insert dbo.tbl_CommentableEntity (ItemId)\nselect wispId from (\n    insert dbo.tbl_Wisps (UserId,WispTypeId,CreatedOnDate,PrivacyTypeId,WispText)\n    output inserted.wispId\n    values (@m_UserId, @m_WispTypeId, @m_CreatedOnDate, @m_PrivacyTypeId, @m_WispText)\n) as ins	0
6717444	6717123	Checking multiple Radio buttons from different group boxes in c#	if (lbItems.SelectedIndex == -1)\n{\n    if (rdBtnMed.Checked)\n    {\n        using (StreamWriter File = new StreamWriter(filepath))\n        {\n            foreach (string item in lbItems.Items)\n            {\n                 saveAllText = medium + " " + item;\n                 outputFile.WriteLine(saveText);\n            }\n        }\n    }                        \n    else if (rdBtnMedium.Checked && rdBtnN.Checked)\n    {\n        using (StreamWriter File = new StreamWriter(filepath))\n        {\n            foreach (string item in lbItems.Items)\n            {\n                saveAllText = mediumNo + " " + item;\n                outputFile.WriteLine(saveText);\n            }\n        }\n    }\n}	0
7293231	7291374	Inserting DateTime into Acess Database via C# and Asp.net	string time = this.TextBox10.Text;\n        DateTime dt = new DateTime();\n        if (DateTime.TryParse("12/12/2011", out dt))\n        {\n            // your code here\n        }	0
6783001	6782888	Is there an attribute that I can use with ASP.NET MVC 3 to prevent model fields from being automatically included in my views?	[ScaffoldColumn(false)]	0
268829	268778	What's the MSIL to call a base class's event handler?	.method public hidebysig virtual instance void OnEventConsumed(object sender, class [mscorlib]System.EventArgs e) cil managed\n    {\n        .maxstack 8\n        L_0000: nop \n        L_0001: ldarg.0 \n        L_0002: ldarg.1 \n        L_0003: ldarg.2 \n        L_0004: call instance void SubclassSpike.BaseClass::OnEventConsumed(object, class [mscorlib]System.EventArgs)\n        L_0009: nop \n        L_000a: ret \n    }	0
7011796	7003894	Get subscribed podcasts using ITunes SDK	var podCastPlaylist = new iTunesAppClass()\n    .LibrarySource\n    .Playlists\n    .Cast<IITPlaylist>()\n    .First(pl => pl.Name == "Podcasts")	0
9192891	9192291	Reading & displaying value in Datetimepicker	// C#\n// Put the using statements at the beginning of the code module\nusing System.Threading;\nusing System.Globalization;\n// Put the following code before InitializeComponent()\n// Sets the culture to English (US)\nThread.CurrentThread.CurrentCulture = new CultureInfo("en-US");\n// Sets the UI culture to English (US)\nThread.CurrentThread.CurrentUICulture = new CultureInfo("en-US");	0
1248	11	How can relative time be calculated in C#?	const int SECOND = 1;\nconst int MINUTE = 60 * SECOND;\nconst int HOUR = 60 * MINUTE;\nconst int DAY = 24 * HOUR;\nconst int MONTH = 30 * DAY;\n\nvar ts = new TimeSpan(DateTime.UtcNow.Ticks - yourDate.Ticks);\ndouble delta = Math.Abs(ts.TotalSeconds);\n\nif (delta < 1 * MINUTE)\n{\n  return ts.Seconds == 1 ? "one second ago" : ts.Seconds + " seconds ago";\n}\nif (delta < 2 * MINUTE)\n{\n  return "a minute ago";\n}\nif (delta < 45 * MINUTE)\n{\n  return ts.Minutes + " minutes ago";\n}\nif (delta < 90 * MINUTE)\n{\n  return "an hour ago";\n}\nif (delta < 24 * HOUR)\n{\n  return ts.Hours + " hours ago";\n}\nif (delta < 48 * HOUR)\n{\n  return "yesterday";\n}\nif (delta < 30 * DAY)\n{\n  return ts.Days + " days ago";\n}\nif (delta < 12 * MONTH)\n{\n  int months = Convert.ToInt32(Math.Floor((double)ts.Days / 30));\n  return months <= 1 ? "one month ago" : months + " months ago";\n}\nelse\n{\n  int years = Convert.ToInt32(Math.Floor((double)ts.Days / 365));\n  return years <= 1 ? "one year ago" : years + " years ago";\n}	0
25873831	25867135	Implementing ladders in unity 2D	void Update()\n{\n    if((isgrounded  || !doublejump) && Input.GetKey(KeyCode.Space) )\n    {\n        anim.SetBool( "Ground",false);\n        rigidbody2D.AddForce(new Vector2(0,jumpforce));\n        if(!doublejump && !isgrounded)\n            doublejump = true;\n    }\n    if(Ladder && Input.GetAxis("Vertical")>0)\n    {\n\n        anim.SetBool("LadderUp",true);\n        transform.Translate (new Vector2(0,0.2f) * Time.deltaTime*maxspeed);\n        rigidbody2D.gravityScale =0;\n    //  rigidbody2D.velocity = new Vector2(rigidbody2D.velocity.x,Input.GetAxis("Vertical")*maxspeed);\n    }\n    if(!Ladder)\n    {\n        anim.SetBool("LadderUp",false);\n        rigidbody2D.gravityScale =1;\n    }\n\n}	0
11563334	11562860	AutoMapper Map single list on source object into two lists on destination object	internal class StartNewDemo\n{\n    public static void Main(string[] args)\n    {\n        Mapper.CreateMap<IList<Article>, ViewAllArticles>()\n            .ForMember(map => map.ActiveArticles, opt => opt.MapFrom(x => x.Where(y => y.IsActive)))\n            .ForMember(map => map.InactiveArticles, opt => opt.MapFrom(x => x.Where(y => !y.IsActive)));\n\n        var list = new List<Article>() { new Article { IsActive=true }, new Article { IsActive = false } };\n        var result = Mapper.Map<List<Article>, ViewAllArticles>( list );\n    }\n}	0
7065057	7045470	GridView Non-Visible Row Showing up in Empty Data Row	foreach (DataControlField field in _gridView.Columns)\n{\n    TableCell cell = new TableCell();\n    cell.Text = "&nbsp;";\n\n    if (field.ItemStyle.CssClass == "hideGridColumn")\n        cell.Visible = false;\n\n    row.Cells.Add(cell);\n}	0
9792679	9791583	How do I get the projects to build in the active Visual Studio configuration?	foreach (SolutionContext solutionContext in _applicationObject.Solution.SolutionBuild.ActiveConfiguration.SolutionContexts)\n {\n     if (solutionContext.ShouldBuild)\n      activeProjects.Add(solutionContext.ProjectName);\n  }	0
1688523	1688505	C#: Getting a button to display a preset form	protected void Button1_Click(object sender, EventArgs e)\n{\n    Form2 myForm = new Form2();\n    myForm.ShowDialog();\n}	0
2370440	2370388	SocketException: address incompatible with requested protocol	Socket serverSocket =\n    new Socket(ipAddress.AddressFamily, SocketType.Stream, ProtocolType.Tcp);\n                        ???	0
10839075	10838917	Load a Lazy Proxy Property	session.Lock(entity, LockMode.None);	0
16678252	16667135	How I can execute a Batch Command in C# directly?	processInfo = new ProcessStartInfo();\nprocessInfo.FileName  = "C:\\lmxendutil.exe";\nprocessInfo.Arguments = "-licstatxml -host serv005 -port 6200";\n//etc...	0
8729619	8728797	Naming a synchronization object in c# for use with contention analysis	public class NamedSyncRoot\n{\n    private object _syncRoot;\n\n    public string Name { get; private set; }\n\n    public NamedSyncRoot(string name)\n    {\n        Name = name;\n        _syncRoot = new object();\n    }\n\n    public void Lock()\n    {\n        Monitor.Enter(_syncRoot);\n    }\n\n    public void Unlock()\n    {\n        Monitor.Exit(_syncRoot);\n    }\n}\n\npublic class Foo\n{\n    private static NamedSyncRoot namedLock = new NamedSyncRoot("Foo");\n\n    public void Bar()\n    {\n        namedLock.Lock();\n        //...\n        namedLock.Unlock();\n    }\n}	0
5617512	5617498	How to use IList in Silverlight	IList list = new List<SomeType>()	0
12613327	12613313	Why Label controls aren't being hit in a foreach loop if the Label is in a GroupBox?	SetLabels (this);\n\npublic void SetLabels(Control ctrl)\n{\n  foreach (Control c in ctrl.Controls)\n     {\n         SetLabels(c);\n         if (c is Label)\n         {\n             if (c.Text == "12/31/1600")\n             {\n                 c.Text = "Not Found";\n             }\n         }\n     }\n}	0
27337104	27336772	how to make a textBox change its height when the number of lines change	SizeF size;\nprivate void textBox1_TextChanged(object sender, EventArgs e)\n{\n    using (Graphics G = textBox1.CreateGraphics())\n        size = G.MeasureString("Xy_", textBox1.Font, 999);\n\n    textBox1.Height = (int)(textBox1.Lines.Count() * size.Height + 5);\n    textBox2.Top = textBox1.Bottom - 1;\n}	0
31393939	31392909	WPF Custom Control Design Error	public HtmlViewer()\n {\n     InitializeComponent();\n\n     if (!DesignerProperties.GetIsInDesignMode(this)) // If NOT in design mode...do work.\n        populateCb();  \n }	0
28726268	28725976	Compare int input to position of array	class Month\n{\n    public string strMonth(int month)\n    {\n        var months = new Dictionary<int, string>\n        {\n            {1, "Jan"},\n            {2, "Feb"},\n            {3, "March"},\n            {4, "April"},\n            {5, "May"},\n            {6, "June"},\n            {7, "July"},\n            {8, "Aug"},\n            {9, "Sept"},\n            {10, "Oct"},\n            {11, "Nov"},\n            {12, "Dec"}\n        };\n\n        var monthString = "check fails";\n        if (months.ContainsKey(month))\n        {\n            monthString = months[month];\n        }\n        return monthString;\n    }\n}	0
12549142	12498959	C# - How to scan Interleaved 2 of 5 with more than 10 digits? Motorola EMDK 2.6 .NET on MC55 running Windows Mobile 6.1	SymbolReader.Decoders.I2OF5.Enabled = true;\nSymbolReader.Decoders.I2OF5.MinimumLength = 0;\nSymbolReader.Decoders.I2OF5.MaximumLength = 0;	0
31587511	31568578	GridObjectDataSource DataTable Sorting with parameters	DataView dv = new DataView(dtTable);\n    dv.Sort = columnName + " " + GetSortDirection(columnName);\n    GridView1.DataSource = dv;\n    dtTable = dv.ToTable();\n    GridView1.DataBind();	0
14909467	14908007	Calling a method on a field	Ldflda [proxyField]   // push the this pointer\nLdc_I4 123            // push the argument\nCallvirt [HandleCode] // call the method\nRet                   // return	0
1700315	1700240	How to sort ResourceSet in C#	DropDownList1.DataSource = Resources.FileTypes.ResourceManager\n    .GetResourceSet(System.Globalization.CultureInfo.CurrentCulture, true, true)\n    .OfType<DictionaryEntry>()\n    .OrderBy(i => i.Value);	0
13799713	13798879	Converting X509Certificate2 certificate into BouncyCastle X509Certificate	Org.BouncyCastle.Security.DotNetUtilities	0
21423692	21423511	Find files by not like mask	var clientFiles = Directory.GetFiles("C:\\", "Client*.xlsx");\nvar clientFilesWithDelete = clientFiles.Where(clientFile => clientFile.EndsWith("_delete.xlsx"));\nvar clientFilesWithoutDelete = clientFiles.Except(clientFilesWithDelete);	0
9202665	9202464	Comparing character statistics to produce predetermined third value	public abstract class Player : IComparable\n{\n\n    public abstract int Skill { get; }\n\n    public int CompareTo(object obj)\n    {\n        if (obj is Player)\n            return this.Skill.CompareTo(((Player) obj).Skill);\n        throw new ArgumentException();\n    }\n}\n\npublic class Warrior : Player\n{\n    public override int Skill\n    {\n        get { return 3; }\n    }\n}\n\npublic class Destroyer : Player\n{\n    public override int Skill\n    {\n        get { return 4; }\n    }\n}\n\npublic class Game\n{\n\n    public Player Attacker { get; set; }\n\n    public Player Opponent { get; set; }\n\n    public bool AttackerWins\n    {\n        get { return Attacker.CompareTo(Opponent) == 1; }\n    }\n\n    public bool OpponentWins\n    {\n        get { return Opponent.CompareTo(Attacker) == 1; }\n    }\n}	0
26845673	26771154	Passing Parameter to SSRS Business Object Class Data Source	public class ReportModel\n{\n\n public List<Top5Record> GetTop5(int branchId)\n{           \n   return (from s in context.Salesmen\n   where s.branchId == branchId\n   select new Top5Record\n  {\n     Name  = tr.Name,\n     Sales = tr.Sales\n  }).ToList();\n}\n}	0
13075411	13035427	RazorGenerator, Templates, and @Html	public ActionResult SomeAction() {\n  // call other section logic using HttpWebRequest or WebClient\n  // /controller/emailsection/{vars}/......\n  // Get the string out of the request add it to ViewData["xxx"]\n  // rinse and repeat for other sections\n\n}\n\npublic ActionResult EmailSection() {\n  //put section logic here\n\n  Response.ContentType = "text/html"; // "text/plain"\n  Response.Write("Some HttpWebResponse");\n  return null;\n}	0
11748096	11747915	Intercept button click on page load	protected void Page_Load(object sender, EventArgs e)\n {\n    if( IsPostBack ) \n    {\n        string senderControl = Request.Params["__EVENTTARGET"].ToString();\n        //senderControl will contain the name of the button/control responsible for PostBack\n    }\n  }	0
30988929	30988892	How to capture video stream using emgu cv	Capture videoCapture = new Capture();\nImage<Bgr, byte> currentFrame = videoCapture.QueryFrame();	0
5388359	5388335	Can File.Copy copy from a volume to a different volume?	File.Copy(@"C:\File.txt", @"E:\File.txt");	0
7090263	6957023	Multiline cell in Telerik grid (MVC3)	this.Categories = String.Join("<br>", entity.Categories.Select(o => o.Current.Name));	0
22228950	22172902	DataGridView GetCellDisplayRectangle too slow	private Rectangle GetCellRectangle(int columnIndex, int rowIndex)\n        {\n            Rectangle selRect = new Rectangle(0, 0, 0, 0);\n\n            selRect.X = RowHeadersWidth + 1;\n            for (int i = FirstDisplayedScrollingColumnIndex; i < columnIndex; i++)\n            {\n                selRect.X += Columns[i].Width;\n            }\n            selRect.X -= FirstDisplayedScrollingColumnHiddenWidth;\n\n            selRect.Y = ColumnHeadersHeight + 1;\n            for (int i = FirstDisplayedScrollingRowIndex; i < rowIndex; i++)\n            {\n                selRect.Y += Rows[i].Height;\n            }\n\n            selRect.Width = Rows[rowIndex].Cells[columnIndex].Size.Width;\n            selRect.Height = Rows[rowIndex].Cells[columnIndex].Size.Height;\n            return selRect;\n        }	0
11316275	11315967	How to Append attribute by using HtmlAgilitiPack?	HtmlAttribute attr = doc.CreateAttribute("foo", "baa");\nnodes[0].Attributes.Add(attr);	0
33274542	33264064	Chome opens for a split second then closes using selenium webdriver	using System;\nusing Microsoft.VisualStudio.TestTools.UnitTesting;\nusing OpenQA.Selenium.Firefox;\nusing OpenQA.Selenium;\nusing OpenQA.Selenium.Support.UI;\nusing OpenQA.Selenium.Chrome;\n\nnamespace UnitTestProject1\n{\n    [TestClass]\n    public class BrowserTest\n    {\n    string DRIVER_PATH = @"C:...misc...\Selenium Webdriver\chromedriver";\n\n        [TestMethod]\n        public void ChromeTest()\n        {\n            IWebDriver driver = new ChromeDriver(DRIVER_PATH);\n            driver.Navigate().GoToUrl("http://www.google.com");\n        }\n    }\n}	0
16174515	16174207	How to run VBS script from C# code	Process scriptProc = new Process();\nscriptProc.StartInfo.FileName = @"cscript"; \nscriptProc.StartInfo.Arguments ="//B //Nologo \\loc1\test\myfolder\test1.vbs";\nscriptProc.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;\nscriptProc.Start();\nscriptProc.WaitForExit();\nscriptProc.Close();	0
17808268	17808085	How can you scroll a ListBox to the bottom	listbox.ScrollIntoView(listbox.Items[listbox.Items.Count - 1]);	0
3662877	3662517	How to make [example] extension method more generic/functional/efficient?	yield return	0
24273959	24145054	Selenium WebDriver to test an ActiveX Control	private void UploadFile()\n    {\n        foreach (var element in driver.FindElements(By.TagName("button")))\n        {\n            string open = element.Text;\n            if (open == "Open")\n            {\n\n                element.SendKeys(@"C:\My\Relative\Path\");\n                element.Click();\n\n                string executable = @"C:\My\Relative\Path\fileUploadScript2.exe";\n                System.Diagnostics.Process.Start(executable);\n            }\n        }\n    }	0
6960108	6960040	XML Document Parsing C#	XmlNode n = doc.DocumentElement.SelectSingleNode("Offer/OfferListing/Price/FormattedPrice");	0
14880991	14880949	How can I use an enum as a datasource?	comboBoxType1.DataSource= Enum.GetNames(typeof(ValueType));	0
2920108	2920028	What is the faster way of trying to find a single character on a String?	static void Main(string[] args)\n    {\n        string myString = "qwertyuipasdfghjklzxcvbnm,.~";\n\n        var s = Stopwatch.StartNew();\n\n        for (int i = 0; i < 1000000; i++)\n        {\n            Boolean contains = myString.IndexOf("~", StringComparison.InvariantCultureIgnoreCase) != -1;\n        }\n\n        s.Stop();\n        Console.WriteLine(s.ElapsedMilliseconds);\n\n        var s2 = Stopwatch.StartNew();\n\n        for (int i = 0; i < 1000000; i++)\n        {\n            Boolean contains = myString.IndexOf('~') != -1;\n        }\n\n        s2.Stop();\n        Console.WriteLine(s2.ElapsedMilliseconds);\n        Console.ReadLine();\n\n    }	0
34200808	34198259	WinRT C++ (Win10), opencv HSV color space, image display, artifacts	//convert from SoftwareBitmap to Mat\nMat cvFrame = this->Convert(frame);\n\n//change color space\ncvtColor(cvFrame, cvFrame, COLOR_BGR2HSV);\n\n// split chanels\nvector<Mat> hsvChannels(3);\nsplit(cvFrame, hsvChannels);\n\n//create empty chanel\nMat empty;\nempty = Mat::zeros(cvFrame.rows, cvFrame.cols, CV_8UC1);\n\n// create hsv with empty alpha\nvector<Mat> channels;\nchannels.push_back(hsvChannels[0]); //h\nchannels.push_back(hsvChannels[1]); //s\nchannels.push_back(hsvChannels[2]); //v\nchannels.push_back(empty); //a\n\n//put back to Mat\nmerge(channels, cvFrame);\n\n// convert back to SoftwareBitmap \nreturn this->Convert(cvFrame);	0
15167967	15167705	How to bind to all elements in a BindingList?	foreach (MyClass myClass in myBindingList)\n{\n    myClass.PropertyChanged += MyClassOnPropertyChanged;\n}\n\nprivate void MyClassOnPropertyChanged(object sender, PropertyChangedEventArgs propertyChangedEventArgs)\n{\n    // ...\n}	0
34250243	34250176	How to set Textbox.Enabled from false to true on TextChange?	private void metaName_TextChanged(object sender,EventArgs e)\n{\n    TextBox ctrl = sender as TextBox;\n    if(ctrl != null)\n    {\n         bool enable = !string.IsNullOrEmpty(ctrl.Text);\n         TextBox secondOne = this.Controls\n                       .OfType<TextBox>()\n                       .FirstOrDefault(x => x.Name == "metaHTTPEquiv");\n        if(secondOne != null)\n           secondOne.Enabled = enable;\n    }\n}	0
8203463	8203316	Adding content to a TreeViewItem programmatically	new TreeViewItem {\n    Header = new StackPanel {\n        Children = {\n            new Button { ... }\n        }\n    }\n}	0
27824504	27804581	How do I make a programmatically-created System DSN show up as an ODBC Data Source?	dataSourcesKey.SetValue(information.DSNName, information.DriverName);	0
7574605	7571990	C# Serialization with control over Attribute and Element without System.Serialization?	System.Xml.Serialization.XmlSerializer	0
16790411	16790337	Converting strings to int in C#	string SubString = MyString.Substring(1);	0
12622964	12622550	Split items using ItemsControl	public IEnumerable<Well> SomeWells\n { get { return Wells.Take(5); }	0
13003740	13003721	Regex non-greedy match	string[^,]+itemB[^,]+,	0
9417245	9416095	dynamic does not contain a definition for a property from a project reference	dynamic o = new ExpandoObject();\n o.Title = "Ghostbusters";\n o.Rating = "PG";\n\n Console.WriteLine(m.PrintMovie(o));	0
21788967	21788856	How can I save data to a new file every time the program loops	var epochTime = (DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0)).TotalSeconds;\nSystem.IO.File.WriteAllText(string.Format(@"E:\path.{0}.txt", epochTime), data);	0
4823805	4823792	Retrieve Element of XDocument by name	XNamespace ns = "http://...";\nvar elem = doc.Element(ns + "TagName");	0
26473034	26472981	How to get an un-parameterized type from an parameterized generic type?	Type unparameterizedFoo = parameterizedFoo.GetGenericTypeDefinition();	0
9025125	9001916	Using Linq on a Client Object model result from sharepoint	var query = rolesAssignments.Select(x => x.RoleDefinitionBindings.Cast<RoleDefinition>().Select(y => y.RoleTypeKind == RoleType.Administrator)).Any();\nvar hasAdmin = context.LoadQuery(query);\ncontext.ExecuteQuery();	0
27536609	27535745	Why are one field of all objects in a list set to zero after using GROUP BY?	var positiveSupporters = supporters.GroupBy(x => x.name).Select(x => new Supporter { name = x.Key, supportAmount = x.Sum(y => y.supportAmount), GFP = dictionary[x.Key] }).ToList();	0
10026257	10026181	how to display the items in the combobox in any given manner?	eg. Your Table\n    Column1 Column2 .... DisplayOrder(int)\n    Principal                     1\n    FinanceManager                2\n    etc...	0
11268384	11268128	Error while trying to uncheck all the checkboxes in a C# app	foreach (object o in LogicalTreeHelper.GetChildren(FedApp.MainWindow))\n{\n  if (o is CheckBox)\n  {\n      ((CheckBox)o).Checked = false;\n  }\n}	0
22109125	22109008	Read/Write Xml elements and contents to listBox object	var logList = XDocument.Load(XMLConfigFile).Root.Elements(); //XmlConfigFile is the source of the Xml data\nvar contents= from element in logList\n              select (string)element.Attribute("LogRecord");\nforeach(var content in contents)\n{\n    listHoursLog.Items.Add(content);\n}	0
17936969	17936944	How do I repeatedly run code in a C# system tray application (Like on a timer)?	var timer = new Timer(tick_milliseconds);\n        timer.Elapsed += DoOnTimerClick;\n        timer.Enabled = true;	0
4935639	4935562	C# or VB.NET: How to programatically change encoding format to UTF-8 of all text files in a given directory?	DirectoryInfo DI = new DirectoryInfo("TextFiles_Path");\nFileInfo[] Files = DI.GetFiles("*.txt");\nforeach(FileInfo Fl in Files)\n{\n    StreamReader SR = Fl.OpenText(); //This opens a stream to the file **in UTF8 encoding**\n    StreamWriter SW = new StreamWriter(new FileStream(Fl.FullName + ".UTF8.txt", FileMode.OpenOrCreate), Encoding.UTF8);\n    SW.Write(SR.ReadToEnd());\n}	0
30389315	30389055	Best way to access image files to improve performance	Parallel.ForEach(files, file =>\n{\n    // do something with file\n    ...\n});	0
3143691	3143657	Truncate Two decimal places without rounding	value = Math.Truncate(100 * value) / 100;	0
13474092	13474018	C# - string to number	double num1 = Convert.ToDouble(str1,CultureInfo.InvariantCulture);\ndouble num2 = Convert.ToDouble(str2,CultureInfo.InvariantCulture);	0
6227412	6227373	How to open a file in memory?	MemoryStream inMemoryCopy = new MemoryStream();\nusing (FileStream fs = File.OpenRead(path))\n{\n  fs.CopyTo(inMemoryCopy);\n}\n// Now you can delete the file at 'path' and still have an in memory copy	0
10722641	10722467	C#: Loop to find minima of function	public void Test()\n{\n    var ys = new[] { 1, 2, 3, 4, 5, 4, 3, 2, 1, 2, 3, 4, 5, 4, 3, 4, 5, 4 };\n    var indices = GetMinIndices(ys);\n}\n\npublic List<int> GetMinIndices(int[] ys)\n{\n    var minIndices = new List<int>();\n    for (var index = 1; index < ys.Length; index++)\n    {\n        var currentY = ys[index];\n        var previousY = ys[index - 1];\n        if (index < ys.Length - 1)\n        {\n            var neytY = ys[index + 1];\n            if (previousY > currentY && neytY > currentY) // neighbors are greater\n                minIndices.Add(index); // add the index to the list\n        }\n        else // we're at the last index\n        {\n            if (previousY > currentY) // previous is greater\n                minIndices.Add(index);\n        }\n    }\n    return minIndices;\n}	0
31766920	31766758	Rectangle clockwise movement	if (y <= 0 && x < 750)\n{\n    x += 5;\n}\nelse if (x == 750 && y < 340)\n{\n    y += 5;\n}\nelse if (y >= 340 && x > 0)\n{\n    x-=5;\n}\nelse if (y > 0 && x <= 0)\n{\n    y-=5;\n}\nbreak;	0
4724453	4571425	What library do I need to reference for remote connection to RDC server from console app?	rdp.Server = txtServ.Text;\nrdp.UserName = txtUser.Text;\nIMsTscNonScriptable secured = (IMsTscNonScriptable)rdp.GetOcx();\nsecured.ClearTextPassword = txtPassword.Text;\nrdp.Connect();	0
9236382	9236362	fastest way to delete the content of a table	truncate table [name of table]	0
18673232	18673120	Want to find path of a file from the application folder?	string _myDirectoryPath = Environment.CurrentDirectory.ToString().Substring(0, Environment.CurrentDirectory.ToString().Length - 10).ToString() + @"\Myfile.txt";\n  StreamReader sr = new StreamReader(_myDirectoryPath);	0
25117922	25117786	How to add an interface realization to a base class ( List<t>)	public static class PoolingExtensions\n{\n    public static void PoolObject<T>(this List<T> source, T item)\n    {\n        //do something to pool object properly\n    }\n}	0
9528134	9514163	CPU High Usage with time for serial port	if (k == 14)\n{\n    try\n    {\n\n        curr_x = (pictureBox2.Width / 2) + (int)((engval[13] * (pictureBox2.Width)) / map_width);\n        curr_y = (pictureBox2.Height / 2) - (int)((engval[14] * (pictureBox2.Height)) / map_height);\n        PointF p1 = new Point(curr_x, curr_y);\n        if (_gPath != null && _gPath.PointCount > 0)\n            p1 = _gPath.PathPoints[_gPath.PathPoints.Length - 1];\n        PointF p2 = new Point(curr_x, curr_y);\n        _gPath.AddLine(p1, p2);\n        pictureBox2.Invalidate();\n    }\n    catch (Exception ex)\n    {\n        MessageBox.Show(ex.Message);\n    }\n}	0
1657267	1650763	Call unmanged Code from C# - returning a struct with arrays	public partial class Form1 : Form\n{\n    public SYSTEM_OUTPUT output;\n\n    [DllImport("testeshm.dll", EntryPoint="getStatus")]\n    public extern static int getStatus(out SYSTEM_OUTPUT output);\n\n    public Form1()\n    {\n        InitializeComponent();           \n    }\n\n    private void ReadSharedMem_Click(object sender, EventArgs e)\n    {\n        try\n        {\n            if(getStatus(out output) != 0)\n            {\n                //Do something about error.\n            }\n        }\n        catch (AccessViolationException ave)\n        {\n            label1.Text = ave.Message;\n        }\n    }\n}	0
1158310	1157894	Is there any easy way to create new xmls from a xml file using c#	System.Xml.XmlDocument daddyDoc = new System.Xml.XmlDocument();\ndaddyDoc.LoadXml("<?xml version='1.0' encoding='UTF-8'?><components><component name='a'/><component name='b'/><component name='c'/></components>");\nforeach (System.Xml.XmlNode sprogNode in daddyDoc.GetElementsByTagName("component"))\n{\n    System.Xml.XmlDocument sprogDoc = new System.Xml.XmlDocument();\n    sprogDoc.CreateXmlDeclaration("1.0", "UTF-8", null);\n    sprogDoc.AppendChild(sprogDoc.CreateElement("component"));\n    sprogDoc.Save(string.Format("C:\\{0}.xml", sprogNode.Attributes["name"].Value));\n}	0
34122202	34122129	Edit fields of outgoing HTTP request headers in C#	oSession.oRequest["Cookie"] = (oSession.oRequest["Cookie"] + ";SessionID=YOUR_SESSION_ID");	0
26820038	26819550	LINQ to get the Descendant of type "a" from HTMLNodesCollection	var imgElems = htmlDoc.DocumentNode\n               .SelectNodes("//div[@class='entry-thumbnail hover-thumb']/a/img");	0
10710112	10709983	Moving a file into a subfolder in C# trouble?	// TODO: check for listBox1.Text to be blank or non-file\n\n        if (comboBox1.Text == "Select File Destination")\n        {\n            MessageBox.Show("Please Select A Destination Folder", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);\n        }\n\n        string sourceFile = Path.Combine(Environment.SpecialFolder.UserProfile, "Downloads", listBox1.Text;\n        string destinationFile = Path.Combine(Environment.SpecialFolder.MyDocuments, "iracing", "setups", comboBox1.Text;\n        File.Move(sourceFile, destinationFile);\n    }\n    catch { }	0
3169316	3125303	How can add TablexId and TableyId to a relationships table ( shows up as navigation property on Entity Framework )?	db.Items.Where(id => id.Id == newItem.Id).First().Tags.Add(newTag);	0
6591696	6591102	Need some C# Regular Expression Help	string returnString = someRandomText.Substring(0, someRandomText.IndexOf("</ol>") - 1);	0
26478877	26478836	Parse a value = "pair" string into Dictionary	dictionary.Add(match.Groups["Keyword"].Value, match.Groups["Value"].Value);	0
6326017	6325983	TreeNodeCollection Control Property C#	MenuItems.AddRange(yourList);	0
16608493	16608447	Finding all files in a folder using enumeration	IEnumerable<string> Search(string sDir)\n{\n    foreach (var file in Directory.GetFiles(sDir))\n    {\n        yield return file;                \n    }\n\n    foreach (var directory in Directory.GetDirectories(sDir))\n    {\n        foreach(var file in Search(directory))\n            yield return file;\n    }\n}	0
10546454	10545940	Populate list with selecteditems from group of combo boxes	Item ConvertToItem(Object obj)\n{\n  ....\n}\n\nforeach (var Cbox in CBoxContainer.Children.OfType<ComboBox>())\n{\n  if (Cbox.SelectedItem != null)\n  {\n   items.Add(ConvertToItem(CBox.SelectedItem));\n  }\n}	0
30269827	30267537	Unity - need to return value only after coroutine finishes	public int success_fail\n\nIEnumerator POST(string username, string passw)\n{\n    WWWForm form = new WWWForm();\n    form.AddField("usr", username);\n    form.AddField("pass", passw);\n\n    WWW www = new WWW(url, form);\n\n    yield return StartCoroutine(WaitForRequest(www));\n}\n\nprivate IEnumerator WaitForRequest(WWW www)\n{\n    yield return www;\n    if (www.error == null)\n    {\n        if(www.text.Contains("user exists"))\n            {\n                success_fail = 2;\n            }\n            else\n            {\n                success_fail=1;\n            }\n    } else {\n        success_fail=0;\n    }    \n}	0
20124777	20124736	How to use String variable to obtain specific list of items in collections by using Extention Select Method	string property="Region"; \nvar prop = typeof(Processing).GetProperty(property);\nvar result=process.Select(a=>prop.GetValue(a, null));	0
6838887	6838870	Get distinct value from comma seperated array using LINQ	lists.SelectMany(l => l.Split(',')).Distinct().ToList();	0
2795067	2794952	Query a List of List of Items in LINQ c#	var query = from list in lists\n            from value in list\n            where lists.Where(l => l.Contains(value)).Any()\n            select new { List = list, Value = value };	0
3657053	3656918	variable that can't be modified	public class SetValueOnce<T>\n{\n    public bool _set;\n    private T _value;\n\n    public SetValueOnce()\n    { \n      _value = default(T);\n      _set = false;\n    }\n\n    public SetValueOnce(T value)\n    { \n      _value = value;\n      _set = true;\n    }\n\n    public T Value\n    {\n      get\n      {\n          if(!_set)\n             throw new Exception("Value has not been set yet!");\n          return _value;\n      {\n      set\n      {\n         if(_set)\n             throw new Exception("Value already set!");\n         _value = value;\n         _set = true;\n      }\n   }\n}	0
1367398	1367256	Set RTF text into WPF RichTextBox control	rtfBox.Selection.Load(myStream, DataFormats.Rtf);	0
23563459	23563250	Compare Flag Enums by Description	var result =\n   Enum.GetValues(typeof(UserRoles))\n       .Cast<UserRoles>()\n       .Where(r => (r & testRoles) == r)\n       .Select(r => typeof(UserRoles).GetField(r.ToString())\n                                     .GetCustomAttribute<DescriptionAttribute>()\n                                     .Description)\n       .Intersect(currentUserRoles)\n       .Any();	0
5369583	4567239	Deleting a child entity in a many-to-one relationship using POCO in EF4 CTP5	this.ContextOptions.ProxyCreationEnabled = true;	0
29773296	29772562	Reading a customised heating schedule file in C#	var stream = new FileStream("myfile.txt", FileMode.Open);\nvar streamReader = new StreamReader(stream);\nwhile (!streamReader.EndOfStream)\n{\n   // read in the current line of the file\n   var line = streamReader.ReadLine();\n   if (string.IsNullOrWhiteSpace(line))\n        continue;\n\n   // split the line by the hyphen, trim the whitespace\n   var split = line.Split(new[] { '-' }).Select(x => x.Trim()).ToArray();\n\n   // parse the time, use the current date for the day\n   var time = DateTime.Parse(split[0]);\n\n   // save your action for later\n   var action = split[1];\n\n   // compare the time in the file with the current time, use a 1 second tolerance\n   if (DateTime.Now.Subtract(time).Duration() < TimeSpan.FromSeconds(1))\n   {\n        // if the current time is within 1 second of the time in the file\n        switch(action)\n        {\n             case "SP":\n                break;\n             default:\n                break;\n        }\n   }\n}	0
762870	762861	how to check if a datareader is null or empty	if (myReader["Additional"] != DBNull.Value)\n{\n    ltlAdditional.Text = "contains data";\n}\nelse\n{\n     ltlAdditional.Text = "is null";\n}	0
6364952	6364245	WinForm - Don't allow radio button to be tabbed into	public partial class Form1 : Form\n{        \n    public Form1()\n    {\n        InitializeComponent();\n        radioButton1.TabStop = false;\n        radioButton2.TabStop = false;\n    }\n\n    private void radioButton1_CheckedChanged(object sender, EventArgs e)\n    {\n        radioButton1.TabStop = false;\n        radioButton2.TabStop = false;\n    }\n\n    private void radioButton2_CheckedChanged(object sender, EventArgs e)\n    {\n        radioButton1.TabStop = false;\n        radioButton2.TabStop = false;\n    }\n\n}	0
6642421	6642005	How can I set page size using WkHtmlToXSharp?	........your code.....\n Document pdfDoc = new Document(PageSize.A3,8f, 8f, 8f, 8f);\n PdfWriter.GetInstance(pdfDoc, Response.OutputStream);\n ...................................	0
14417839	14417720	How to get the public path of an Amazon Object?	string path = String.Format("http://{0}.s3.amazonaws.com/", originBucketName);	0
12439549	12439518	How I create application file like .apk for Windows Phone?	Documents\Visual Studio 2010\Projects\AppName\Bin\Release\	0
13389073	13388922	c# Take a screenshot of specific area	g.CopyFromScreen(center.X - 36, center.Y - 30, 0, 0, new Size(36 * 2, 30 * 2));	0
27666933	27666848	Specific regex in C#	[^>]+>\s+([^\s]*)	0
11223133	11222557	Determine size of a file by reading its lines	sr.ReadLine	0
21828488	21828252	Get struct within a struct using reflection	_someClass.PreLoadedAssembly\n          .GetType("Some.NameSpace.ToAccess.HowTo")\n          .GetNestedType("AccessMe");	0
33668155	33635888	After Closing WebBrowser control, form opens last URL in default system browser	(form1 frm = new form1()) {------------------ }	0
31203177	31202258	How write an AddressBar for Awesomium WebBrowser control	/// <summary>\n/// Occurs when the target URL has changed. This\n/// is usually the result of hovering over a link on a page.\n/// </summary>\npublic event UrlEventHandler TargetURLChanged;	0
9229575	9227803	How can I prevent a ListView option from changing?	int lastIndex = -1;\n\nif (q)\n{\n    lastIndex = (ListView)Sender.SelectedIndex;\n} \nelse \n{\n    // Stop change from happening\n    (ListView)Sender.SelectedIndex = lastIndex;\n}	0
14877204	14877012	Changing cell colours of a TableLayoutPanel by variables during runtime?	void tableLayoutPanel_CellPaint(object sender, TableLayoutCellPaintEventArgs e)\n{\n    Graphics g = e.Graphics;\n    Rectangle r = e.CellBounds;\n    g.FillRectangle(GetBrushFor(e.Row, e.Column), r);\n}\n\nprivate Brush GetBrushFor(int row, int column)\n{\n    if (row == 2 && column == 1)\n        return Brushes.Red;\n\n    // other logic\n    // ...\n    // return default Brush\n}	0
8024154	8023571	What's wrong with this QuickSort program?	public int Partition(IList<int> list, int l, int r){\n    int pivot = list[l];\n    int i = l+1;\n    int j = r;\n    while(true){\n        //{i,j| l< i,j <= r}\n        while(i<=r && list[i] <  pivot)++i;\n        while(j>l  && list[j] >= pivot)--j;\n        if(i<j)\n            Swap(list, i, j);\n        else\n            break;\n    }\n    Swap(list, l, j);\n    return j;\n}	0
3405426	3404637	EF save to Context but not to Datasource	TestEntity testEntity = new TestEntity() { Name = "Hello World" };\ncontext.TestEntities.AddObject(testEntity);\n\nvar entitiesInOSM = context.ObjectStateManager.\n        GetObjectStateEntries(EntityState.Added | EntityState.Deleted | EntityState.Modified | EntityState.Unchanged).\n        Where(ent => ent.Entity is TestEntity).\n        Select(ent => ent.Entity as TestEntity);\n\nAssert.AreEqual(1, entitiesInOSM.Count(), "Entity not in context!");	0
8157055	8157025	Constraining a generic type argument to numeric types	where T : struct, IConvertible, IComparable<T>	0
4964618	4964572	C#: A two step textbox calculation is only yielding the correct result when clicking my calculate button twice	tb2 = 30.00 - (10 * Math.Log10(origin));\nvar tb3 = tb2 - (10 * Math.Log10(channels));\ntextBox2.Text = tb2.ToString("n2");\ntextBox3.Text = tb3.ToString("n2");	0
24087031	24086625	Deserialized Xml Object Loop Throws NullReferenceException	object[] rowItems = null;\nrowItems[0] = jobs.Items[i].Date;	0
8077534	8077486	Image margin behavior	proba.VerticalAlignment = VerticalAlignment.Top;\nproba.HorizontalAlignment = HorizontalAlignment.Left;	0
29513009	29512889	how to get the month name	CultureInfo.CurrentCulture.DateTimeFormat.GetMonthName(monthNumber);	0
12792190	12792175	converting byte to image & image to byte using c#	public Image byteArrayToImage(byte[] byteArrayIn)\n{\n     Image returnImage = null;\n     using (MemoryStream ms = new MemoryStream(byteArrayIn))\n     {\n         returnImage = Image.FromStream(ms);\n     }\n     return returnImage;\n}	0
16599345	16599281	Is it bad practice for a class to be aware of its location in an array?	var objIndexPair = collection.\n    Select((v, i) => new {\n        Index = i\n    ,   Object = v\n    }).ToList();	0
12131651	12131610	Regex expression to get first word after specified word	(?<=NR\.)\s?\w+	0
1439985	1439954	Max DateTime in a list	List<DateTime> dates = new List<DateTime> { DateTime.Now, DateTime.MinValue, DateTime.MaxValue };\n\nDateTime max = DateTime.MinValue; // Start with the lowest value possible...\nforeach(DateTime date in dates)\n{\n    if (DateTime.Compare(date, max) == 1)\n        max = date;\n}\n\n// max is maximum time in list, or DateTime.MinValue if dates.Count == 0;	0
216747	215854	Prevent DTD download when parsing XML	XmlReaderSettings settings = new XmlReaderSettings();\n        settings.XmlResolver = null;\n        settings.DtdProcessing = DtdProcessing.Parse;\n        XmlDocument doc = new XmlDocument();\n        using (StringReader sr = new StringReader(xml))\n            using (XmlReader reader = XmlReader.Create(sr, settings))\n            {\n                doc.Load(reader);\n            }	0
18231894	18231844	IO.directorynotfound - Dynamical SqlConnection string	private static string FunctionToDynamicallyCreateConnectionstring()\n   {\n\n        string path = Properties.Settings.Default.swPath;\n\n        if (path != null)\n        {\n            StreamReader sr = new StreamReader(File.Open(path, FileMode.Open));\n\n            SqlConnectionStringBuilder cb = new SqlConnectionStringBuilder();\n\n\n            cb.DataSource = DecodeFrom64(sr.ReadLine());\n            cb.InitialCatalog = DecodeFrom64(sr.ReadLine());\n            cb.UserID = DecodeFrom64(sr.ReadLine());\n            cb.Password = DecodeFrom64(sr.ReadLine());\n            return cb.ToString(); \n       }\n       else\n            return string.Empty\n   }	0
29772845	29771686	Application crash when close com port in a background worker - C# application?	string data = _serialPort.ReadLine();	0
14613508	14611690	How to get all comments in a given group?	var fb = new FacebookClient(facebookOAuthResult.AccessToken);\n\n                var query = string.Format("select actor_id, attachment, message from stream where source_id = {0}", "groupId");\n\n                dynamic parameters = new ExpandoObject();\n                parameters.q = query;\n\n                dynamic result = fb.Get("/fql", parameters);	0
8078357	8078131	How to add an element as the n child to an element in LINQ	foreach (var element in elementsToChange)\n{\n  XElement lastChild = null;\n  foreach(var childName in Enumerable.Range(1, 3).Select(x => "Child" + x))\n  {\n    var child = element.Element(childName);\n    if(child == null)\n    {\n      child = new XElement(childName);\n      if(lastChild == null)\n        element.AddFirst(child);\n      else\n      {\n        lastChild.AddAfterSelf(child);\n      }\n    }\n    lastChild = child;\n  }\n}	0
33915141	33914498	Changing picturebox backcolor in Visual Studio (c#) using a variable in place of a name	Control []controls=this.Controls.Find("pictureBox" + resultValue.ToString(), true);\n        if (controls != null && controls.Length > 0)\n        {\n            foreach (Control control in controls)\n            {\n                if (control.GetType() == typeof(PictureBox))\n                {\n                    PictureBox pictureBox = control as PictureBox;\n                    pictureBox.BackColor = Color.FromArgb(r, g, b);\n                }\n            }\n        }	0
6817715	6817664	C# Adding data into, or removing data from, a string array	// Filters out the second item (zero-based index 1)\nsourceFile = sourceFile.Where((s, i) => i != 1).ToArray();	0
16633292	16633278	Rewrite foreach statement to linq	var count = settings.FavouritesSetting.Count(i => i.FavouriteType != Constants.FavouriteType.Folder);\n\nreturn count.ToString();	0
32652749	32652630	Assign different object to a one object in C#	public interface ILayer\n{\n    void pop_in();\n}\n\n// one of your classes\npublic class SomeLayer : ILayer\n{\n    // ...\n}\n\n//object for store active layer\nILayer active_layer = new SomeLayer();\n\n// rest of the code works	0
21679029	21678670	Display user information after logging in	protected void Page_Load(object sender, EventArgs e)\n    {\n        //string DOB;\n        if (Session["UserAuthentication"] != null)\n        {\n            Student student = (Student)Session["UserAuthentication"];\n            lbStudentNum.Text= student.StudentNumber ;\n            City.Text= student.City;\n            Postcode.Text= student.Postcode ; \n        }\n        else\n        {\n            Response.Redirect("Index.aspx");\n        }	0
4021232	4021199	How to format a string displayed in a MessageBox in C#?	string strMsg = String.Format("Machine\t: {0}\nUser\t: {1}", "TestMachine", "UserName");	0
30376842	30313510	View state data being lost on a back click in MVC	[OutputCache(Duration=0, VaryByParam="none", Location=OutputCacheLocation.Client, NoStore=true)]\npublic ActionResult Cart()\n{\n//your code goes here.\n}	0
19731792	19731738	How to get response type of the request without loading the full content	var request = (HttpWebRequest)WebRequest.Create(url);\n    request.Method = "HEAD";\n    using (var response = (HttpWebResponse)request.GetResponse())\n    {\n         //...	0
7532373	7530673	Accessing gridview from a non GridView event	for(int rowIndex =0; rowIndex<gv.rows.count; rowIndex++)\n{\n  Myddl = gv.rows[rowIndex].FindControl("Quantity") as DropDownList;\n\n}	0
26466100	26465955	Pass arrays of different types of enum values to a function	WorkWithEnums(first.Cast<Enum>().ToArray())	0
21846178	21794706	How to pass an array of <List> to a stored procedure	DateString = '01/02/2012|05/02/2013|01/02/2014'\n    TypeString = 'Medical|Theft|Test'\n    DescString = "Its a medical|..."	0
8098016	8096915	Reading from and conditionally writing to complex XML files with LINQ	string orderCode = "FOO";\n    string paramCode = "BAR";\n\n    XDocument doc = XDocument.Load("file.xml");\n\n    XNamespace abc = "http://www.mycompany.com/xyz/abc";\n\n    XElement value = \n        doc\n        .Descendants(abc + "order")\n        .First(o => o.Element(abc + "orderCode").Value == orderCode)\n        .Descendants(abc + "orderParameter")\n        .First(p => p.Element(abc + "parameterCode").Value == paramCode)\n        .Element(abc + "billedValue")\n        .Element(abc + "value");\n\n    value.SetElementValue(abc + "numericalValue", 20);\n    value.SetElementValue(abc + "stringValue", "twenty");\n\n    doc.Save(Console.Out); // do doc.Save("file.xml") to overwrite	0
2047610	2047596	How to check if two string are of the same length?	if(passnew.Length == passcnfrm.Length && \n   passnew.Length > 6 && passnew.Length < 15)\n{\n    // do stuff\n}	0
33505084	33408654	Custom MD5 / CRC check for a re downloaded ftp always saying the file is different from the original	bytesGelesen = leseStream.Read(leseBuffer, 0, leseBuffer.Length);	0
24210907	24210748	Getting all text nodes in xml using linq or xpath	XDocument doc = XDocument.Load("file.xml");\nIEnumerable<XText> textNodes = doc.DescendantNodes().OfType<XText>();	0
11618440	11618360	How can I efficiently link two datasets in C#?	var reviewGrids = (from r in review\n                   join t in topic on r.RowKey.Substring(0, 6) equals t.RowKey\n                   select new ReviewGrid\n                   {\n                     r.PartitionKey,  \n                     r.RoWKey,\n                     t.Topic,\n                   }).ToList();	0
27097032	27096668	Enhance my RegEx for proofreading	(?:"|'(?!s\b|\s)|?)[^"'??]+(?:"|'(?!s\b)|?)	0
15903558	15903173	In C#- Retrieving data from selected item in combo box and fill into data grid view	private void frmMain_Load(object sender, EventArgs e)\n{\n    a = new MyLibrary("localhost", "root", "", "cashieringdb");\n    fillCombo();   //fill combo before calling loadDataGridView_Main()\n    loadDataGridView_Main();\n    dataLog();    \n}	0
17419279	17419143	Read the xml and store it in a string	XmlDocument xml = new XmlDocument();\nxml.LoadXml(@"\n<DESCIONTREE>\n  <Motion X='296' Y='88' Angle='-90' Direction='up' file='2.jpg' />\n  <Motion X='384' Y='94' Angle='90' Direction='down' file='2.jpg' />\n</DESCIONTREE>\n");\n\nXmlNodeList xnList = xml.SelectNodes("/DESCIONTREE/Motion");\n\n\nforeach (XmlNode xn in xnList)\n{\n    Console.WriteLine("{0} {1} {2} {3} {4}", xn.Attributes["X"].Value, xn.Attributes["Y"].Value, xn.Attributes["Angle"].Value, xn.Attributes["Direction"].Value, xn.Attributes["file"].Value);\n}	0
10225332	10225052	Listbox - add two identical items - WPF	private void Window_Loaded ( object sender, RoutedEventArgs e )\n{\n   listBox_MyListBox.Items.Add ( "demo" );\n   listBox_MyListBox.Items.Add ( "demo" );            \n}	0
29393021	29391464	Telling RestSharp *not* to add a specific HTTP header	webRequest.AutomaticDecompression = \n    DecompressionMethods.Deflate | DecompressionMethods.GZip | DecompressionMethods.None;	0
25310778	25307331	How to change the Web Reference URL through TextBox	ssrsWebService.ReportingService2010 rs = new ssrsWebService.ReportingService2010();\nrs.Url = ReportServerURLTxt.Text + "/ReportService2010.asmx";	0
9065923	9065778	How to detect call to methods from another form?	class Form1: Form\n{\n    public void Button1_Click(object sender, EventArgs e)\n    {\n        var form2 = new Form2();\n        form2.SomeMethodCalled += Form2_SomeMethodCalled;\n    }\n\n    public void Form2_SomeMethodCalled(object sender, EventArgs e)\n    {\n        // method in form2 called\n    }\n}\n\n\nclass Form2 : Form\n{\n    public event EventHandler SomeMethodCalled;\n\n    public void SomeMethod()\n    {\n        OnSomeMethodCalled();\n        // .....\n    }\n\n    private void OnSomeMethodCalled()\n    {\n        var s = SomeMethodCalled;\n        if(s != null)\n        {\n            s(this, EventArgs.Empty);\n        }\n    }\n}	0
7311862	7311822	How to return numberOfMessages per user using Linq	var result = dbContext.Users\n    .Select(u => new \n                   {\n                       UserID = u.Id, \n                       NumberOfMessages = u.Messages.Count()\n                   })\n    .ToList();	0
26477003	13662497	Execute a pl/sql function with OracleCommand	using Oracle.DataAccess.Client;\nusing Oracle.DataAccess.Types;\n\nint RETURN_VALUE_BUFFER_SIZE = 32767; \nOracleCommand cmd = new OracleCommand();\ntry {\n    cmd.Connection = conn;\n    cmd.CommandText = "KRIST.f_Login";\n    cmd.CommandType = CommandType.StoredProcedure;\n\n    cmd.Parameters.Add("returnVal", OracleDbType.Varchar2, RETURN_VALUE_BUFFER_SIZE);  \n    cmd.Parameters["returnVal"].Direction = ParameterDirection.ReturnValue;\n\n    cmd.Parameters.Add("userName", OracleDbType.Varchar2);\n    cmd.Parameters["userName"].Value = "kristian";\n\n    cmd.Parameters.Add("password", OracleDbType.Varchar2);\n    cmd.Parameters["password"].Value = "kristian";\n\n    cmd.ExecuteNonQuery();\n    string bval = cmd.Parameters["returnVal"].Value.ToString();\n    return bval;\n} catch (Exception e) {\n    // deal with exception \n} finally {\n    command.Dispose();\n    connection.Close();\n    connection.Dispose();\n}	0
20757659	20757397	How to insert values in one column? c#	foreach (string value in data1)\n{\n\n    var match = Regex.Match(value, @"(?<Number>\d+)(?<Text>.*)");\n    var number = match.Groups["Number"].Value;\n    var text = match.Groups["Text"].Value;\n    string result2 = string.Format("{0}", text);\n    data.Rows.Add(result2);\n}\n\ndataGridView1.DataSource = data;	0
12497454	12497401	How to pass a parameter to class constraint	using (T entitiesContext = (T)Activator.CreateInstance(typeof(T), new[]{conn}))	0
2692352	2692326	Linq to XML query date intervals	DateTime.Parse(sale.Element("Date").Value) >= date.Date.AddDays(-7)	0
26998465	26968594	pbkdf2_sha256 C# implementation	var salt = "FbSnXHPo12gb";\nvar password = "geheim";\nvar interactions = 12000;\n\n\nusing (var hmac = new HMACSHA256())\n{\n    var df = new Pbkdf2(hmac, password, salt, interactions);\n    Console.WriteLine(Convert.ToBase64String(df.GetBytes(32)));\n}\n\n//hash I should get: \n//pbkdf2_sha256$12000$FbSnXHPo12gb$LEpQrzPJXMI0m3tQuIE5mknqCv1GWgT5X2rWyLHN0Xk=\n\n//hash I get:\n//LEpQrzPJXMI0m3tQuIE5mknqCv1GWgT5X2rWyLHN0Xk=	0
9787443	9787350	Change text property of all items in form	foreach (Control objCtrl in yourFormName.Controls) {\n    if (objCtrl  is Label)\n    {\n        // Assign Some Text \n    }\n\n\n    if (objCtrl  is Button)\n    {\n        // Assign some text\n    }	0
25064500	25064468	IEnumerable C# object to JSON object of arrays with name	public object GetAllProduct()\n{\n    var products= _productRepository.GetAllProduct();\n    return new { data = products };\n}	0
15991395	15991361	Redirecting text data from file to stdin c# windows	program.exe < input.txt > output.txt	0
9702738	9702476	How can I make a date time picker always contain the last day of the month while showing month and year only?	DateTime lastDayOfMonth = new DateTime(\n    selectedDate.Year, \n    selectedDate.Month, \n    DateTime.DaysInMonth(selectedDate.Year, selectedDate.Month));	0
3368608	3368581	See any problems with this C# implementation of a stack?	public class Stack<T>\n{\n    private const int _defaultSize = 4;\n    private const int _growthMultiplier = 2;\n\n    private T[] _elements;\n    private int _index;\n    private int _limit;\n\n\n    public Stack()\n    {\n        _elements = new T[_defaultSize];\n        _index = -1;\n        _limit = _elements.Length - 1;\n    }\n\n\n    public void Push(T item)\n    {\n        if (_index == _limit)\n        {\n            var temp = _elements;\n            _elements = new T[_elements.Length * _growthMultiplier];\n            _limit = _elements.Length - 1;\n            Array.Copy(temp, _elements, temp.Length);\n        }\n        _elements[++_index] = item;\n    }\n\n    public T Pop()\n    {\n        if (_index < 0)\n            throw new InvalidOperationException();\n\n        var item = _elements[_index];\n        _elements[_index--] = default(T);\n        return item;\n    }\n\n    public void Clear()\n    {\n        _index = -1;\n        Array.Clear(_elements, 0, _elements.Length);\n    }\n}	0
13170537	13169779	generic error in gdi+ decoding a valid jpeg	SOS for 1st component, compressed data, SOS for 2nd component, compressed data,...	0
215538	215471	Locating installer paths in c#	string path = Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles);	0
2917031	2916815	Get data from XDocument	PubDate = DateTime.ParseExact(xml.Root.Elements("pubDates")\n.Elements("date")\n.Where(n => n.Attribute("format").Value == "standard")\n.FirstOrDefault()\n.Value\n, "yyyy-mm-dd", CultureInfo.InvariantCulture);	0
32254028	32253821	Serialize to JSON with lower case property values	Json.Net	0
4492100	4491914	Clean approach to finding a folder's parent	private void SetProjectFolder(string sessionid)\n    {\n        //This will simulate the contains statement\n        string searchPattern = string.Format("*{0}*", sessionid);\n        string[] supportDirs = Directory.GetDirectories(ApplicationContainer.SupportDirectory, searchPattern);\n\n        foreach (string filteredFolder in supportDirs)\n        {\n            _productName = Directory.GetParent(filteredFolder).Name;\n            break;\n        }\n    }	0
6748846	6748676	Task Parallel with .net framework 4	delegate void SetProgressBarCallback();\n\n        private void SetProgressBar()\n        {\n            // InvokeRequired required compares the thread ID of the\n            // calling thread to the thread ID of the creating thread.\n            // If these threads are different, it returns true.\n            if (this.progressBar1.InvokeRequired)\n            {   \n                SetProgressBarCallback d = new SettProgressBarCallback(SetProgressBar);\n                this.Invoke(d);         \n            }\n            else\n            {\n                for(int i=0; i<99; i++)\n                {\n                     Thread.Sleep(1);\n                     progressBar1.Value = i;\n                 }\n            }\n        }	0
26967155	26967110	How can I make a Property Read-only Declared in Interface in C#	public interface IRepository \n{\n    bool IsTxOpened { get; }\n    //.....\n}	0
23408692	23408644	How can I get the value with most occurrences in a collection?	var mostCommon = MyCollection\n  .GroupBy(r => r)\n  .Select(grp => new { Value = grp.Key, Count = grp.Count() })\n  .OrderByDescending(x => x.Count)\n  .First()\n\nConsole.WriteLine(\n  "Value {0} is most common with {1} occurrences", \n  mostCommon.Value, mostCommon.Count);	0
11260865	11260775	How Change Telerik RadGrid Column's Property Server-Side 	grdDemo.DataSource = ds\ngrdDemo.DataBind()\n\ngrdDemo.MasterTableView.GetColumn("TemplateColumn_Commands").Display = False	0
1221155	1221135	returning a value to a c# program through python script	process.ExitCode	0
18877855	18877591	How to read HTTP request headers in a WCF web service?	IncomingWebRequestContext request = WebOperationContext.Current.IncomingRequest;\nWebHeaderCollection headers = request.Headers;\n\nConsole.WriteLine("-------------------------------------------------------");\nConsole.WriteLine(request.Method + " " + request.UriTemplateMatch.RequestUri.AbsolutePath);\nforeach (string headerName in headers.AllKeys)\n{\n  Console.WriteLine(headerName + ": " + headers[headerName]);\n}\nConsole.WriteLine("-------------------------------------------------------");	0
4194931	4194839	How to Parse XML in C#	using(var client = new ServiceReference1.ThirdPartyServiceClient())\n{\n    client.SendSomething("123", "hello");\n    string output = client.GetSomething();\n    Console.WriteLine(output);\n}	0
18647252	18636424	bypassing Entity Framework to import / update a large amount of data	truncate table TheFile_Staging\n    BULK INSERT TheFile_Staging FROM'C:\Data\TheFile.txt'\n WITH (fieldterminator=',', rowTerminator='\r\n',FirstRow=2)\n  //FirstRow=2 means skip Row#1 - use this when 1st row is a header.\n\nMERGE TheFile_Table as target\nUSING (SELECT ID,Value1,Value2 from TheFile_Staging) as source\non target.ID = source.ID\nWHEN MATCHED THEN\n  UPDATE SET target.Value1=source.Value1, target.Value2=source.target2\nWHEN NOT MATCHED THEN \n  INSERT (id,Value1,Value2) VALUES (source.Id,source.Value1,source.Value2);	0
19470860	19470776	wpf DataGrid automatically edit cell with CustomControl at DataTemplate	private void DataGrid_GotFocus(object sender, RoutedEventArgs e)\n{\n    // Lookup for the source to be DataGridCell\n    if (e.OriginalSource.GetType() == typeof(DataGridCell))\n    {\n        // Starts the Edit on the row;\n        DataGrid grd = (DataGrid)sender;\n        grd.BeginEdit(e);\n    }\n}	0
28334074	28292601	Serilog - multiple log files	.ByIncludingOnly(evt => evt.Level == LogEventLevel.Warning)	0
18595139	18594571	EventAggregator postpone a message for later use	public class OriginalMessage : CompositePresentationEvent<OriginalArgs> { }\npublic class MyDelayedMessage : CompositePresentationEvent<MyEventArgs> { }\n\npublic class DelayedMessage {\n    EventAggregator _bus;\n    OriginalMessage _msg;\n    DispatcherTimer _timer;\n    OriginalArgs _args;\n\n    public DelayedMessage(\n        EventAggregator bus,\n        OriginalMessage sourceMessage,\n        OriginalArgs args,\n        TimeSpan delay\n    ) {\n        _bus = bus;\n        _args = args;\n        _msg = sourceMessage;\n        _timer = new DispatcherTimer();\n        _timer.Interval = delay;\n        _timer.Tick += OnTimerTick;\n    }\n\n    void OnTimerTick(object sender, EventArgs args) {\n\n        _bus.GetEvent<MyDelayedMessage>().Publish(_args);\n    }\n}	0
18639010	18604912	Resizing image with MaxHeight and MaxWidth	protected void Page_Load(System.Object sender, System.EventArgs e) {\n    if (!Page.IsPostBack) {\n        LoadImage();\n    }\n}\n\nprivate void LoadImage(){\n    Image1.ImageUrl = LoadURLFromDatabase(params);\n    Image1.Width = (int)(image.Width * ratio);\n    Image1.Height = (int)(image.Height * ratio);\n}	0
2929202	2929027	Fitting place names into map shapes	public Point Centrality(Point somePoint, Point[] otherPoints)\n{\n    float sumOfSquares = 0;\n    foreach (Point point in otherPoints)\n    {\n        float dist = DistanceBetween(somePoint, point);\n        sumOfSquares += dist * dist;\n    }\n    return 1 / sumOfSquares;\n}	0
11475352	11472172	How to find an application installation path in the ms windows registry via EXE name	var key = Registry.LocalMachine.OpenSupKey("SOFTWARE\MyCompany\Data");\nvar value = key.GetValue("Location");	0
17621088	17621059	Response redirect to same page with querystring on page load	void Page_Load( ... )\n{\n    if (!Page.IsPostBack)\n    {\n        if (QueryString["VisitFlag"] == null)\n            Response.Redirect("Welcome.aspx?VisitFlag=Done");\n    }\n}	0
20378858	20377796	Make an object lifetime depend on another without the latter referencing the former	yourTable.TryGetValue(B)	0
16920988	16865532	How to run NUnit in debug mode from Visual Studio?	Attach to Process	0
30260335	30258551	How to avoid complete refresh on button click in custom tab of Outllook Plugin	public void SendAutoNotification()\n    {\n        Outlook.MailItem mailItem = (Outlook.MailItem)\n            Globals.AutoMailer.Application.CreateItem(Outlook.OlItemType.olMailItem);\n        mailItem.Subject = "AutoGeneratedEmail";\n        mailItem.To = "xxx.xxx@xxx.com";\n        mailItem.Body = "This is just for test purpose. This is an auto generated email from outlook adddin";\n        mailItem.Importance = Outlook.OlImportance.olImportanceLow;\n        ((Outlook._MailItem)mailItem).Send();\n    }	0
1441429	1441406	How do I access a file share programattically	net.exe	0
5560965	5560952	How to add a Click event to an Ellipse in code behind?	Ellipse ellipse = new Ellipse();\nellipse.MouseUp += ellipse_MouseUp;\n\nprivate void ellipse_MouseUp(object sender, MouseButtonEventArgs e)\n{\n   ...\n}	0
28563345	28483931	GregorianCalendar last year day of the week	Private Function Date2Weekday(ByVal d As Date, ByVal y As Integer) As Date\n    'determine week\n    Dim weekNumber As Integer = Math.Ceiling(d.Day / 7)\n    'determine day number\n    Dim daynumber1 As Integer = Weekday(d)\n    'determine target first day of month\n    Dim targetDay1 As Date = New DateTime(y, d.Month, 1)\n    Dim targetDay1Number As Integer = Weekday(targetDay1)\n    Dim dt As Integer = (weekNumber * 7) + (daynumber1 - targetDay1Number)+1\n    If dt > weekNumber * 7 Then dt -= 7\n Date2Weekday = New DateTime(y, d.Month, dt)     \n End Function\n\nPrivate Function salescalendar(ByVal dtduty As DataTable) As DataTable\n   Dim eventcal As New DataTable\n    Dim lastyear = MyCalendar.GetYear(Now) - 1\n    Dim todays As Date = Now.Date\n Dim dayrecord = (From Row In eventcal.AsEnumerable\n                 Where Row.Field(Of DateTime)("date") = Date2Weekday(todays, lastyear)\n                Select Row.Field(Of Double)("sales")) \n  end function	0
10398713	10398686	Resolving bool from linq query	OnHomePage = im.PageImages.Any(p => p.ImageId == im.Id \n                                   && p.Page.PageName == "/Home");	0
5516530	5516448	What strategies enable use of an IoC container in a library?	private IMyDependency dependency;\n\npublic MyClass(IMyDependency dependency)\n{\n    this.dependency = dependency;\n}\n\npublic MyClass() : this(new MyDefaultImplementation())\n{\n\n}	0
21328722	21327017	Customizing button text appearance	Private Sub Button1_Paint(sender As System.Object, e As System.Windows.Forms.PaintEventArgs) Handles Button1.Paint\n        Button1.Text = String.Empty\n        e.Graphics.DrawString("Test", Button1.Font, Brushes.Black, New Point(0, 5))\nEnd Sub	0
14689274	14689128	FTP a file in .net	File.Copy()	0
1776735	1776578	C#: Bind XML to ComboBox via DataSet	DataSet dataSet = new DataSet();\nDataTable dataTable = new DataTable("table1");\ndataTable.Columns.Add("col1", typeof(string));\ndataSet.Tables.Add(dataTable);\n\nStringReader strR = new StringReader("<root><table1><col1>val1</col1></table1><table1><col1>val2</col1></table1></root>");\n\ndataSet.ReadXml(strR);\n\ncomboBox1.DataSource = dataSet.Tables[0];\ncomboBox1.DisplayMember = "col1";\ncomboBox1.ValueMember = "col1";	0
25932447	25931610	How to find UserControl on aspx page	Panel a = (Panel)pnlAddEdit;\nUserControl ab = (UserControl )a.FindControl("EditProduct1");	0
19006433	18884525	Logic to kill a process within a time limit	if (process.ExitCode != 0)\n{\n    this.completed = false;\n}	0
33657581	33656899	EF & Linq unable to retrieve related data	[JsonIgnore]	0
18704034	18220155	Automatic update of Text Boxes using a class of variables	public String RemoteTestBinding\n{\n    get { return "Value to return"; }\n}	0
19528843	19528669	Adding "--help" parameter to C# console application	string[] args = Environment.GetCommandLineArgs();\n        if (args.Length == 2)\n        {\n            if (args[1].ToLower(CultureInfo.InvariantCulture).IndexOf("help", System.StringComparison.Ordinal) >= 0)\n            {\n                // give help\n            }\n        }	0
23376839	23376806	Using a boolean to access array indices	games[radiant_wins==0 ? 0:1] = radiant_players;\ngames[radiant_wins==1 ? 0:1] = dire_players;	0
5283336	5283307	disable dropdownlist items	if (i % 5 > 0) {\n   dropdownlist1.items[i].Attributes.Add("disabled","disabled");\n}	0
1356443	1356425	C# 3.0 Remove chars from string	string s = "lsg  @~A\tSd 2??R3 ad"; // note tab\ns = Regex.Replace(s, @"\s+", " ");\ns = Regex.Replace(s, @"[^a-zA-Z ]", ""); // "lsg A Sd R ad"	0
34185175	34184602	Refactoring foreach loop with several of if-else statements	public List<Models.EmployeeInfo> GetEmployeeInfo(SPListItemCollection splic)\n{\n    var listEmployeeInfo = new List<Models.EmployeeInfo>();\n    var propertyNames = new List<string>(){"EmployeeName","Position","Office","IsPublic"}\n\n    foreach (SPListItem item in splic)\n    {\n        var employeeInfo = new Models.EmployeeInfo(); \n\n        foreach (var propertyName in propertyNames)\n        {  \n            string newData = "";\n            if (item[propertyName] != null)\n            {\n                newData = item[propertyName];\n            }\n            employeeInfo.GetType().GetProperty(propertyName).SetValue(employeeInfo, newData, null); \n        }\n\n        listEmployeeInfo.Add(employeeInfo);\n    }\n    return listEmployeeInfo;\n}	0
19847877	19847819	How can I make a concentric pattern of circles in my WinForms application?	namespace ClickAppearBalls\n{\n    public partial class Form1 : Form\n    {\n        private Random randClick;\n        private Graphics paper;\n        private Pen pen;\n        private int circleSize = 30;\n\n        public Form1()\n        {\n            InitializeComponent();\n            randClick = new Random();\n            paper = picCanvas.CreateGraphics();\n\n        }\n\n        private void picCanvas_Click(object sender, EventArgs e)\n        {\n            int x, y;\n\n            x = picCanvas.Height / 2;\n            y = picCanvas.Width / 2;\n\n            Color color = Color.FromArgb(randClick.Next(0, 256), randClick.Next(0, 256), randClick.Next(0, 256));\n            Pen pen = new Pen(color);\n            pen.Width = 3;\n            paper.DrawEllipse(pen, x - circleSize/2, y - circleSize/2, circleSize, circleSize);\n\n            circleSize += 10; // increase size here\n        }\n    }\n}	0
21318082	21317789	Display data from List in C#	p2Trace.FileName = linkList[0].FileName;\np2Trace.Title = linkList[0].Title;\np2Trace.HotspotID = linkList[0].HotspotID;	0
6136114	6136066	C# regual expression needed	string cleanString = Regex.Replace(originalString, "(?<![a-zA-Z])EXAMPLE", "");	0
27798201	27702806	Need to add TreeListCommandEventArgs in radbutton eventargs	protected void RadButton1_Click(object sender, EventArgs e)\n{\n    RadTreeList1.ItemCommand -= new EventHandler<TreeListCommandEventArgs>(RadTreeList1_ItemCommand);\n\n    ContentPlaceHolder contentPage = this.Page.Master.FindControl("ContentPlaceHolder1") as ContentPlaceHolder;\n    RadButton R = sender as RadButton;\n    RadButton radbutton1 = R.Parent.FindControl("RadButton1") as RadButton;\n    CommandEventArgs e2 = new CommandEventArgs(null, radbutton1.CommandArgument);\n    TreeListCommandEventArgs e1 = new TreeListCommandEventArgs(null, radbutton1.CommandArgument, e2);\n    TreeListDataItem dataItem = e1.Item as TreeListDataItem;\n    Hashtable table = new Hashtable();\n    table["RowId"] = (dataItem.FindControl("Label1") as Label).Text;\n    table["Alias"] = (dataItem.FindControl("Label2") as Label).Text;\n}	0
7055360	7055332	A string representation of the properties and methods	SomeClass someObject = new SomeClass();\n\nint x = someObject.GetType().GetProperty ("X").GetGetMethod ().Invoke (someObject,null);\n\nsomObject.GetType().GetProperty("Y").GetSetMethod().Invoke(someObject, new object[] { "Value" });\n\nsomeObject.GetType().GetMethod("DoSomething").Invoke(someObject, null);	0
14872856	14722744	Exporting GridView with Data to Image in asp.net	1.First export gridview data to pdf. \n2.Then  convert it into image.	0
5077983	5077912	displaying pdf file after installation	myProcess.WaitForExit();	0
28225633	28119216	Saving a Drawn Image as MonoChrome	g = Graphics.FromImage(Signature);\ng.Clear(Color.White);	0
29441748	29441722	How can I read a text file after a certain posicion in c#	class test\n{\n    int currentIndex = 0;\n\n    private string myMethod(string input)\n    {\n        string val = input.Substring(currentIndex, 15);\n        currentIndex+=15;\n        return val;\n    }\n}	0
5935971	5935941	c# compare DateTime start and DateTime stop with List<DateTime>	if (dates.All(date => date >= start && date <= stop)) {\n    // Do something.\n}	0
6629216	6629185	Progmatically genereated emails for Outlook get stuck in Drafts folder even after being sent!	Outlook.MAPIFolder folder\n    = oNameSpace.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderDrafts);\n...\nmic.SaveSentMessageFolder = folder	0
29376570	29376491	Deserializing this JSON response to C#	public class MyData{ \n  [JsonProperty("locations")]\n  public Dictionary<string, Location> Locations {get;set;} \n}\npublic class Location\n{\n  public string street1 { get; set; }\n  public string street2 { get; set; }\n  public string city { get; set; }\n  public string state { get; set; }\n  public string postal_code { get; set; }\n  public string s_status { get; set; }\n  public string system_state { get; set; }\n}	0
11894692	11894586	clickable listview for all subItem in its item c#	listView1.FullRowSelect = true;	0
4674884	4674632	How can I copy byte[] into byte[,,]?	struct BitmapDataAccessor\n{\n    private readonly byte[] data;\n    private readonly int[] rowStarts;\n    public readonly int Height;\n    public readonly int Width;\n\n    public BitmapDataAccessor(byte[] data, int width, int height)\n    {\n        this.data = data;\n        this.Height = height;\n        this.Width = width;\n        rowStarts = new int[height];\n        for(int y=0;y<height;y++)\n          rowStarts[y]=y*width;\n    }\n\n    public byte this[int x, int y, int color] // Maybe use an enum with Red = 0, Green = 1, and Blue = 2 members?\n    {\n        get { return data[(rowStarts[y] + x) *3 + color]; }\n        set { data[(rowStarts[y] + x) *3 + color] = value; }\n    }\n\n    public byte[] Data\n    {\n        get { return data; }\n    }\n}	0
1573515	1573505	How to get a custom object out of a List<> with LINQ?	return products.Where(p => p.ProductNumber == productNumber).SingleOrDefault();	0
14905085	14903705	RegEx to parse stored procedure and object names from DDL in a .sql file C#	Regex DDL = new Regex(@"(?<=\b(create|alter|drop)\s+(procedure|proc|table|trigger|view|function)\b\s\[dbo\].)\[.*?\]", RegexOptions.IgnoreCase);\n    Match match = DDL.Match(inputScript);\n    while(match.Success)\n    {\n        textBox2.Text += "\r\n" + match.Groups[1].Value + " - " + match.Groups[2].Value + " - " +  match.Value;\n        match = match.NextMatch();\n    }\n    textBox3.Text = "DONE";	0
6543384	6543361	How to cast a list	List<A> listA = new List<A>();\nList<B> listB = new List<B>();\nfor (int i = 0; i < listA.Count; i++)\n{\n    listB.Add((B)listA[i]);\n}	0
23440833	23440749	Run a scheduled task from web application	using TaskScheduler;\n\nusing (TaskService tasksrvc = new TaskService(server.Name, login, domain, password)\n{\n    Task task = tasksrvc.FindTask(taskName);\n    task .Run();       \n}	0
8809269	8809248	how to load a comma separated numbers to List<int> in c#	string formIdList = ...\nList<int> ids = formIdList.Split(',').Select(int.Parse).ToList();	0
1742865	1742787	Check if a specific exe file is running	bool isRunning = Process.GetProcessesByName("test")\n                .FirstOrDefault(p => p.MainModule.FileName.StartsWith(@"c:\loc1")) != default(Process);	0
11304358	11304345	C# String with [@]	var result = string.Format(@"<S> \n          <child id='{0}'/> \n          <child id='{1}'> \n            <grandchild id='{2}' /> \n            <grandchild id='{3}' /> \n          </child> \n        </S>", id1, id2, id3, id4);	0
3458650	3458617	How can I return a Object with Data in it	var results = new List<page>();\nstring queryString = "SELECT PageID,ParentID...";\nusing (SqlConnection connection = new SqlConnection(connectionString))\n{\n    SqlCommand command = new SqlCommand(queryString, connection);\n    connection.Open();\n    SqlDataReader reader = command.ExecuteReader();\n    while (reader.Read())\n    {\n        page p= new page();\n        p.PageID = reader["PageID"]; \n        //...\n        results.Add(p);\n    }\n    reader.Close();\n}\nreturn results;	0
5805573	5804596	Watin Runscript No Wait	string timed = string.Format("setTimeout(\"{0}\", 500);", script);\n\nDocument.RunScript(timed);	0
17114889	17114664	Using a string for a pattern in regex using key regex characters	myM = Regex.Matches(s, phrase, RegexOptions.IgnoreCase);	0
16360746	16310044	Storing an object[] as column in Fluent NHibernate	Map(x => x.Args).CustomType<ObjectArrayType>();\n\nclass ObjectArrayType : IUserType\n{\n    public object NullSafeGet(IDBReader reader, string[] names, object owner)\n    {\n        byte[] bytes = NHibernateUtil.BinaryBlob.NullSafeGet(reader, names[0]);\n        return Deserialize(bytes);\n    }\n\n    public void NullSafeSet(IDBCommand cmd, object value, int index)\n    {\n        var args = (object[])value;\n        NHibernateUtil.BinaryBlob.NullSafeSet(cmd, Serialize(args), index);\n    }\n\n    public Type ReturnType\n    {\n        get { return typeof(object[]); }\n    }\n\n    public SqlType[] SqlTypes\n    {\n        get { return new [] { SqlTypeFactory.BinaryBlob } }\n    }\n}	0
12877828	12877588	C# How To Do Inheritance From A Generic Class	class ClassB<T> : ClassA<T> {}\nclass ClassC<T> : ClassB<T> {}	0
27889033	27888881	Check values in DataTable	for (int counter = 0; counter < dtTwo.Rows.Count; counter++)\n{\n    var contains=dtOne.Select("ColumnC= '" + dtTwo.Rows[counter][0].ToString() + "'");\n    if (contains.Length != 0)\n    {\n       Response.Write("CostCode "+dtTwo.Rows[counter][0].ToString()+" not present in the Excel");\n       break;\n    }\n}	0
6518822	6518584	Detecting 302 Redirect	webReq.UserAgent = "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US) AppleWebKit/525.13 (KHTML, like Gecko) Chrome/0.A.B.C Safari/525.13";	0
11367861	11367830	How to find FULL name of calling method C#	MethodBase method = stackTrace.GetFrame(1).GetMethod();\nstring methodName = method.Name;\nstring className = method.ReflectedType.Name;\n\nConsole.WriteLine(className + "." + methodName);	0
32217928	32217866	How to make a column read only in data grid in asp.net	DT.Columns(0).ReadOnly = True '// Make the column(0) readonly and assign to DataGrid.\n\n   Datagrid!.DataSource = DT	0
10971510	10968728	Check the border of a sprite in XNA?	class Car\n{\n   // Keep a reference to the game inside the car class.\n   Game game;\n\n   public Car (Game game)\n   { \n      this.game = game;\n   }\n\n   public void Update(.....\n   { \n       // You can access the client bounds here.\n       // the best thing about this method is that\n       // if the bounds ever changes, you don't have\n       // to notify the car, it always has the correct\n       // values.\n   }\n}	0
31088097	31087909	C# how to input numbers in to the second text box. whenever I click the button it keeps apearing in the 1st textbox	private void eight_Click(object sender, EventArgs e)\n    {\n        tbox1.Text = tbox1.Text + "8 h"; // changing text box 1\n        tbox2.Text = tbox2.Text + "H"; // changing text box 2\n    }	0
7995967	7995725	facing error for inserting xml data into database table using c#	XmlDocument _document = new XmlDocument();\n_document.LoadXml(_xmlString);\nXmlDeclaration _declaration = (XmlDeclaration)_document.FirstChild;\n_declaration.Encoding = "UTF-16";	0
1928974	1928933	C# get date/time a windows service started	using System.Diagnostics;\n private static DateTime GetStartTime(string processName)\n {\n    Process[] processes = \n        Process.GetProcessesByName(processName);\n    if (processes.Length == 0) \n       throw new ApplicationException(string.Format(\n          "Process {0} is not running.", processName));\n    // -----------------------------\n    DateTime retVal = DateTime.Now;\n    foreach(Process p in processes)\n       if (p.StartTime < retVal) \n          retVal = p.StartTime;\n\n    return retVal ;\n }	0
19120669	19120138	Spliting string into 3 parts	string st = "Adams, John - 22.6.2001";\n\n// first split on dash, to seperate name and date\nstring[] partsArray = st.Split('-');\n\n// now split first part to get first and surname (trim surrounding whitespace)\nstring[] nameArray = partsArray[0].Split(',');\nstring firstName = nameArray[1].Trim();\nstring lastName = nameArray[0].Trim();\n\n// get date from other part (again trim whitespace)\nstring dateAsString = partsArray[1].Trim();	0
12422029	12421938	GridView How to get the value from a textbox in EDIT MDOE	GridViewRow row = (GridViewRow)(((LinkButton)e.CommandSource).NamingContainer);\nstring name = ((TextBox)row.FindControl("TextBox1")).Text\n\nCmd.CommandText = "update Customers set customer_name = '" + name + "', modified_on = getdate(), modified_by = '" + System.Environment.UserName + "' where customer_id = '" + customerID + "'";	0
2162835	2162752	Setting an image.Source from a resource file	new BitmapImage(new Uri("C:\Users\Sergio\Documents\Visual Studio 2008\Projects\emailwpf\emailwpf\ok.png"))	0
11260568	11259947	Regex to match given string filenames in a string	using System;\nusing System.Collections.Generic;\nusing System.Text.RegularExpressions;\n\nnamespace ConsoleApplication1\n{\n    class Program\n    {\n        static void Main(string[] args)\n        {\n            const string example = "PrintFileURL(\"13572_IndividualInformationReportDelta_2012-06-29_033352.zip\",\"13572_IndividualInformationReportDelta_2012-06-29_033352.zip\",0,\"53147\",\"Jun 29 3:33\",\"/icons/default.gif\")";\n            Console.WriteLine(example);\n\n            const string pattern = "\\\"([a-zA-Z0-9\\-_]*?\\..*?)\\\"";\n            var regex = new Regex(pattern);\n            var result = regex.Matches(example);\n            foreach (Match item in result)\n            {\n                Console.WriteLine(item.Groups[1]);\n            }\n        }\n    }\n}	0
27804339	27803901	How can I retrieve selected item's both Text and Value from DropDownList in MVC	public ActionResult EcgBilling()\n{\n    var model = new SelectBillingSiteReportModel\n    {\n        Sites = new List<SelectListItem>\n        {\n            new SelectListItem {Text = "One", Value = "One:1"},\n            new SelectListItem {Text = "Two", Value = "Two:2"},\n            new SelectListItem {Text = "Three", Value = "Three:3"},\n        }\n    };\n    return View(model);\n}\n\n[HttpPost]\npublic ActionResult EcgBilling(SelectBillingSiteReportModel model)\n{\n    string[] array = model.SelectedSiteKey.Split(':');\n    string text = array[0];\n    string value = array[1];\n    return View();\n}	0
19259804	19254839	WebBrowser Control Changing Attributes	element.OuterHtml	0
21038866	21036696	Removing not visible rows from DataGridView	private void tmr_GET_Tick(object sender,EventArgs e) \n{\n    //copied from your comment\n    string[] row= { ar[i, 0], ar[i, 1], ar[i, 2], ar[i, 3], ar[i, 4], ar[i, 5], ar[i, 6], ar[i, 7]}; \n    dataGridView1.Rows.Add(row); \n    //Check if max rows quantity exceeds and remove first row\n    if (dataGridView1.Rows.Count = 16)\n        dataGridview1.Rows.RemoveAt(0);\n}	0
21483042	21481954	Bitmap with Nearest Neighbor Causes Tearing	UseLayoutRounding="True"	0
31716039	31677639	Set Property in Viewmodel from Code Behind	public class ConversionViewModel()\n{\n    private static ConversionViewModel _this;\n    public ConversionViewModel()\n        {\n            InitializeComponent();\n            _this = this;\n        }\n\n        public static ConversionViewModel GetInstance()\n        {\n            return _this;\n        }\n\n      //Other prop and methods\n}\n\nprivate void myTreeView_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)\n        {\n            try\n            {\n\n                Field selectedField = new Field();\n\n                selectedField = (Field)myTreeView.SelectedItem;\n\n               ConversionViewModel.GetInstance().AddConversionType(selectedField.Table, selectedField.Name);                       \n            }\n            catch (Exception ex)\n            {\n                MessageBox.Show(ex.Message);\n            }\n        }	0
16618870	16617933	protobuf-net - generated class from .proto - Is repeated field supposed to be Read Only with no setter?	var order = new Order();\norder.Lines.Add( new OrderLine {...} );	0
15032982	15032643	Get Values from Process StandardOutput	StringCollection values = new StringCollection();\n    var proc = new Process\n    {\n        StartInfo = new ProcessStartInfo\n        {\n            FileName = "openfiles.exe",\n            Arguments = "/query /FO CSV /v",\n            UseShellExecute = false,\n            RedirectStandardOutput = true,\n            RedirectStandardError = true,\n            CreateNoWindow = false\n        }\n    };\n    proc.Start();\n\n    proc.OutputDataReceived += (s,e) => {\n        lock (values)\n        {\n            values.Add(e.Data);\n        }\n    };\n    proc.ErrorDataReceived += (s,e) => {\n        lock (values)\n        {\n            values.Add("! > " + e.Data);\n        }\n    };\n\n    proc.BeginErrorReadLine();\n    proc.BeginOutputReadLine();\n\n    proc.WaitForExit();\n    foreach (string sline in values)\n        MessageBox.Show(sline);	0
12915730	10122355	How to validate a Search String using Model First approach in MVC 3?	namespace Models\n{\n    [MetadataType(typeof(UserSearchMetadata))]\n    public partial class UserSearch\n    {\n        //some class\n    }\n\n    public class UserSearchMetadata\n    {\n        [Required] //required attribute\n        public string SearchString {get;set;}\n    }\n}	0
30907915	30598050	Copy/clone an Excel shape with EPPlus to other worksheet?	/// <summary>\n    /// Add a new shape to the worksheet\n    /// </summary>\n    /// <param name="Name">Name</param>\n    /// <param name="Source">Source shape</param>\n    /// <returns>The shape object</returns>\n\n    public ExcelShape AddShape(string Name, ExcelShape Source)\n    {\n        if (Worksheet is ExcelChartsheet && _drawings.Count > 0)\n        {\n            throw new InvalidOperationException("Chart worksheets can't have more than one drawing");\n        }\n        if (_drawingNames.ContainsKey(Name))\n        {\n            throw new Exception("Name already exists in the drawings collection");\n        }\n        XmlElement drawNode = CreateDrawingXml();\n        drawNode.InnerXml = Source.TopNode.InnerXml;\n\n        ExcelShape shape = new ExcelShape(this, drawNode);\n        shape.Name = Name;\n        shape.Style = Source.Style;\n        _drawings.Add(shape);\n        _drawingNames.Add(Name, _drawings.Count - 1);\n        return shape;\n    }	0
3958394	3958058	Deserialize custom SOAP/XML to objects	XDocument result = XDocument.Parse(e.Result.ToString());\n\nXmlNamespaceManager nsManager = new XmlNamespaceManager(new NameTable());\nXNamespace namespace = result.Root.GetDefaultNamespace();\nnsManager.AddNamespace("def", namespace.NamespaceName);\n\nIEnumerable<XElement> ele = result.XPathSelectElements("/def:GetAllUserCollectionFromWeb/def:Users/def:User", nsManager);	0
23226518	23226464	Convert string with hex values to byte array	byte[] t = x.Split().Select(s => Convert.ToByte(s, 16)).ToArray();	0
9524235	9523429	How to sort items that are databound	SqlDataSource2.SelectCommand = "SELECT * FROM dealervideo inner join videos on videos.RecID = dealervideo.VideoRecID inner join dealers on dealers.RecID = dealervideo.DealerRecID where dealers.RecID = " + hidRecID.Value + " ORDER BY videos.RecID";	0
6081238	6081170	How can I update a DataTable in C# without using a loop?	DataRow dr = datatable.AsEnumerable().Where(r => ((string)r["code"]).Equals(someCode) && ((string)r["name"]).Equals(someName)).First();\ndr["color"] = someColor;	0
8572046	8571991	Find gridview linkbutton value jquery	row.children("td:eq(1)").find('a').text();	0
32618284	32615141	LINQ Joining Two Tables and Getting the Row with Max ID	var currentParts=tblPartsVersion\n  .GroupBy(v=>v.PartID)\n  .Select(x=>x.OrderByDescending(pv=>pv.PartVersionID).First());	0
9689917	9689867	DeleteCommand in datalist, Cannot convert int to target type string	SqlDataSource1.DeleteParameters["BrandID"].DefaultValue =\n    Datalist1.DataKeys[e.Item.ItemIndex].ToString();	0
22403947	22403755	Get url src from iframe using regex c#	string search = "<iframe width=\"100%\" height=\"450\" scrolling=\"no\" frameborder=\"no\" src=\"https://w.soundcloud.com/player/?url=https%3A//api.soundcloud.com/playlists/26104012&amp;auto_play=false&amp;hide_related=false&amp;visual=true%22\"></iframe>";\nstring sPattern = "^.*src=.*playlists\\/([0-9]+)&.*$";\n\n\nMatch match = Regex.Match(search, sPattern, RegexOptions.IgnoreCase);\n// Here we check the Match instance.\nif (match.Success)\n{\n    // Finally, we get the Group value and display it.\n    string id = match.Groups[1].Value;\n}	0
4150915	4150902	IEnumerable data type: how to create a null object?	Enumerable.Empty<T>()	0
2534135	2534083	Dynamically load a type from an external assembly	Assembly assembly = Assembly.LoadFile("Lib.dll");\nILib lib = (ILib)assembly.CreateInstance("Lib");\nlib.doSomething();	0
17185162	17185048	All songs are starting simultaneously instead of one after another	WindowsMediaPlayer player = new WindowsMediaPlayer;\n\n        for (int i = 1; i < 30; i++)\n        {\n            IWMPMedia media = player.newMedia( @"C://Songs//m" + i + ".mp3");\n            player.currentPlaylist.appendItem(media);                \n        }\n\n        player.controls.play();	0
18267418	18267362	Linq Result Join all Rows Data to string	string.Join(",", dataLists.Select(x => x.EMAILID));	0
18686666	18685981	How to redirect my Windows Phone C# app to a setting page?	Windows.System.Launcher.LaunchUriAsync(new Uri("ms-settings-bluetooth:"));	0
8724197	8643867	Is there a way to protect Unit test names that follows MethodName_Condition_ExpectedBehaviour pattern against refactoring?	public CityGetterTests \n{\n   public class GetCity\n   {\n      public void TakesParidId_ReturnsParis()\n      {\n          //...\n      }\n\n      // More GetCity tests\n   }\n}	0
915889	915795	Pass FieldName as a Parameter	internal class Program {\n    private static void Main(string[] args) {\n        var bar = new Bar {A = 1, B = 2, C = 3};\n        Console.WriteLine(new Foo().X(bar, it => it.A));\n        Console.WriteLine(new Foo().X(bar, it => it.B));\n\n        // or introduce a "constant" somewhere\n        Func<Bar, int> cFieldSelector = it => it.C;\n        Console.WriteLine(new Foo().X(bar, cFieldSelector));\n    }\n}\n\ninternal class Foo {\n    // Instead of using a field by name, give it a method to select field you want.\n    public int X(Bar bar, Func<Bar, int> fieldSelector) {\n        return fieldSelector(bar) * 2;\n    }\n\n    public int A(Bar bar) {\n        return bar.A * 2;\n    }\n\n    public int B(Bar bar) {\n        return bar.B * 2;\n    }\n\n    public int C(Bar bar) {\n        return bar.C * 2;\n    }\n}\n\ninternal class Bar {\n    public int A;\n    public int B;\n    public int C;\n}	0
12544531	12544354	Selecting an item in the RadioButtonList, how to get a list of items to a ListBox from database in asp.net c#	protected void Page_Load(object sender, EventArgs e)??\n{\n   if (!Page.IsPostBack)\n   {\n          RadioFill();\n   }\n}	0
2532017	2532003	Intersect a collection of collections in LINQ	var result = input.Cast<IEnumerable<int>>().Aggregate((x, y) => x.Intersect(y))	0
25852976	25850239	Find matching sequences that have exactly one deviation	Testing value    Input value    ABS(Subtraction)\n--------------+--------------+------------------\n123356789        123456789      100000\n193456789        123456789      70000000\n123450789        123456789      6000\n123456786        123456789      3	0
3991675	3991616	C# Lambda Expression Mapping Multiple Conditions	rec.IsDBNull(rec.GetOrdinal("BloodGroup")) ? BloodGroup.NotSet :\nrec.GetOrdinal("BloodGroup")==1 ? BloodGroup.OPositive :\nrec.GetOrdinal("BloodGroup")==2 ? BloodGroup.ONegative :\nBloodGroup.NotSet	0
24842950	24842790	Programmatically setting button image from database	byte[] data = (byte[])reader["YourColumnName"];\n using (MemoryStream ms = new MemoryStream(data))\n {\n     //here you get the image and assign it to the button.\n     Image image = new Bitmap(ms);\n }	0
28470345	28469891	Image source changeing in C# for windows phone 8.1 RT	myImage.Source = new BitmapImage(new Uri(\n  "ms-appx:///Assets/WorldCupFlags/Sri_Lanka.png", UriKind.Absolute));	0
6420007	6419909	Bind dynamically created properties to a grid	var dataSource = myList.Select(item=> new \n              { Name = item.Key, \n                MainAddress = item.Address.First() });\ngrid.DataSource = dataSource;\ngrid.DataBind();	0
8010215	8006245	How to set datasource of Sub crystal report in c# win form app	ReportDocument cryRpt = new ReportDocument();\ncryRpt.Load("C:/MainReport.rpt");\ncryRpt.DataSourceConnections.Clear();\ncryRpt.SetDataSource(ds.Tables[0]);\ncryRpt.Subreports[0].DataSourceConnections.Clear();\ncryRpt.Subreports[0].SetDataSource(ds.Tables[0]);\ncrystalReportViewer1.ReportSource = cryRpt;\ncrystalReportViewer1.Refresh();	0
29270427	29269986	How do I choose a registered dependent type at runtime using Unity IoC?	UnityIoC.Instance.RegisterType<IDataAccess,SQLServerDataAccess>("SQL");\nUnityIoC.Instance.RegisterType<IDataAccess,MongoDataAccess>("Mongo");\n\nUnityIoC.Instance.RegisterType<CustomerManager,CustomerManager>("Mongo", new InjectionConstructor(new ResolvedParameter<IDataAccess>("Mongo")));\n\nUnityIoC.Instance.RegisterType<CustomerManager,CustomerManager>("SQL", new InjectionConstructor(new ResolvedParameter<IDataAccess>("SQL")));\n\nCustomerManager manager = UnityIoC.Instance.Resolve<CustomerManager>();	0
6568362	6568306	Get argument value from string input	public string GetArgumentValueByName(string queryString, string paramName)\n{\n    var paramCol = HttpUtility.ParseQueryString(queryString);\n    return paramCol[paramName] ?? string.Empty;        \n}	0
14079990	14079952	Checked Id Doesn't retrieve from a gridview	foreach (GridViewRow row in GvDDlToken.Rows)\n{\n    if(((CheckBox)row.FindControl("CheckBox1")).Checked == true)\n    {\n    //some code\n    }\n}	0
9579001	9578510	how to convert a string received from jquery to c# dynamic object?	public static class JavaScriptSerializerExtension\n{\n    public static dynamic DeserializeDynamic(this JavaScriptSerializer serializer, string value)\n    {\n        var dic = serializer.Deserialize<IDictionary<string, object>>(value);\n        return ToExpando(dic);\n    }\n\n    private static ExpandoObject ToExpando(IDictionary<string, object> dic)\n    {\n        var expando = new ExpandoObject() as IDictionary<string, object>;\n\n        foreach (var item in dic)\n        {\n            var prop = item.Value as IDictionary<string, object>;\n            expando.Add(item.Key, prop == null ? item.Value : ToExpando(prop));\n        }\n\n        return (ExpandoObject)expando;\n    }\n}	0
26376568	26376453	Custom Route Not Matched	public static void RegisterRoutes(RouteCollection routes)\n    {\n        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");\n\n        routes.MapRoute(\n            name: "Custom",\n            url: "Secret/Routes/1",\n            defaults: new { controller = "Account", action = "Login", id = UrlParameter.Optional}\n        );\n\n        routes.MapRoute(\n            name: "Default",\n            url: "{controller}/{action}/{id}",\n            defaults: new { controller = "Home", action = "Contact", id = UrlParameter.Optional }\n        );\n    }	0
348800	348743	How do I Send SMS to Active Directory Users	System.DirectoryServices.	0
21406808	21405367	"Adress already in use" when trying to start a tcpListener after stoping it	tcpListener.Close();	0
621647	621266	Continue in while inside foreach	foreach (string objectName in this.ObjectNames)\n{\n    // Line to jump to when this.MoveToNextObject is true.\n    this.ExecuteSomeCode();\n    while (this.boolValue)\n    {\n        if (this.MoveToNextObject())\n        {\n            // What should go here to jump to next object.\n            break;\n        }\n    }\n    if (! this.boolValue) continue; // continue foreach\n\n    this.ExecuteSomeOtherCode();\n}	0
11203018	11202654	Set all values in SelectList in C#	public SelectList(\n    IEnumerable items,\n    string dataValueField,\n    string dataTextField\n)	0
17478333	17478295	c# for loop wrong number of iterations	var endIndex = Convert.ToInt32(s[k]);\n    for (int i = 0; i < endIndex; i++)	0
3616239	3616215	Like in Lambda Expression and LINQ	customers.Where(c => c.Name.Contains("john"));	0
25398342	25398057	Use variable from Main method in another method	using System.IO;\nusing System.Linq;\nusing System;\n\nclass Program\n{\n    static void Main()\n    {\n        int[] scores = { 4, 7, 9, 3, 8, 6 };\n        Console.WriteLine(resoult(scores));\n    }\n\n    static int resoult(int[] pScores)\n    {\n        return pScores.Sum() - pScores.Max() - pScores.Min();\n    }\n}	0
25010550	24998004	Autofac type registered on a keyed enum with a constructor not resolving	builder.RegisterType<ClassImplementation>()\n                .UsingConstructor(typeof (IAnotherClassInterface ))\n                .Keyed<IClass>(EnumType.First);	0
21788140	21787436	My Windows service is reading 100's of files with thousands of records in each file and inserting in to Sql server using threading	while not end of input\n{\n    read a batch of records from the disk\n    wait for pending asynchronous SQL insert operation to complete\n    start asynchronous SQL insert operation with\n}	0
5497226	5497162	get the username and nickname of any users from active directory	DirectoryEntry directoryEntry = new DirectoryEntry("WinNT://" + Environment.MachineName);\nstring userNames="Users :  ";\nforeach (DirectoryEntry child in directoryEntry.Children)\n{\n    if (child.SchemaClassName == "User")\n    {\n        userNames += child.Name + Environment.NewLine;\n        PropertyCollection coll = child.Properties;\n\n        // sample of how to get other values\n        object fullName = coll["FullName"].Value;         \n        object nickName = coll["OtherName"].Value;         \n    }\n\n}\nMessageBox.Show(userNames);	0
27271924	27271156	Set sort order on images	void setSort()\n{\n    string id = dataGridView1[0, 0].Value.ToString();\n    int sOrder = 0;\n    for (int row = 0; row < dataGridView1.Rows.Count; row++)\n    {\n        if (dataGridView1[0, row].Value == null) break;\n        string id2 = dataGridView1[0, row].Value.ToString();\n        if (id2 != id) sOrder = 0;\n        sOrder++;\n        dataGridView1[1, row].Value = sOrder;\n        id = id2;\n    }\n}	0
11262305	11235089	C# code for writing data to OpenTSDB	string message = "put mymetric.data_1 1295643636 48 a=foo";\nIPAddress ip = IPAddress.Parse("xxx.xxx.xxx.xxx"); // tsdb deamon host ip\nIPEndPoint endPoint = new IPEndPoint(ip, 4242); // tsdb deamon port\n\nusing (Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))\n{\n    s.Connect(endPoint);\n    s.Send(new ASCIIEncoding().GetBytes(message + Environment.NewLine));\n    s.Close();  \n}	0
5320033	5319391	mysql % due to spaces in db filepath	Image1.ImageUrl	0
32898573	32898181	SQL Query with multiple parameters that could be empty strings	where (td.ApprovedBy == approvedBy && td.Location == location && (pcp == "" || td.PCP == pcp) && (ipa == "" || td.IPA == ipa))	0
18897992	18886873	Add a connection string to local user config file throws lock exception	var connectionString = string.Format(ConnectionStringBase, dbLocation);\n\nvar entities = new DatabaseEntities(connectionString);	0
13885863	13885809	ZipDotNet return file paths from directory to zip	path.Replace("ZipEntry://", "");	0
20325899	20325849	Replacing char on the end of string	myString = myString.TrimEnd('/');	0
9341497	9341284	How do I print multiple pages from WinForms?	if (offsetY >= pageHeight)\n{\n    e.HasMorePages = true;\n    offsetY = 0;\n    return; // you need to return, then it will go into this function again\n}\nelse {\n    e.HasMorePages = false;\n}	0
17154938	17154769	Insert multiple sql rows via stored proc	insert into myTable (select *, literalValue from someOtherTable);	0
24826609	24826142	Execute SQL script files via PowerShell using a console app	//get application path and script directory\nprivate const string scriptPath = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "Scripts");\n\nprivate void RunScripts()\n{\n    string[] scripts = Directory.GetFiles(scriptPath, "*.sql", SearchOption.TopDirectoryOnly);\n    //name them script01.sql, script02.sql ...etc so they sort correctly\n    Array.Sort(scripts);\n\n    if (scripts.Length > 0)\n    {\n        using (SqlConnection conn = new SqlConnection(ConfigurationManager.AppSettings["ConnectionStringKey"]))\n        {\n            conn.Open();\n            using (SqlCommand cmd = conn.CreateCommand())\n            {\n                foreach (string script in scripts)\n                {\n                    cmd.CommandText = File.ReadAllText(script);\n                    cmd.ExecuteNonQuery();\n                }\n            }\n        }\n    }\n}	0
21248158	21248117	Clicking a Button in a button array	public void WepaonEquip(Object sender, System.EventArgs e)\n{\n    Button clickedbutton = (Button)sender\n    clickedbutton.BackColor = Color.OrangeRed;\n\n}	0
30328534	30323980	open app url scheme without option to go to store if not available windows phone 8	Launcher.LaunchUriAsync	0
23028658	23028643	how to remove the blank space	private void button1_Click(object sender, RoutedEventArgs e)\n    {\n        if (textBox1.Text.Trim() =="")\n        {\n            MessageBox.Show("Campul este liber!");\n            return;\n\n        }\n        //ListBox li = sender as ListBox;\n\n\n        ListBoxItem li = new ListBoxItem();\n        li.Content=textBox1.Text;\n        textBox1.Clear();\n        listBox1.Items.Add(li);\n\n        textBox1.Focus();\n\n\n\n\n    }	0
2991261	2991163	Error invoking stored procedure with input parameter from ADO.Net	public static void Run()\n        {\n            try\n            {\n                _command.Parameters.AddWithValue("@Param1", 300101);\n                _command.Parameters.AddWithValue("@Param2", 100);\n                _command.Parameters.AddWithValue("@Param3", 200);\n\n                _command.ExecuteScalar();\n            }\n            catch (Exception e)\n            {\n                Console.WriteLine(e);\n            }\n        }	0
13870767	13868849	Using an Array declared in a XAML resource	Items.Cast<Color> ()	0
18125475	18060048	Keep Console.ReadLine always on last line	class Program\n{\n    static void Main(string[] args)\n    {\n        new Messager(1000 * 2.5f);\n        new Messager(1000 * 3);\n        while (true)\n        {\n            Console.ReadLine();\n        }\n    }\n}\n\npublic class Messager\n{\n    Timer Timer;\n\n    public Messager(double interval)\n    {\n        this.Timer = new Timer(interval);\n        this.Timer.Elapsed += (sender, e) =>\n        {\n            int currentTopCursor = Console.CursorTop;\n            int currentLeftCursor = Console.CursorLeft;\n\n            Console.MoveBufferArea(0, currentTopCursor, Console.WindowWidth, 1, 0, currentTopCursor + 1);\n\n            Console.CursorTop = currentTopCursor;\n\n            Console.CursorLeft = 0;\n\n            Console.WriteLine("message from " + this.Timer.Interval);\n\n            Console.CursorTop = currentTopCursor +1;\n            Console.CursorLeft = currentLeftCursor;\n\n        };\n        this.Timer.Start();\n    }\n}	0
1162027	1161950	Copying part of one XML DOM to another for XSL transformation (.NET)	foreach (XmlElement xmlUnit in xmlMain.SelectNodes("/report/unit"))\n{\n    var xmlDest = new XmlDocument();\n    xmlDest.AppendChild(xmlDest.CreateElement("report"));\n\n    // Add the report properties...\n    foreach ( XmlElement xmlValue in xmlMain.SelectNodes( "/report/report_name | /report/report_date" ) )\n    xmlDest.DocumentElement.AppendChild(xmlDest.ImportNode(xmlValue, true));\n\n    // Add the "<unit>" element from the main document...\n    xmlDest.DocumentElement.AppendChild(xmlDest.ImportNode(xmlUnit, true));\n\n    // Now generate report using xmlDest\n}	0
4224735	4224717	How to set default value for a variable in C#?	string a = GetValue() ?? "Default";	0
16773481	16773316	Convert string to int in linq-to-sql query: how to deal with values which cannot be converted?	join  temps in dc.T_DM_Temps on demands.DateDemande_FK equals temps.Temps_PK\nwhere dc.ISNUMERIC(leads.GeolocDistanceRouteDistrib) // Added!\nwhere leads.longitudeClient != null && (Convert.ToInt32(leads.GeolocDistanceRouteDistrib) > 1000*30) && (temps.Date > new DateTime(2000, 1, 1).Date)\nselect new Lead	0
11994628	11994530	Moving a control within another control's visible area	private Point start = Point.Empty;\n\nvoid pictureBoxPackageView_MouseUp(object sender, MouseEventArgs e) {\n  _mapPackageIsMoving = false;\n}\n\nvoid pictureBoxPackageView_MouseMove(object sender, MouseEventArgs e) {\n  if (_mapPackageIsMoving) {\n    pictureBoxPackageView.Location = new Point(\n                             pictureBoxPackageView.Left + (e.X - start.X), \n                             pictureBoxPackageView.Top + (e.Y - start.Y));\n  }\n}\n\nvoid pictureBoxPackageView_MouseDown(object sender, MouseEventArgs e) {\n  start = e.Location;\n  _mapPackageIsMoving = true;\n}	0
26328876	26328782	How to add directory location to mysql varchar?	string input = @"C:\SomeFolder\SubFolder\image.jpg";\nstring query = input.Replace(@"\", @"\\");	0
13543247	13543146	Access SQLite db from MMF	Data Source=:memory:	0
6595015	6583414	Import multiple .xml files into a DataSet	private ArrayList GetFilePaths()\n    {\n        ArrayList filePaths = new ArrayList();\n        FolderBrowserDialog folder = new FolderBrowserDialog();\n        folder.ShowDialog();\n\n        foreach (string filePath in Directory.EnumerateFiles(folder.SelectedPath))\n        {\n            filePaths.Add(filePath.ToString());\n        }\n        return filePaths;\n    }\n\n    private void ImportXmls(ArrayList filePaths)\n    {\n        DataSet[] tempDSCollection = new DataSet[filePaths.Count];\n        int impFiles = 0;\n        foreach (object ob in filePaths)\n        {\n            DataSet impDS = new DataSet();\n            impDS.ReadXml(ob.ToString());\n\n            tempDSCollection[impFiles] = impDS;\n            impFiles++;\n        }\n\n        foreach (DataSet aDS in tempDSCollection)\n        {\n            foreach (DataTable table in aDS.Tables)\n            {\n                mainDS.Merge(table);\n            }\n        } \n    }	0
32950371	32950263	Convert boxed ienumerable into object array without knowing explicit type	IEnumerable enumberable = (IEnumerable)list;\n\n  List<object> values = new List<object>();\n\n  foreach (object obj in enumerable)\n  {\n      values.Add(obj);\n  }	0
14766833	14766742	How do you make two instances communicate with echotor through the same class?	class People\n{\nprivate decimal cash;\nprivate string name = "";\npublic string Name\n{\nget { return name; }\nset { name = value; }\n}\npublic decimal Cash\n{\nget { return cash; }\nset { cash = value; }\n}\n\npublic void Give(Person target, decimal amount)\n{\n  Cash -= amount;\n  target.Cash += amount;\n}\n}	0
22965316	22965224	How to TypeCast SelectMany Results	return libraries.SelectMany(lib => lib.ContainedSpaces).OfType<Room>().ToList();	0
31889740	31886515	How to timeout a constructor in C#?	System.Threading.Thread thread = new System.Threading.Thread(()=>{\n\n        using (mqQueueManager = new MQQueueManager(this._queueManager, this._properties))\n        {\n        }\n\n        });\n        thread.Start();\n        var isComplete = thread.Join(TimeSpan.FromSeconds(30));\n\n        if (!isComplete)\n        {\n            thread.Abort();\n        }	0
340554	340546	How to chose between new and override in C#?	Base b = new Derived();\nDerived d = new Derived();\nb.MyMethod(); // Calls Base.MyMethod\nd.MyMethod(); // Calls Derived.MyMethod	0
7410483	7410382	How can I write a signature on C# for a wrapped C++ method having a pointer to a function it its arguments?	[UnmanagedFunctionPointer(CallingConvention.Cdecl)]\ndelegate void AnotherMethodDelegate(string s, IntPtr anyParameter);\n\n[DllImport("dllname",\n           CallingConvention = CallingConvention.Cdecl,\n           CharSet = CharSet.Ansi)]\nuint aMethod(IntPtr anyParameter, AnotherMethodDelegate anotherMethod);	0
18904633	18904561	Programmatically convert Excel 2003 files to 2007+	public void Convert(String filesFolder)\n{\n     files = Directory.GetFiles(filesFolder);\n\n     var app = new Microsoft.Office.Interop.Excel.Application();\n     var wb = app.Workbooks.Open(file);\n     wb.SaveAs(Filename: file + "x", FileFormat: Microsoft.Office.Interop.Excel.XlFileFormat.xlOpenXMLWorkbook);\n     wb.Close();\n     app.Quit();\n}	0
8309381	8308870	Unzip one File from Directory	public static ZipEntry GetEntryExt(this ZipFile file, string fileName)\n{\n    foreach (ZipEntry entry in file)\n    {\n        if (entry.IsFile && entry.Name.EndsWith(Path.DirectorySeparatorChar + fileName))\n            return entry;\n    }\n\n    return null;\n}	0
22778620	22778178	Send file to client and delete it	private static void DownloadFile(string path)\n{\n    FileInfo file = new FileInfo(path);\n    byte[] fileConent = File.ReadAllBytes(path);\n\n    HttpContext.Current.Response.Clear();\n    HttpContext.Current.Response.AddHeader("Content-Disposition", string.Format("attachment; filename={0}", file.Name));\n    HttpContext.Current.Response.AddHeader("Content-Length", file.Length.ToString());\n    HttpContext.Current.Response.ContentType = "application/octet-stream";\n    HttpContext.Current.Response.BinaryWrite(fileConent);\n    file.Delete();\n    HttpContext.Current.Response.End();\n}	0
23941689	23941192	Asp.net culture how to set it properly	protected override void InitializeCulture()\n{\n   Thread.CurrentThread.CurrentCulture = new CultureInfo("fr-CA");\n   Thread.CurrentThread.CurrentUICulture = new CultureInfo("fr");\n   base.InitializeCulture();\n}	0
5942205	5942108	Datatype mismatch in query expression with OleDbCommand	string insertString = "UPDATE streets set TmpColumn=City & '" + zoneCH + "'& State &'" +zoneCH +"'& Zip WHERE 1"	0
3394017	3394000	parse a path in c#	Path.GetDirectoryName	0
14636969	14634706	Deserializing an array using SOAP	public void StoreCredentials(Credentials credentials)\n    {\n        credentials.Encrypt(_myUser.Encryption);\n        Hashtable credsTable;\n        var soap = new SoapFormatter();\n\n        FileStream stream;\n        try\n        {\n            stream = new FileStream(_path, FileMode.Open, FileAccess.ReadWrite);\n            credsTable = (Hashtable) soap.Deserialize(stream);\n            stream.Close();\n            stream = new FileStream(_path, FileMode.Create, FileAccess.ReadWrite);\n            if (credsTable.ContainsKey(credentials.Id))\n                credsTable[credentials.Id] = credentials;\n            else\n                credsTable.Add(credentials.Id, credentials);\n        }\n        catch (FileNotFoundException e)\n        {\n            stream = new FileStream(_path, FileMode.Create, FileAccess.ReadWrite);\n            credsTable = new Hashtable {{credentials.Id, credentials}};\n        }\n        soap.Serialize(stream, credsTable);\n        stream.Close();\n    }	0
15208469	15208243	convert string value in a text box into int using c#	string myvalue = ((TextBox)DV_Port.FindControl("txtmyvalue")).Text;\n\nif (myvalue.Equals("YES", StringComparison.OrdinalIgnoreCase))\n{\n    //Change to 1\n}\nelse if (myvalue.Equals("NO", StringComparison.OrdinalIgnoreCase))\n{\n    //Change to 0\n}\nelse\n{\n    //You should probably tell the user that their input is in an incorrect\n    //format here.\n}	0
16476650	16427445	One-to-many relationship mapping: Cannot add or update a child row: a foreign key constraint fails	public Nullable<int> companyID { get; set; }	0
8711597	8577627	ScintillaNET vs AvalonEdit for providing scripting interface for a WPF Application	private void Form1_Load(object sender, EventArgs e)\n    {\n        this.scintilla1 = new ScintillaNet.Scintilla();\n        this.scintilla1.ConfigurationManager.Language = "python";\n        this.scintilla1.Indentation.ShowGuides = true;\n        this.scintilla1.Indentation.SmartIndentType = ScintillaNet.SmartIndent.Simple;\n        this.scintilla1.Location = new System.Drawing.Point(0, 0);\n        this.scintilla1.Margins.Margin0.Width = 40;\n        this.scintilla1.Margins.Margin2.Width = 20;\n        this.scintilla1.Name = "scintilla1";\n        this.scintilla1.TabIndex = 4;\n        this.scintilla1.Whitespace.Mode = ScintillaNet.WhitespaceMode.VisibleAfterIndent;\n        this.scintilla1.Dock = DockStyle.Fill;\n        this.Controls.Add(this.scintilla1);\n    }	0
28101282	28099851	K-means with initial centers	public static List<PointCollection> DoKMeans(PointCollection points, int clusterCount, Point[] startingCentres)\n{\n    // code...\n    int ctr = 0;\n    foreach (List<Point> group in allGroups)\n    {\n        PointCollection cluster = new PointCollection();\n        cluster.c.X = startingCentres[ctr].X;\n        cluster.c.Y = startingCentres[ctr].Y;\n        cluster.AddRange(group);\n        allClusters.Add(cluster);\n    }\n    // rest of code the same\n}	0
19245877	19222517	how to set xtrapivotgrid datasource from dataset dynamically at run time	DevExpress.XtraPivotGrid.PivotGridControl pivotGrid = new DevExpress.XtraPivotGrid.PivotGridControl();\n\nControls.Add(pivotGrid);\npivotGrid.ForceInitialize();\npivotGrid.DataSource = database.Tables[0];\npivotGrid.RetrieveFields();	0
33747705	33747555	getting the array elements out in new array	public static void DviderWords() \n{\n    string str = "Alameer Ahmed Amr Ali alameer .";\n    string[] oops = str.Split(' ', ',', '!');\n    int stringCounter = oops.Length;\n    string[] holder = new string[stringCounter - 1];\n    for (int i = 0; i < stringCounter - 1; i++)\n    {\n        holder[i] = oops[i] + oops[i + 1];\n    }\n}	0
20836191	20836153	LinkLabel no underline - Compact Framework	Font f = LinkLabel1.Font; \nLinkLabel1.Font = New Font(f, f.Style && !FontStyle.Underline)	0
21382798	21382700	How to treat the list of exceptions?	IEnumerable<Exception>	0
17087002	17083233	TimeZoneCode to TimeZoneInfo	public static TimeZoneInfo GetUserTimeZone(IOrganizationService service, Guid userId)\n{\n    int timeZoneCode = 35; //default timezone to eastern just incase one doesnt exists for user\n    var userSettings = service.Retrieve(UserSettings.EntityLogicalName, userId, new ColumnSet("timezonecode")).ToEntity<UserSettings>();\n\n    if ((userSettings != null) && (userSettings.TimeZoneCode != null))\n    {\n        timeZoneCode = userSettings.TimeZoneCode.Value;\n    }\n\n    return GetTimeZone(service, timeZoneCode);\n}\n\npublic static TimeZoneInfo GetTimeZone(IOrganizationService service, int crmTimeZoneCode)\n{\n    var qe = new QueryExpression(TimeZoneDefinition.EntityLogicalName);\n    qe.ColumnSet = new ColumnSet("standardname");\n    qe.Criteria.AddCondition("timezonecode", ConditionOperator.Equal, crmTimeZoneCode);\n    return TimeZoneInfo.FindSystemTimeZoneById(service.RetrieveMultiple(qe).Entities.First().ToEntity<TimeZoneDefinition>().StandardName);\n}	0
26242264	26242056	Get url address from url file	string line = File.ReadLines(FileName).Skip(1).Take(1).First();\nstring url = line.Replace("URL=","");\nurl = url.Replace("\"","");\nurl = url.Replace("BASE","");	0
8550223	8550209	C# Reflection: How to get the type of a Nullable<int>?	if (myObject.GetType() == typeof(Nullable<Int32>))\n    // when Nullable<Int32>, do this\nelse if (myObject.GetType() == typeof(string))\n    // when string, do this\nelse if (myObject.GetType() == typeof(Nullable<bool>))\n    // when Nullable<bool>, do this	0
30588743	30588563	Getting exception when trying to delete a line from a text file. How can i solve it?	lines = File.ReadAllLines(RecentFiles);\nList< ToolStripMenuItem > items = new List< ToolStripMenuItem >();\nusing (StreamWriter writer = new StreamWriter(RecentFiles))\n{\n    for (int i = 0; i < lines.Length; i++)\n    {\n        if (File.Exists(lines[i])) {\n            writer.WriteLine(lines[i]);\n            items.Add(new ToolStripMenuItem()\n              {\n                Text = lines[i]\n              });\n        }\n    }\n}	0
25453960	25453700	Using LINQ to search between two Dates and Times	.Where(row => startTime == null || row.A_Date > startDate || (row.A_Date == startDate && row.A_Time >= startTime))	0
15677741	15677522	Referencing a cell in WPF datagrid	class SaleItem : INotifyPropertyChanged\n{\n    public int Num { get; set; }\n    public string ItemID { get; set; }\n    public string Name { get; set; }\n\n    private decimal price;\n    public decimal Price\n    {\n        get { return price; }\n        set\n        {\n            this.price = value; \n            OnPropertyChanged("Total");\n        }\n    }\n\n    private decimal quantity;\n    public decimal Quantity\n    {\n        get { return quantity; }\n        set\n        {\n            this.quantity = value; \n            OnPropertyChanged("Total");\n        }\n    }\n\n    public decimal Total\n    {\n        get { return Price * Quantity; }\n    }\n\n    public event PropertyChangedEventHandler PropertyChanged;\n    private void OnPropertyChanged(string propertyName)\n    {\n        var handler = PropertyChanged;\n        if (handler != null)\n            handler(this, new PropertyChangedEventArgs(propertyName));\n    }\n}	0
212135	212115	Method for Application Version on a Console Utility App	Assembly.GetExecutingAssembly().GetName().Version	0
239963	239951	How to determine if XElement.Elements() contains a node with a specific name?	bool hasCity = OrderXml.Elements("City").Any();	0
32096681	32096055	Generating a table from another table - MVC5	db.Patients.Add(patient);	0
26351610	26351578	Implementation of Queue using Linked List- It creates the Linked List but stops working after it prints	Node print = front;\n            while (front != null)\n            {\n                 Console.WriteLine(print.data);\n                 print = print.next;\n            }	0
4221864	4221366	Using itextsharp (or any c# pdf library), how to open a PDF, replace some text, and save it again?	public static byte[] Generate()\n{\n  var templatePath = HttpContext.Current.Server.MapPath("~/my_template.pdf");\n\n  // Based on:\n  // http://www.johnnycode.com/blog/2010/03/05/using-a-template-to-programmatically-create-pdfs-with-c-and-itextsharp/\n  var reader = new PdfReader(templatePath);\n  var outStream = new MemoryStream();\n  var stamper = new PdfStamper(reader, outStream);\n\n  var form = stamper.AcroFields;\n  var fieldKeys = form.Fields.Keys;\n\n  foreach (string fieldKey in fieldKeys)\n  {\n    if (form.GetField(fieldKey) == "MyTemplatesOriginalTextFieldA")\n      form.SetField(fieldKey, "1234");\n    if (form.GetField(fieldKey) == "MyTemplatesOriginalTextFieldB")\n      form.SetField(fieldKey, "5678");\n  }\n\n  // "Flatten" the form so it wont be editable/usable anymore  \n  stamper.FormFlattening = true;  \n\n  stamper.Close();\n  reader.Close();\n\n  return outStream.ToArray();\n}	0
32479061	32449557	Code-behind only validation rule of a textbox	Binding bindingNumberList = new Binding(businessModelObjectName);\n    bindingNumberList.Source = currentTestData;\n    bindingNumberList.Mode = BindingMode.TwoWay;\n    bindingNumberList.UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged;\n    bindingNumberList.ValidatesOnDataErrors = true;\n    GenericValidationRule gvrCheckValidImageNubers = new GenericValidationRule();\n    gvrCheckValidImageNubers.ValidationStep = ValidationStep.RawProposedValue;\n    gvrCheckValidImageNubers.WhatToCheck = "Contains Existing Image Numbers";\n    bindingNumberList.ValidationRules.Add(gvrCheckValidImageNubers);\n    tbNumberList.SetBinding(TextBox.TextProperty, bindingNumberList);	0
4648894	4648377	Outlook 2007 Addin C# - Startup Path	string path = Path.Combine(AppDomain.CurrentDomain.SetupInformation.ApplicationBase, "MyDll.dll");	0
2472027	2472003	How do I Moq It.IsAny for an array in the setup of a method?	It.IsAny<byte[]>()	0
4555742	4555725	use attribute of a method into another method	private int[] nums = null;\n\n public int merge() \n\n  {       \n      string[] source = textBox3.Text.Split(','); \n       nums = new int[source.Length];//i want to use nums in mergesort() too,how can i do that?       \n        for (int i = 0; i < source.Length; i++)    \n           { \n               nums[i] = Convert.ToInt32(source[i]);\n           }\n\n\n    }	0
24456619	24456583	Sort Only One Element Of KeyValuePair inside List<t>	entries = entries.OrderBy(kvp => kvp.Value).ToList();	0
34034450	34034195	How to select Row from Datagirdview and show in textbox?	else if (dataGridView1.Columns[e.ColumnIndex].Name == "Edit")\n{\n    Form2 form = new Form2();\n    form.textBox1.Text = ((DataGridView)sender).Rows[e.RowIndex].Cells["Text"].Value.ToString();\n    form.Show();\n    Hide();\n}	0
24451339	24447753	Is it possible to use attribute routing and convention based routing in the same controller?	[RoutePrefix("{member_id:int}/hotels")]\npublic class HotelsController : ApplicationController\n{\n    [Route("delete/{id:int}", Name = NamedRoutes.HotelDelete)]\n    public ActionResult Delete(int id)\n    {\n    }\n\n    [Route("new", Name = NamedRoutes.HotelNew)]\n    public ActionResult New()\n    {\n    }\n\n    [HttpPost]\n    [ValidateInput(false)]\n    [Route("new", Name = NamedRoutes.HotelNewPost)]\n    public ActionResult New(HotelDataEntry hotel)\n    {\n    }\n\n    [Route("edit/{id:int}", Name = NamedRoutes.HotelEdit)]\n    public ActionResult Edit(int id)\n    {\n    }\n\n    [HttpPost]\n    [ValidateInput(false)]\n    [Route("edit/{id:int}", Name = NamedRoutes.HotelEditPost)]\n    public ActionResult Edit(HotelDataEntry hotel)\n    {\n    }\n}	0
865147	865139	How do i resize a silverlight app based on its contents?	width = 200;\nheight = 200;\n\nvar host = HtmlPage.Document.HtmlPage.Plugin.Id);\nhost.SetStyleAttribute("width", width.ToString());\nhost.SetStyleAttribute("height", height.ToString());	0
18246895	18246716	Creating JSON on the fly with JObject	dynamic jsonObject = new JObject();\njsonObject.Date = DateTime.Now;\njsonObject.Album = "Me Against the world";\njsonObject.Year = 1995;\njsonObject.Artist = "2Pac";	0
17990368	17990335	How to add table in the existing database?	CREATE TABLE	0
31526115	31525963	How to Use Nested ObservableCollections to Fill Data Grid	var first = instanceObservable.First();\n\ndataGridInstance.ItemSource = first;	0
28798003	28693438	How to create class in asp.net with c#	using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Web;\nusing System.Web.UI;\nusing System.Web.UI.WebControls;\nusing System.Data;\nusing System.Data.SqlClient;\n\npublic partial class ForumPost : System.Web.UI.Page\n{\n    protected void Page_Load(object sender, EventArgs e)\n    {\n\n    }\n    protected void btnSubmit_Click(object sender, EventArgs e)\n    {\n\n\n\n        string t = "TPost";\n        string f = "PostTitle,PostQuestion";\n        string v = "@pt,@pq";\n\n        lib.insert(t, f, v);\n        lib.cmd.Parameters.AddWithValue("@pt", this.tbxTitle.Text);\n        lib.cmd.Parameters.AddWithValue("@pq", this.tbxText.Text);\n        lib.con.Open();\n        lib.cmd.ExecuteNonQuery();\n        lib.con.Close();\n\n        lblshow.Text = "submited !!!";\n\n\n    }\n}	0
3574332	3574208	how do i use the c++ dll in c#	using System.Runtime.InteropServices;\nusing System;\n\nclass call_dll {\n\n  [StructLayout(LayoutKind.Sequential, Pack=1)]\n  private struct STRUCT_DLL {\n    public Int32  count_int;\n    public IntPtr ints;\n  }\n\n  [DllImport("mingw_dll.dll")]\n  private static extern int func_dll(\n      int an_int,\n      [MarshalAs(UnmanagedType.LPArray)] byte[] string_filled_in_dll,\n      ref STRUCT_DLL s\n   );\n\n  public static void Main() {\n\n    byte[] string_filled_in_dll = new byte[21];\n\n\n    STRUCT_DLL struct_dll = new STRUCT_DLL();\n    struct_dll.count_int = 5;\n    int[]  ia = new int[5];\n    ia[0] = 2; ia[1] = 3; ia[2] = 5; ia[3] = 8; ia[4] = 13;\n\n    GCHandle gch    = GCHandle.Alloc(ia);\n    struct_dll.ints = Marshal.UnsafeAddrOfPinnedArrayElement(ia, 0);\n\n    int ret=func_dll(5,string_filled_in_dll, ref struct_dll);\n\n    Console.WriteLine("Return Value: " + ret);\n    Console.WriteLine("String filled in DLL: " + System.Text.Encoding.ASCII.GetString(string_filled_in_dll));\n\n  }\n}	0
32632557	32632396	Ignore accented letters while filtering a string in C#	if (char.IsLetterOrDigit(c) || c == '.' || c == '_') {\n    sb.Append(c);\n}	0
24800890	24800814	Will my static method return a new EF context to every object that calls it?	public static PresenceEntities GetEFContext()\n    {\n        var edmConnectionString = [connection string here]\n        return new PresenceEntities(edmConnectionString); //THIS LINE !!\n    }	0
8166932	8166757	Conversion of byte array containing hex values to decimal values	if (BitConverter.IsLittleEndian)\n    Array.Reverse(array); //need the bytes in the reverse order\nint value = BitConverter.ToInt32(array, 0);	0
14436700	14436325	Create a new method at run-time	System.Reflection.Emit.DynamicMethod	0
24904379	24904149	C# XML serialization - Change array item name	public class JobStatusListTask : IXmlSerializable\n{\n    public JobListSettings ListSettings;\n\n    public List<JobFilterCriteria> Filters;\n\n    public JobStatusListTask()\n    {\n        Filters = new List<JobFilterCriteria>();\n        Filters.Add(new JobFilterCriteria("STATUS", CriteriaOperator.Equal, "ERROR"));\n    }\n\n\n    public JobStatusListTask(JobListSettings settings) : this()\n    {\n        ListSettings = settings;\n    }\n\n    public void WriteXml(XmlWriter writer)\n    {\n        writer.WriteStartElement("Filters");\n        foreach(var item in Filters)\n        {\n            writer.WriteStartElement("Criteria", string.Format("Criteria_{0}", Count++));\n            writer.WriteAttributeString("Parameter", Parameter);\n            writer.WriteAttributeString("Operator", Operator.ToString());\n            writer.WriteAttributeString("Value", Value);\n        }\n        writer.WriteEndElement();\n    }\n\n}	0
28048087	28047846	returning multiple class model data from linq in list via return method in C#	var processedCourseInstance = (from _courseInstances in _uof.CourseInstances_Repository.GetAll()\n                                             join _courses in _uof.Courses_Repository.GetAll() on _courseInstances.CourseID equals _courses.CourseID \n                                             join _studylevel in _uof.StudyLevel_Repository.GetAll() on _courses.StudyLevelId equals _studylevel.StudyLevelID\n                                             orderby _courseInstances.CourseCode\n                                             select new CoursesInstanceStudyLevel_ViewModel(){\n     _CourseInstanceModel  = _courseInstances.FirstOrDefault(),\n     StudyLevelModel  = _studylevel.FirstOrDefault()}).ToList();	0
8851306	8851155	finding difference between two dictionaries	var diff = dicOne.Except(dicTwo).Concat(dicTwo.Except(dicOne));	0
2755428	2755398	Convert a byte array to a class containing a byte array in C#	[StructLayout(LayoutKind.Sequential)]\npublic struct PacketFormat\n{\n  public byte header;\n  [MarshalAs(UnmanagedType.ByValArray, SizeConst = 256)] public byte[] data;\n}	0
11197990	11197852	how to get reference from property info in c#	else if (currentNodeType != typeof (object) && Type.GetTypeCode(currentNodeType) == TypeCode.Object)\n            {\n                object propVal = p.GetValue(objToRip,null);\n\n                if(propVal != null) ProcessAllStrings(ref propVal);\n            }	0
33115648	33110521	When I run a script which is attached to my canvas to pop up a pause menu it only runs once	GetComponent< PauseMenu >().enabled = false;	0
8013607	8012726	How to send a HTML Email from a asp.net Website	string BODY = String.Empty;\nstring PageName = "[Path to resource]"; //example C:\DataSource\Website\DomainName\RousourceFolder\page.html\n\nBODY = new StreamReader(PageName).ReadToEnd();	0
22972325	22972024	Search for a Item in ListView and get its properties	ListViewItem lvi = listView1.FindItemWithText("searchMe");\nstring s = "";\nforeach (ListViewItem lvsi in lvi.SubItems) s += lvsi.Text + " ";	0
246529	246498	Creating a DateTime in a specific Time Zone in c# fx 3.5	public struct DateTimeWithZone\n{\n    private readonly DateTime utcDateTime;\n    private readonly TimeZoneInfo timeZone;\n\n    public DateTimeWithZone(DateTime dateTime, TimeZoneInfo timeZone)\n    {\n        utcDateTime = TimeZoneInfo.ConvertTimeToUtc(dateTime, timeZone); \n        this.timeZone = timeZone;\n    }\n\n    public DateTime UniversalTime { get { return utcDateTime; } }\n\n    public TimeZoneInfo TimeZone { get { return timeZone; } }\n\n    public DateTime LocalTime\n    { \n        get \n        { \n            return TimeZoneInfo.ConvertTime(utcDateTime, timeZone); \n        }\n    }        \n}	0
20256303	20256277	How to use the DataRow to get the colunms name?	foreach (DataColumn c in DR[0].Table.Columns) \n{\n    MessageBox.Show(c.ColumnName);\n}	0
12051618	12051525	how to hide .net app from process list	GetLastInputInfo()	0
4541066	4541050	Creating new sql server table with c#	"CONSTRAINT ['pk_" + TName + "'] PRIMARY KEY CLUSTERED "	0
4924122	4923231	Getting results from Parallel.For	public IEnumerable<HotelAvail> GetAvailability (IList<string> codes, \n                                                    DateTime startDate, \n                                                    int numNights)\n    {\n        return codes.AsParallel().AsOrdered().Select(code => \n                 new AvailService().GetAvailability(code, startDate, numNights))\n                .ToList();\n    }	0
7269267	7268736	filtering values from string after/before certain word in c#	string myString = "* FLAGS (\\Answered \\Flagged \\Draft \\Deleted \\Seen)\r\n* OK [PERMANENTFLAGS ()] Flags permitted.\r\n* OK [UIDVALIDITY 657136382] UIDs valid.\r\n* 3 EXISTS\r\n* 0 RECENT\r\n* OK [UIDNEXT 4] Predicted next UID.\r\n. OK [READ-ONLY] INBOX selected. (Success)\r\n";\n\nstring myWordToFind = "EXISTS";\n\nstring result = Regex.Match(myString, @"(?<MyNumber>\d+)\s*(" + Regex.Escape(myWordToFind) + ")",\n    RegexOptions.Compiled | RegexOptions.IgnoreCase)\n    .Groups["MyNumber"].Value;	0
31954492	31951008	Can one use the Source property of a MediaElement to play content?	private async void Button_Click(object sender, RoutedEventArgs e)\n{\n    StorageFolder musicLib = Windows.Storage.KnownFolders.MusicLibrary;\n    StorageFile song = await musicLib.GetFileAsync(@"Artist\Album\Song.mp3");\n    var stream = await song.OpenReadAsync();\n    me.SetSource(stream, stream.ContentType);\n}	0
10932089	10931786	Holding event for Button in C# for Win 8 Metro App	if (e.HoldingState == Windows.UI.Input.HoldingState.Started)	0
25773138	25772895	How to change the color for entire GridView row	if (DateTime.Parse(e.Row.Cells[5].Text).Date < DateTime.Now.Date)\n{\n   e.Row.ForeColor = Color.FromName("#C00000");\n   e.Row.ToolTip = "Task is Past Due";\n}	0
22655506	22655333	Register new pageasynctask with async Task method that takes parameters	protected void Page_Load(object sender, EventArgs e)\n    {\n        RegisterAsyncTask(new PageAsyncTask(() => SomeMethod(accID: 1000)));\n\n       // etc\n}	0
7095788	7095612	How do I bind a field to a control in WinForms?	Person person1 = new Person();\nperson1.Name = "Odys";\ntextbox.DataBindings.Add("Text", person1, "Name");	0
33933103	33932550	Pass Parameters to SQL Triggers via asp.net	CREATE TRIGGER tg_Employees_RegisterAdminOnly ON dbo.Employees\nAFTER INSERT AS\nBEGIN\n    IF EXISTS (SELECT * FROM INSERTED WHERE CreateBy <> 1110) BEGIN\n        RAISERROR('Unauthorized registration', 16, 1)\n        ROLLBACK\n        RETURN\n    END\nEND\nGO	0
33560250	33553613	How to unsubscribe from subscription when webrole is deleting by autoscaling?	public class WebRole : RoleEntryPoint\n{\n    public override bool OnStart()\n    {\n        // For information on handling configuration changes\n        // see the MSDN topic at http://go.microsoft.com/fwlink/?LinkId=166357.\n\n        RoleEnvironment.Stopping += (sender, args) =>\n            {\n                messagesListener.Stop(true);\n                Logger.LogInfo("Website is stopping. InstanceNo = " + instanceNo);\n            };\n\n        return base.OnStart();\n    }\n\n    public override void OnStop()\n    {\n        // you can also put stuff here to test\n        base.OnStop();\n    }\n}	0
18012161	18010776	Databind a gridview on another page	GridView grv = ((GridView)this.Page.PreviousPage.FindControl("gridview1"));	0
32793029	32792965	Sort a list using a search string	var items = listEmployee\n    .OrderByDescending(e => e.Name.Equals(searchString))\n    .ThenBy(e => e.ID).ToArray();	0
21749362	21742199	Deserializing XML from HttpWebResponse GetResponseStream with different types	XmlSerializer.CanDeserialize	0
2160957	2160923	C#: How can I get the icon for a certain file?	public System.Windows.Media.ImageSource Icon\n{\n    get\n    {\n        if (icon == null && System.IO.File.Exists(Command))\n        {\n            using (System.Drawing.Icon sysicon = System.Drawing.Icon.ExtractAssociatedIcon(Command))\n            {\n                // This new call in WPF finally allows us to read/display 32bit Windows file icons!\n                icon = System.Windows.Interop.Imaging.CreateBitmapSourceFromHIcon(\n                  sysicon.Handle,\n                  System.Windows.Int32Rect.Empty,\n                  System.Windows.Media.Imaging.BitmapSizeOptions.FromEmptyOptions());\n            }\n        }\n\n        return icon;\n    }\n}	0
17025770	17025253	Uploading to a specific folder to Skydrive	LiveAuthClient authClient = new LiveAuthClient();\nLiveLoginResult authResult = await authClient.LoginAsync(new List<string>() { "wl.basic", "wl.skydrive", "wl.skydrive_update" });\ntry\n{\n    var folderData = new Dictionary<string, object>();\n    folderData.Add("name", "Test Folder");\n    LiveConnectClient liveClient = new LiveConnectClient(authResult.Session);\n    LiveOperationResult operationResult =\n        await liveClient.PostAsync("me/skydrive", folderData);\n    dynamic result = operationResult.Result;\n    var folderId = result.id;\n\n    /*result is dynamic object, you can get the folder id with id property \n    operationResult.RawResult will return JSON response with some data related to \n    that folder */\n}\ncatch (LiveConnectException exception)\n{\n}	0
22336166	22334574	Calling Static Methods with Data Contexts in LINQPad	void Main()\n    {\n        tName.test.DoIt(); // Fully qualify the static method name\n    }\n\n} // Close the generated context's class\n\nnamespace tName\n{\n    public class test\n    {\n    // Define other methods and classes here\n        public static void DoIt()\n        {\n            Console.WriteLine("Done");\n        }\n    }\n// } Don't close the namespace. Let LinqPad do it.	0
32125714	32125619	Invoke an instance method from a expression	Expression<Action<MyClass>> expr = x => x.SomeMethod("Nathan", 10, 1.5d); \nAction<MyClass> action = expr.Compile();\n\nMyClass instance = new MyClass();\naction(instance);	0
15828951	15828446	How to mirror a Matrix3D?	var cameraTrans = sceneCamera.TransformationMatrix;\ncameraTrans.Scale(new Vector3D(-1, 1, 1));	0
692944	691980	How do I save an entity for the first time that requires another pre-existing entity to be attached to it	Company company = new Company();\ncompany.CreateDate = DateTime.Now;\ncompany.UpdateDate = DateTime.Now;\ncompany.CompanyType = companyType;\nRanchBuddyEntities.AddToCompanies(company);\nRanchBuddyEntities.SaveChanges();	0
8079119	8079047	In WPF is there a way to determine if another control captures the mouse?	public partial class MainWindow : Window {\n    public MainWindow() {\n        InitializeComponent();\n    }\n    static MainWindow() {\n        EventManager.RegisterClassHandler(typeof(UIElement), Mouse.GotMouseCaptureEvent, new MouseEventHandler(MainWindow_GotMouseCapture));\n    }\n    static void MainWindow_GotMouseCapture(object sender, MouseEventArgs e) {\n        // e.OriginalSource is a captured element\n    }\n}	0
26999252	26993276	How To Pass Value To Previous ViewContoller	((Controller)NavigationController.ViewControllers[0]).myVariable = 3;	0
1587831	1587809	How to open another form in codebehind using javascript	String s = "Contact.aspx";\n            Response.Write("<script type='text/javascript'>window.open('"+s+"')</script>");	0
21349361	21349281	Displaying data for logged user	[Authorize]\npublic ActionResult Index()\n{\n    string loggedUser = User.Identity.Name;\n    var model = db.AdresModel.Where(x => x.User.UserName == loggedUser).ToList();\n    return View(model);\n}	0
7710888	7023869	How to combine inner join and left join in Entity Framework	Data = m.Data ?? [default value]	0
21258456	21257251	convert int to string in linq for searching	var pop = ctx\n    .PurchaseOrders\n    .OrderBy(x => x.PurchaseOrderID)\n    .ToList()\n    .Select(x => new SearchItem()\n    {\n        id = x.PurchaseOrderID.ToString(),\n        label = x.SupplierID,\n        category = "purchaseorder"\n    });	0
25889351	25889205	How to call a Controller method which is accepting two models?	// You don't need [FromBody] since complex types are already taken\n// from the request body\npublic IHttpActionResult DoStuff(SomeDto dto)	0
27747613	27746855	Calling an action of another controller and getting view as a string	protected string RenderViewToString(string viewName, object model = null)\n{\n  ViewData.Model = model;\n  using(StringWriter sw = new StringWriter())\n  {\n    ViewEngineResult viewResult = ViewEngines.Engines.FindView(ControllerContext, viewName, null);\n    ViewContext viewContext = new ViewContext(ControllerContext, viewResult.View, ViewData, TempData, sw);\n    viewResult.View.Render(viewContext, sw);\n\n    return sw.GetStringBuilder().ToString();\n  }\n}\n\nprotected string RenderPartialViewToString(string viewName, object model = null)\n{\n  ViewData.Model = model;\n  using(StringWriter sw = new StringWriter())\n  {\n    ViewEngineResult viewResult = ViewEngines.Engines.FindPartialView(ControllerContext, viewName);\n    ViewContext viewContext = new ViewContext(ControllerContext, viewResult.View, ViewData, TempData, sw);\n    viewResult.View.Render(viewContext, sw);\n\n    return sw.GetStringBuilder().ToString();\n  }\n}	0
22941907	22938062	can an nhibernate transaction flush only changes committed to session?	ISession.Evict	0
29755449	29755324	Binary Reading of Bytes Returning only One Value. C#	public static void WriteDefaultValues()\n    {\n        using (BinaryWriter writer = new BinaryWriter(File.Open(FileName, FileMode.Create)))\n        {\n            writer.Write((byte)0);\n            writer.Write((byte)1);\n            writer.Write((byte)2);\n            writer.Write((byte)3);\n        }\n    }	0
4367694	4367663	How can I add a node to the selected node in a TreeView?	TreeNode node = treeView.SelectedNode;\nnode.Nodes.Add(new TreeNode());	0
4013593	4013549	How to change the colour of a databound html item at runtime?	Style="color:<%# DataAdapter.Enabled ? 'green' : 'red' %>"	0
17243904	17243793	How can convert a hex string into a string whose ASCII values have the same value in C#?	string command = "AA";\nint num = int.Parse(command,NumberStyles.HexNumber);\nstring bits = Convert.ToString(num,2); // <-- 10101010	0
2153691	2153472	Duplicate range in Excel via C#	// First copy paste with static range values\nRange destination = yourWorksheet.get_range("A10",Type.Missing)\nyourWorksheet.get_range("A5", "I9").Copy(destination);	0
1271142	1271122	How to get ShowState of a window in c# or c++?	WINDOWPLACEMENT wp;\nGetWindowPlacement( hWnd, &wp );\n\nUINT showCmd = wp.showCmd;	0
32975139	32971977	How to pass query string parameter to asp.net web api 2	public IHttpActionResult GetCustomer([FromUri]CustomerRequest request, long id = 0)	0
5111673	5098793	Gridview column and row total	protected void gridview1_onrowdatabound(Object sender, GridViewRowEventArgs e)\n{\n // Check if it's a header row\n  if (e.Row.RowType == DataControlRowType.Header) \n   {\n      e.Row.Cells.add("Total"); //add a header Col\n    }\n\n     int count = 0;\n\n     if(e.Row.RowType == DataControlRowType.DataRow)\n        {\n            count = count + Convert.ToInt32(e.Row.Cells[0].value)+cell1 value+cell2 value;\n          e.Row.Cells.add(count.tostring());\n         }\n     }	0
11363978	11363951	How can I find a word in a C# string	var html = "<html><head></head><body><h1>hello</h1></body></html>";\n\nHtmlDocument d = new HtmlDocument();\nd.LoadHtml(html);\n\nvar h1Contents = d.DocumentNode.SelectSingleNode("//h1").InnerText;	0
14224862	14224784	How to download multiple files using asp and c#	window.open("download.aspx?id=id of file1");\nwindow.open("download.aspx?id=id of file2");	0
11464353	11464278	How to convert a Base64 PNG image string to PNG Format in C#	byte[] data = Convert.FromBase64String(base64String);\nusing(var stream = new MemoryStream(data, 0, data.Length))\n{\n  Image image = Image.FromStream(stream);\n  //TODO: do something with image\n}	0
22412122	22412022	No value given for one or more required parameters while trying to add a record	"INSERT INTO Words (Word) VALUES(?)"	0
2603772	2603733	How to Access a descendant object's internal method in C#	[assembly:InternalsVisibleTo("SomeOtherAssembly")]	0
28310920	28202699	MassTransit, RabbitMQ - FIFO dequeue support	x.ReceiveFrom(uri) // uri should be unique per bus instance	0
859950	859844	How to catch exceptions on another thread without affecting the debugger	#if (DEBUG)\nreceivingSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout, 0);\n#endif	0
12796896	12796524	Regular expression for matching date	string Date = "December 8"\n\n  MatchCollection MC = Regex.Matches(Date, @"(?i)([\d]{1,2}(\s)?(January|Jan|February|feb|March|mar|April|Apr|May|June|July|August|Aug|September|Sep|October|Oct|November|Nov|December|Dec))|(January|Jan|February|feb|March|mar|April|Apr|May|June|July|August|Aug|September|Sep|October|Oct|November|Nov|December|Dec)(\s)?[\d]{1,2}");	0
27094778	27094734	How to make a form stay above another	protected void SetZOrder(IntPtr bottom, IntPtr top) {\n    const int flags = 0x0002 | 0x0001; \n    NativeMethods.SetWindowPos(bottom, top, 0, 0, 0, 0, flags);\n}	0
15244054	15242921	WPF: Display PDF File using WebBrowser	string GuidePath = @"./Resources/Guide/LogViwer User Manual.pdf";	0
15882177	15882106	get only 3 words of a String in C#	string result = string.Join(" ", str.Split().Take(3));	0
22627521	22223346	retrieve data to textboxt using LINQ to SQL	{\n            Response.Write(q.ToString()); // "q" will have your database record\n        }	0
17892953	17892892	how do I combine objects in order to display all at the same time as JSON?	public List<Node> getNotifications(int id)\n{\n    var bucket = new List<Node>(notificationTreeNodes.Count);\n\n    foreach (var notificationTreeNode in notificationTreeNodes)\n    {\n        Node nd = new Node();\n        ...\n\n        bucket.Add(nd);\n    }\n\n    return bucket;\n}	0
34001404	34001096	Copy a table from Database1 to Database2	public static void TransportTable(string sourceDbPath , string targetDbPath, List<string> lstTables)\n    {\n        string constr = ("Provider=Microsoft.JET.OLEDB.4.0;data source=" + targetDbPath + ";Persist Security Info=False;");\n        var conn = new OleDbConnection(constr);\n        var yescommander = new OleDbCommand();\n        conn.Open();\n        lstTables.ForEach(delegate(String tableName)\n        {\n            yescommander.CommandType = CommandType.Text;\n            yescommander.Connection = conn;\n            yescommander.CommandText = "SELECT f.* INTO " + tableName + " FROM " + tableName + " AS f IN '" + sourceDbPath + "';";\n            int result = yescommander.ExecuteNonQuery();\n        });\n        conn.Close();\n    }	0
12735168	12605701	How to prevent selection order influencing which row comes first in a DataGridView?	var orderedRows = dataGridView.SelectedRows.Cast<DataGridViewRow>().OrderBy(row => row.Index);	0
23534307	23534132	How do I checkbox.Checked using a variable of type "Control"?	CheckBox checkbox1 = FindControl(foo) as CheckBox;\nif(checkbox1!=null)\n{\n    if (checkbox1.Checked)\n    {\n         //write your code here\n    }\n }	0
25716913	25715447	How to update file name in filewatcher	FileInfo file = new FileInfo(e.FullPath);\n    Console.WriteLine(file.Name);	0
6591644	6591583	Appending and Prepending '#' in an string using only Regex	var res = Regex.Replace(input, @"^(.*)$", "#$1#");	0
6277160	6277100	Problem with getting a cell value OnRowCommand in Gridview	k = row.Cells[0].Text;	0
15724269	15722561	C# Load a .NET assembly from memory with parameters	Assembly program = Assembly.Load(ASSEMBLY_BYTES);\n\nstring[] args = new string[] { "-s" };\n\nprogram.EntryPoint.Invoke(null, new object[] { args });	0
4907695	4907631	How can I allow a method to accept either a string or int?	void MyMethod<T>(T param)\n{\n    if (typeof(T) == typeof(int))\n    {\n        // the object is an int\n    }\n    else if (typeof(T) == typeof(string))\n    {\n        // the object is a string\n    }\n}	0
28709323	28709265	C# How can I read a MultiString from the registry	string sep = ",";\nstring result = String.Join(sep, stringArr);	0
7011600	7011236	Format C# Double to Scientfic Notation in powers with multiples of three	static string Scientific3(double value, int precision)\n{\n    string fstr1 = "{0:E" + (precision+2).ToString() + "}";\n    string step1 = string.Format(fstr1, value);\n    int index1 = step1.ToLower().IndexOf('e');\n    if (index1 < 0 || index1 == step1.Length - 1)\n        throw new Exception();\n    decimal coeff = Convert.ToDecimal(step1.Substring(0, index1));\n    int index = Convert.ToInt32(step1.Substring(index1 + 1));\n    while(index%3!=0)\n    {\n        index--;\n        coeff *= 10;\n    }\n    string fstr2 = "{0:F" + precision.ToString() + "}E{1}{2:D3}";\n    return string.Format(fstr2, coeff, ((index < 0) ? "-" : "+"), Math.Abs(index));\n}	0
7365454	7365377	Building a generic filter parameter inputs interface?	public abstract class BaseFilter\n{\n    public string SortBy { get; set; }\n    public bool SortAscending { get; set; }\n    public int RowStart { get; set; }\n    public int RowCount { get; set; }\n}\n\npublic class BookFilter : BaseFilter\n{\n    public string ISBN { get; set; }\n    public int Year { get; set; }\n}\n\npublic class AuthorFilter : BaseFilter\n{\n    public string Name { get; set; }\n}	0
26916970	26916840	C# How to pause program	await Task.Delay(1000)	0
22989074	22988940	How to access DB in asp.net on this scenario?	public void SomeMethodWhichConnectsToDB()\n{\n    using (var connection = new SqlConnection())\n        using (var command = new SqlCommand())\n        {\n            // do something with the connection, execute the command, etc\n        }\n}	0
30621332	30619790	Finding timer in program process C#	uint oddTimer = 1509949440;\ndouble trueTimer = (oddTimer / 256^3) * 0.1;\nreturn (uint)Math.Ceiling((double)trueTimer);	0
881540	881512	Change application icon after app launched	this.Icon = new Icon(@"<path to icon on disk");	0
4056690	4056327	How do I copy an object with NHibernate	public void CloneStudent(Guid studentId)\n    {\n        // Get existing student\n        Student student = _session.Get<Student>(studentId);\n\n        // Copy by reference\n        Student newStudent = student;\n\n        // Reset Id to do quick and dirty clone\n        newStudent.Id = Guid.NewGuid();\n        newStudent.Sticker = "D";\n\n        // Must evict existing object or Nhibernate will throw object modified error\n        _session.Evict(student);\n\n        // Save new object\n        _session.Save(newStudent);\n        _session.Flush();\n\n\n    }	0
20097886	20095424	Extract Data Annotations in custom ModelBinder	foreach (PropertyInfo prop in Model.GetType().GetProperties())\n{\n    var annotations = prop.GetCustomAttributes(typeof(ValidationAttribute), false);\n    foreach(var annotation in annotations)\n    {\n        if(annotation is RequiredAttribute)\n        {\n            //...\n        }\n    }\n}	0
15956896	15956742	Iterate through N points that are perpendicular to another line	float perp_dx = -dy / Math.sqrt(dy*dy+dx*dx); //normalized\nfloat perp_dy = dx /Math.sqrt(dy*dy+dx*dx); //normalized\n\nfor(int i =0; /*logic here*/){\n float new_x = perp_dx * i + start_x;\n float new_y = perp_dy * i + start_y;\n}	0
11870116	11868494	parse data sent by webapi. is IEnumerable a good choice?	var json = "[\"value1\",\"value2\"]";\nvar values = JsonConvert.DeserializeObject<string[]>(json);	0
12211082	12211013	delete a part from the request.rawurl on a button server side click	string oldUrl = "http://localhost:51854/SupportWebsite/Dashboard.aspx?FromForum=T";\nUri uri = new Uri(oldUrl);\nstring newUrl = uri.GetLeftPart(UriPartial.Path);	0
5179286	5179244	How can I use datetime in for loop?	DateTime start = ...;\nDateTime finish = ...;\n\nfor (DateTime x = start; x <= finish; x = x.AddDays(1))\n{\n   ... // use x\n}	0
2500383	2500257	How do I get XML path by its value?	using System;\nusing System.Xml;\nusing System.Xml.Linq;\nusing System.Xml.XPath;\n\nclass Program\n{\n    static void Main()\n    {\n        var doc = XDocument.Load("test.xml");\n        var ns = new XmlNamespaceManager(new NameTable());\n        ns.AddNamespace("ns", "http://www.epo.org/exchange");\n        var elem = XDocument.Load("test.xml")\n            .XPathSelectElement("//ns:document-id[ns:doc-number='1000']", ns);\n        if (elem != null)\n        {\n            Console.WriteLine(elem.ToString());\n        }\n    }\n}	0
22325736	22300863	Split text message in datagridview columns	if (txt.Length > 1 && txt[1] != null)\n    {\n        addRow.Cells[2].Value = txt[1];\n    }	0
25787065	25786714	Setting BorderBrush of Button with a custom template and triggers	BorderThickness="{TemplateBinding BorderThickness}"	0
5750682	5750650	picking up information server side with redirected pages	Request.Form	0
9488134	9487996	Create multiple instances of the same control with different visual properties via code-behind in WPF	//get mainwindow\nWindow main = App.Current.MainWindow;\nmyControl c1 = new myControl();\n//change properties\nmyControl c2 = new myControl();\n//change properties\n\n//choose a container you want\nStackPanel s = new StackPanel();\n\n//add objects to container\ns.Children.Add(c1);\ns.Children.Add(c2);\n\n//make container as your main content\nmain.Content = s;	0
3377858	3377721	How to get control's property value from string in asp.net	static string getPropertyValueFromProperty(object control, string propertyName)\n    {\n        var controlType = control.GetType();\n        var property = controlType.GetProperty(propertyName, BindingFlags.Static | BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);\n        if (property == null)\n            throw new InvalidOperationException(string.Format("Property ?{0}? does not exist in type ?{1}?.", propertyName, controlType.FullName));\n        if (property.PropertyType != typeof(string))\n            throw new InvalidOperationException(string.Format("Property ?{0}? in type ?{1}? does not have the type ?string?.", propertyName, controlType.FullName));\n        return (string) property.GetValue(control, null);\n    }	0
14782072	14781970	How can I query a db using linq to get related rows with a single call?	var t3Rows = dataContext.T3.Where(x => x.T2.T1.Id == id);	0
3126903	3126886	How to declare generic event for generic delegate in c#	class Foo<T> { public event SomeEventType<T> SomeEventName; }	0
23336081	23334787	Multiple Textbox in a window WPF C#	private void StartKeyBoardProcess(Textbox tb) {\n    try {\n      if (tb != null) {\n          Process.Start("osk.exe", "/C");\n          tb.Focus();\n        }\n    }\n    catch (Exception ex) {\n      Messagebox.Show("Error: StartKeyBoardProcess: "+ex);\n    }\n  }\n\n private void TextBox_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)\n {\n   Textbox tb = sender as Textbox;\n   StartKeyBoardProcess(tb);\n }	0
31881614	31881525	C# - I'd like to create folders specified in textbox by the user. How is it possible to make sure that comma will work as the seperator?	string[] strArr = customersBOX.Text.Split(',');\nforeach (string item in strArr)\n{\n    item.Trim();\n    System.IO.Directory.CreateDirectory(foldercreationPATH.Text + "\\Tosystem\\" + item);            \n}	0
18656909	18656733	how to bind ASP.Net DropDownList control in EditItemTemplate of GridView on edit(imagebutton)click	protected void gv_RowDataBound(object sender, GridViewEditEventArgs e)\n    {\n     if (e.Row.RowType == DataControlRowType.DataRow)\n      {\n            if ((e.Row.RowState & DataControlRowState.Edit) > 0)\n            {\n              DropDownList ddList= (DropDownList)e.Row.FindControl("DStatusEdit");\n              //bind dropdownlist\n              DataTable dt = con.GetData("select distinct status from directory");\n              ddList.DataSource = dt;\n              ddList.DataTextField = "YourCOLName";\n              ddList.DataValueField = "YourCOLName";\n              ddList.DataBind();\n\n              DataRowView dr = e.Row.DataItem as DataRowView;\n              //ddList.SelectedItem.Text = dr["YourCOLName"].ToString();\n              ddList.SelectedValue = dr["YourCOLName"].ToString();\n            }\n       }\n    }	0
25640052	25639972	Stop windows service if running before run again from installer c#	using (ServiceController sc = new ServiceController(serviceInstaller1.ServiceName))\n{    \n   if  ((sc.Status.Equals(ServiceControllerStatus.Stopped)) ||\n     (sc.Status.Equals(ServiceControllerStatus.StopPending)))\n   {\n   // Your code when service stopped\n   }  \n}	0
11410109	11409658	Why do we declare a private parameterless constructor every time	var product = new Product{Name = "Some Name", Price = 10.0};	0
26220784	26220751	Setting cookie using javascript and reading it on server side	string cookieValue = string.Empty;\n\nif (Request.Cookies["province"] != null)\n{\n    cookieValue = Request.Cookies["province"].Value.ToString();\n}	0
9869866	7922844	Fill SQL Server table with test data	--Declare variables\n\nDECLARE @NoOfRows INT, @StartVal INT, @EndVal INT, @Range INT\n\n--Preset the variables\n\n SELECT @NoOfRows = 10000, @StartVal = 10, @EndVal = 20, @Range = @EndVal - @StartVal + 1\n\n--Create the test table with "random values" integers and floats\n\nSELECT TOP (@NoOfRows) \nSomeRandomInteger =  ABS(CHECKSUM(NEWID())) % @Range + @StartVal, \nSomeRandomFloat = RAND(CHECKSUM(NEWID())) * @Range + @StartVal\n\nINTO #TempTable\n\nFROM sys.all_columns ac1\nCROSS JOIN sys.all_columns ac2\n\nSELECT * FROM #TempTable	0
33827450	33827395	C# - Avoid Delay at Button Press/Spam	bool isAKeyDown = false;\nprivate void key_Down(object sender, KeyEventArgs e)\n{\n    if (e.KeyCode == Key.A && !isAKeyDown )\n    {\n        isAKeyDown = true;\n        // Do Stuff\n    }\n}\nprivate void key_Up(object sender, KeyEventArgs e)\n{\n    if (e.KeyCode == Key.A)\n    {\n        isAKeyDown = false;\n    }\n}	0
12027534	12027496	Downloading Multiple Files From the Items in Listbox	foreach (var item in listDownloadXML.Items)\n{\n    //... your code to download "item".\n}	0
9423889	9423565	How do I take a bitmap image and save as a JPEG image file on a Windows Phone 7 device?	var bmp = new WriteableBitmap(bitmapImage);\nusing (IsolatedStorageFile storage = IsolatedStorageFile.GetUserStoreForApplication())\n    {\n        using (IsolatedStorageFileStream stream = storage.CreateFile(@"MyFolder\file.jpg"))\n        {\n            bmp.SaveJpeg(stream, 200, 100, 0, 95);\n            stream.Close();\n        }\n    }	0
12879501	12879397	Find closest number to a given number using a list of integers	public static int FindClosest(int given_number, int[] list_of_integers) {\n\n    // Start min_delta with first element because it's safer\n    int min_index = 0;\n    int min_delta = list_of_integers[0] - given_number;\n    // Take absolute value of the min_delta\n    if ( min_delta < 0 ) {\n        min_delta = min_delta * ( -1 );\n    }\n\n    // Iterate through the list of integers to find the minimal delta\n    // Skip first element because min_delta is set with first element's\n    for ( int index = 1; index < list_of_integers.size(); index++ ) {\n        cur_delta = list_of_integers[index] - given_number;\n        // Take absolute value of the current delta\n        if ( cur_delta < 0 ) {\n            cur_delta = cur_delta * ( -1 );\n        }\n\n        // Update the minimum delta and save the index\n        if ( cur_delta < min_delta ) {\n            min_delta = cur_delta;\n            min_index = cur_index;\n        }\n    }\n    return list_of_integers[min_index];\n}	0
19380470	19380352	HttpClient failing in accessing simple website	internal static async Task<bool> ValidateUrl(string url)\n{\n  Uri validUri;\n  if(Uri.TryCreate(url,UriKind.Absolute,out validUri))\n  {\n    var client = new HttpClient();\n\n    var response = await client.GetAsync(validUri, HttpCompletionOption.ResponseHeadersRead);\n    return response.IsSuccessStatusCode;\n  }\n\n  return false;\n }	0
68681	68640	Can you have a class in a struct?	using System;\n\nnamespace ConsoleApplication1\n{\n    class Program\n    {\n        static void Main(string[] args)\n        {\n            MyStr m = new MyStr();\n            m.Foo();\n\n            MyStr.MyStrInner mi = new MyStr.MyStrInner();\n            mi.Bar();\n\n            Console.ReadLine();\n        }\n    }\n\n    public class Myclass\n    {\n        public int a;\n    }\n\n    struct MyStr\n    {\n        Myclass mc;\n\n        public void Foo()\n        {\n            mc = new Myclass();\n            mc.a = 1;\n        }\n\n        public class MyStrInner\n        {\n            string x = "abc";\n\n            public string Bar()\n            {\n                return x;\n            }\n        }\n    }\n}	0
4361975	4361963	insert into database	SqlCeCommand cmd = new SqlCeCommand("INSERT INTO [Employee Table] VALUES (" +\n    "'" + first + "',"	0
9943024	9942980	How to get the path of a file which is in file upload control in asp.net	FileUploadControl.FileName	0
7413287	7399226	How to open Windows Certificate Viewer (not Manager)	X509Certificate2UI.DisplayCertificate(cert);	0
6997752	6997632	Return muliple selectlist with one actionresult	// new class in your project\npublic class SelectListModel\n{\n    public SelectList SL1 { get; set; }\n    public SelectList SL2 { get; set; }\n}\n\n\n// updated version of your ActionResult    \npublic ActionResult IndexStudents(Docent docent, int lessonid, int classid)\n{\n    var myslm = new SelectListModel \n    {\n        SL1 = new SelectList(docent.ReturnStudentsNormalAsString(lessonid, classid),\n        SL2 = new SelectList(docent.ReturnStudentsNoClassAsString(lessonid, classid)\n    };\n    return View(myslm);\n}\n\n\n// updated view code\n<div class="editor-field">\n    <%: Html.DropDownList("IndexStudentsNormal", Model.SL1 as SelectList) %>  \n</div>\n<div class="editor-field">\n    <%: Html.DropDownList("IndexStudentsNoClass", Model.SL2 as SelectList) %>\n</div>	0
1822187	1822138	parsing application/atom+xml in html page	//link[@type='application/rss+xml']/@href	0
28420306	28420154	Find largest (int) value in the (string) column with LINQ	List<String> column = new List<string>()\n        {\n            "12", "abc", "99", "!", "654"\n        };\n\n        var data = column.Where(x =>\n        {\n            decimal temp;\n            return decimal.TryParse(x, out temp);\n        }).Max(x => Convert.ToDecimal(x));\n        data++;	0
7841688	7841602	How do I use LINQ to parse XML with child elements of the same name?	XElement ele = loaded.Element("messages");    \ndtos = from item in ele.Descendants("message")\n    select new DTO() {title = item.Element(title).value ,... };	0
13780373	13780306	Statement not firing after a `foreach` within a `using` block	StringBuilder bitString = new StringBuilder("0");\n        depthFrame.CopyPixelDataTo(bits);\n        foreach (var bit in bits)\n        {\n            sb.Append(bit.ToString();\n        }\n        Program.Broadcast(bitString.ToString());	0
6862396	6856088	Embed custom SSDL in EF dll	res://*/<dll namespace>.Model.SqlServerCe.ssdl	0
12844751	12844674	How do i write to a text file and read back from a text file from/to a Dictionary<string,List<string>>?	string line = System.String.Empty;\nusing (StreamReader sr = new StreamReader("MyFile.txt")\n{\n    while ((line = sr.ReadLine()) != null)\n    {\n         string[] tokens = line.Split(',');    \n         LocalKeyWords.Add(tokesn[0], tokens[1]);\n    }\n}	0
19403526	19403463	C# Searching for files and folders except in certain folders	var s1 = Directory.GetFiles(path , "*.*", SearchOption.AllDirectories).Where(d => !d.StartsWith("<EXCLUDE_DIR_PATH>")).ToArray();	0
890628	825254	Word Automation: Detect if page break is necessary?	line = wordApp.Selection.Information(wdFirstCharacterLineNumber)\ncol = wordApp.Selection.Information(wdFirstCharacterColumnNumber)	0
19075006	19074930	Read a 2GB file with peek or read	using (var br = new BinaryReader(File.OpenRead(@"filename.2gb"))) {\n    br.BaseStream.Seek(-1, SeekOrigin.End);\n    Console.WriteLine(br.ReadByte()); // last byte\n}	0
686992	686923	How to make sure that Dispose method was called on IDisposable object and if possible to integrate it into continuous integration?	public MyClass : IDisposable\n{\n\nIEventLogger _eventLogger;\n\npublic MyClass() : this(EventLogger.CreateDefaultInstance())\n{\n}\n\npublic MyClass(IEventLogger eventLogger)\n{\n    _eventLogger = eventLogger;\n}\n\n// IDisposable stuff...\n\n#if DEBUG\n~MyClass()\n{\n    _eventLogger.LogError("MyClass.Dispose() was not called");\n}\n#endif\n\n}	0
10285898	10285542	In what format does Oracle expect a date value, and how can I give Oracle what it wants?	int iFromYear = dateTimePickerScheduleDate.Value.Year;\nint iFromMonth = dateTimePickerScheduleDate.Value.Month;\nint iFromDay = dateTimePickerScheduleDate.Value.Day;\n. . .\nocmd.Parameters.Add("AVAIL_DATE", new DateTime(iFromYear, iFromMonth, iFromDay));	0
4998810	2726375	How do I get a bucket by name in the .Net S3 SDK?	public static S3Bucket GetS3Bucket(string bucket)\n{\n    try\n    {\n        AmazonS3 client = Amazon.AWSClientFactory.CreateAmazonS3Client(accessKeyID, secretAccessKeyID);\n        return client.ListBuckets().Buckets.Where(b => b.BucketName == bucket).Single();\n    }\n    catch (AmazonS3Exception amazonS3Exception)\n    {\n        throw amazonS3Exception;\n    }\n}	0
30245832	30245776	Unified Date format with no reliance to the server/system	yyyy-MM-dd	0
12919917	12919900	GET request works, how to make POST work too?	POST /api/updateunitdetails HTTP/1.1\nHost: localhost:58743\n\nContent-Type: application/x-www-form-urlencoded\n\n\n=sweet	0
5253633	5253610	How can I use Linq for this?	var count =\n    from i in player\n    group i by i into g\n    select new { Number = g.Key, Count = g.Count() }	0
22346414	22346307	how to check all of the first and second elements of the 2D array?	int[,] spn = { { 3064, 22 }, { 3064, 16 }, { 3064, 11 } };\n      int helper = 2;\n      for (var N = 0; N < spn.Length / helper; N++)\n      {\n          if (spn[N, 0] != 3064 && spn[N, 1] != 16 || spn[N, 1] != 16)\n              System.Diagnostics.Debug.WriteLine("do something");\n      }	0
8083860	8071416	Create a list from another grouped list. (Rate by date)	// for each combination of ID1 and ID2\n// return the latest item from the \n// most frequently-occuring quantity\nIEnumerable<MyEntity> GetLatestMaxByID(IEnumerable<MyEntity> list) {\n    foreach (var group in list.GroupBy(x => new { x.ID1, x.ID2 }))\n        yield return GetSingleItemForIDs(group);\n}\n\n// return the latest item from the \n// most frequently-occuring quantity\nMyEntity GetSingleItemForIDs(IEnumerable<MyEntity> list) {\n    return list.GroupBy(x => x.Quantity)\n               .MaxBy(g => g.Count())\n               .MaxBy(x => x.Date);\n}\n\n// use MaxBy from the morelinq (http://code.google.com/p/morelinq) \n// or use a simplified one here\n// Get the maximum item based on a key\npublic static T MaxBy<T, U>(this IEnumerable<T> seq, Func<T, U> f) {\n    return seq.Aggregate((a, b) => Comparer<U>.Default.Compare(f(a), f(b)) < 0 ? b : a);\n}	0
8038261	8037714	how to insert rows when there are none already there only	DECLARE @HasData INT\n\nSELECT @HasData = count(*)\nFROM [table]\n\nif (@HasData != 0)    \nbegin\n    INSERT INTO [table] VALUES ('module1')\n    INSERT INTO [table] VALUES ('module2')\n    INSERT INTO [table] VALUES ('module3')\n    -- etc\nend	0
15727829	15092290	Entity Framework - using the same DbContext with different connection strings	public class HOLContextFactory\n{\n    public static HOLDbEntities Create()\n    {\n        // default connection string\n        return new HOLDbEntities(); \n    }\n\n    public static HOLDbEntities CreateQuote()\n    {\n        // specified connection string\n        return new HOLDbEntities ("HOLDbQuoteEntities"); \n    }\n}\n\npublic partial class HOLDbEntities\n{\n    public HOLDbEntities(string connectionString)\n        : base(connectionString) \n        {\n        }\n    }\n}	0
18297545	18297477	How to bind a sql column to a drop down list?	DropDownList1.DataSource  = dtTable;  \nDropDownList1.DataTextField = "Name";\nDropDownList1.DataValueField= "Id";\nDropDownList.DataBind();	0
6349665	6349592	unit testing a unit of work	[Test]\npublic void Will_call_save_changes() {\n\n  var mockContext = new Mock<DBContext>();\n  var unitOfWork = new UnitOfWork(mockContext.Object);\n\n  unitOfWork.Commit();\n\n\n  mockContext.Verify(x => x.SaveChanges());\n\n}	0
29309270	29309118	Using jagged list for only two indexes	_data[_index]	0
13119576	13119477	Convert this string to datetime object	DateTime.parse("2012-10-29T08:45:00.000")	0
19784747	19784663	how to add items from listbox to textbox c#	string value = "The items you purchased are:\r\n\r\n";\nforeach (var item in lbxItemBought.Items)\n{\n   value += "," + item.ToString(); \n}\n\nvalue += "\r\n\r\nYour total price was:" + lblLastCheckout.Text ;\ntbxReceipt.Text = value;	0
18871956	18871824	Inherit a generic class from another generic class	public class SubGenericTest<T> : BaseGenericTest<T> where T:IGenericVewModel, SubViewModel	0
8359521	8359058	Pause/Resume loop in Background worker	void ResumeWorker() {\n     // Start the worker if it isn't running\n     if (!backgroundWorker1.IsBusy) backgroundWorker1.RunWorkerAsync(tempCicle);  \n     // Unblock the worker \n     _busy.Set();\n}\n\nvoid PauseWorker() {\n    // Block the worker\n    _busy.Reset();\n}\n\nvoid CancelWorker() {\n    if (backgroundWorker1.IsBusy) {\n        // Set CancellationPending property to true\n        backgroundWorker1.CancelAsync();\n        // Unblock worker so it can see that\n        _busy.Set();\n    }\n}	0
23409831	23071318	Refreshing RadGridView with Programtically added Button : A column with the same Name already exists in the collection	radGridView1.Columns.Clear();	0
5700075	5699823	How can i add the row dynamically at an exact postion in a dataset	DataColumn dc = new DataColumn("Amount1");\nlocal_ds.Tables[0].Columns.Add(dc);\n\nfor (int i = 0; i < AchDB.Amount1.Count; i++)\n{\n    local_ds.Tables[0].Rows[i]["Amount1"] = AchDB.Amount1[i];\n}	0
25059932	25056429	Accessing Local file from Web Site in VS2013	var doc = XElement.Load(Server.MapPath("~/myxml.xml"));	0
31604247	31604133	Extend "object" with a null check more readable than ReferenceEquals	bool itIsANull = obj.IsNull();	0
8648195	8648022	AJAX JSON not retrieving value	var rpinfo = rpdata[0].FirstName + " " +rpdata[0].LastName	0
28050628	28001429	passing data to constructor parameters to castle windsor container	container.AddFacility<TypedFactoryFacility>();\ncontainer.Register(\n                 Component.For<IInvestigationBoxFactory>()\n                          .AsFactory()\n               );	0
3498554	3498538	C# Linq String[] list minus from String[] list	// as you may know, this is the right method to declare arrays       \nstring[] admins = {"aron", "mike", "bob"};\nstring[] users = {"mike", "katie", "sarah"};\n\n// use "Except"\nvar exceptAdmins = users.Except( admins );	0
11427333	11426980	Insert List of Objects using Entity Framework	Guid.NewGuid().GetHashCode()	0
17702987	17702487	Pivot json data from array of models	var tempFoo = newArray(); tempBar = newArray();\nfor (var i = 0; i < myModel.length; i++){\n    tempFoo.push(myModel[i].foo);\n    tempBar.push(myModel[i].bar);\n}	0
855338	852720	Executing Sql statements with Fluent NHibernate	public int GetSqlCount<T>(Session session, string table)\n{\n    var sql = String.Format("SELECT Count(*) FROM {0}", table);\n    var query = session.CreateSQLQuery(sql);\n    var result = query.UniqueResult();\n    // Could also use this if only updating values:\n    //query.ExecuteUpdate();\n\n    return Convert.ToInt32(result);\n}	0
28247887	28244519	Sending a file via WebRequest	using (var requestStream = request.GetRequestStream())\n{\n    fileStream.CopyTo(requestStream);\n}	0
33558817	33521112	Linq - Get all keys from dictionary where all values in the value list are equal to criteria	var keys =\n    myDictionary\n        .Where(kvp => kvp.Value.All(d =>\n            d.HasValue == false || d.Value == new DateTimeOffset(DateTime.Today)))\n        .Select(kvp => kvp.Key);	0
29545438	29545322	How to pass an attribute value from ImageButton to code behind	((ImageButton)sender).Attributes["UploadStatus"]	0
1662835	1662761	CheckedListBox populating a text control	public class MyValues\n{\n    private bool _check;\n\n    public bool Check\n    {\n        get\n        {\n            return _check;\n        }\n        set\n        {\n            if(_check != value)\n            {\n                _check = value;\n                // todo: raise event!\n            }\n        }\n    }\n}	0
30353998	30353908	Im referencing a constant class static variables, but when i do the values somehow change	public static decimal positivePastLimitDecimal = Convert.ToDecimal(80000000000000E+40)\n public static decimal negativePastLimitDecimal = Convert.ToDecimal(-8000000000000E-40);	0
4880729	4874960	How can I override the serialized name of each list item in a List<SomeStruct>() in c#?	[XmlRoot("Customers")]\npublic class Customers\n{\n    [XmlElement("Customer")]\n    public List<TCustomer> List = new List<TCustomer>();\n}	0
7918208	7918022	Give UI control Click event by code	Grid g = new Grid();\ng.MouseLeftButtonDown += (s, args) =>\n       {\n          //do stuff, you can reference s and args where s is the sender\n       };	0
12061522	12061496	HTMLAgilityPack how to parse document that is already open in WebControl	HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();\ndoc.LoadHtml(webcControl.DocumentText);	0
10523170	10523140	How to sort dictionary by DateTime attribute of the value	dic.Values.OrderBy(i=>i.CreatedDateTime)	0
380955	380911	How to save XPathExpression result to separate XML with ancestor structure?	string xml = @"<xml>\n <a>\n  <x/>\n  <b>\n    <c/>\n    <z/>\n  </b>\n  <c/>\n</a>\n<c/>\n<d><e/></d></xml>";\n    XmlDocument doc = new XmlDocument();\n    doc.LoadXml(xml);\n    XmlDocument results = new XmlDocument();\n    XmlNode root = results.AppendChild(results.CreateElement("xml"));\n    foreach (XmlNode node in doc.SelectNodes("/*/*[descendant-or-self::c]"))\n    {\n        root.AppendChild(results.ImportNode(node, true));\n    }\n    results.Save("out.xml");	0
8317146	8309932	Manipulating dotx templates with C#	// First, create a copy of your template.\nFile.Copy(@"c:\temp\mytemplate.dotx", @"c:\temp\test.docx", true);\n\nusing (WordprocessingDocument newdoc = WordprocessingDocument.Open(@"c:\temp\test.docx", true))\n{\n  // Change document type (dotx->docx)\n  newdoc.ChangeDocumentType(WordprocessingDocumentType.Document);\n\n  // Find all structured document tags\n  IEnumerable<SdtContentRun> placeHolders = newdoc.MainDocumentPart.RootElement.Descendants<SdtContentRun>();\n\n  foreach (var cp in placeHolders)\n  {\n    var r = cp.Descendants<Run>().FirstOrDefault();\n\n    r.RemoveAllChildren(); // Remove children\n    r.AppendChild<Text>(new Text("my text")); // add new content\n  }        \n}	0
27715243	27715230	Select Top for Subquery with Entity Framework	Masters\n   .Select(m => new{\n       Master = m, \n       Detail = m.Details.OrderBy(d => d.StartDate).FirstOrDefault())\n   })	0
3104817	3104703	Cannot access a non-shared member of a class in C#, but can in VB?	public class Form1 {\n    ClassFoo fooObj;\n    public Form1() {\n        fooObj = new ClassFoo(this);\n    }\n    public void Foo() {\n        MessageBox.Show("un-fooed");\n    }\n}\n\npublic class ClassFoo {\n    Form1 mainForm;\n    public ClassFoo(Form1 main) {\n        mainForm = main;\n    }\n    public void Foo() {\n        mainForm.Foo();\n    }\n}	0
27711747	27711690	Compose filters without the presence of a collection?	var previousFilter = filter;\nfilter = c => previousFilter(c) && c <= 10;	0
6545857	6545834	Is it possible to raise an event of other control on selecting another	radio_CheckedChanged(sender, EventArgs.Empty)	0
26480609	26480340	How can i call a Func<int,int,int> arguments in a method in C#?	public static void SomeTestMethod(int number,string str)\n{\n    Check( () => MethodOne(number,str));\n}\n\npublic static int Check(Func<int> method)\n{\n         // some conditions \n      return method();\n}	0
4394910	4394876	Insert 65535 rows into SQL Server 2008	System.Data.SqlClient.SqlBulkCopy	0
251757	243646	How to read a PEM RSA private key from .NET	var bytesToDecrypt = Convert.FromBase64String("la0Cz.....D43g=="); // string to decrypt, base64 encoded\n\nAsymmetricCipherKeyPair keyPair; \n\nusing (var reader = File.OpenText(@"c:\myprivatekey.pem")) // file containing RSA PKCS1 private key\n    keyPair = (AsymmetricCipherKeyPair) new PemReader(reader).ReadObject(); \n\nvar decryptEngine = new Pkcs1Encoding(new RsaEngine());\ndecryptEngine.Init(false, keyPair.Private); \n\nvar decrypted = Encoding.UTF8.GetString(decryptEngine.ProcessBlock(bytesToDecrypt, 0, bytesToDecrypt.Length));	0
32006074	31874525	Filter system fields from Sharepoint ListItemCollection c#	foreach (string li in fieldsToDisplay)\n{\n    clientContext.Load(collListItem,\n        items => items.Include(\n            item => item[li]));\n}	0
16473090	16464006	No embedded images in email	ImageConverter ic = new ImageConverter();\nByte [] ba = (Byte[]) ic.ConvertTo(page,typeof(Byte[]));\nvar memoryStream = new MemoryStream(ba);\npage.Save(memoryStream, System.Drawing.Imaging.ImageFormat.Png);	0
8000891	8000560	2 longitudes C# validation	bool IsMoreWest(double longitudeA, double logitudeB)\n{\n    double difference = longitudeA - logitudeB;\n    if (Math.Abs(difference) > 180.0) {\n        difference = -Math.Sign(difference) * (360.0 - Math.Abs(difference));\n    }\n    return difference < 0;\n}	0
4607972	4607919	Custom MVC route: changing where the views for a controller are located	routes.MapRoute("Employees", "employees/{action}", new { \n    controller = "Employee",\n    action = "Index" });	0
5720731	5719122	Add model with link to model object EFModelFirst	var ingredient = db.Ingredients.Single(i => i.Name == name); //throws exception if more than one ingredient with that name excists\nperson.Ingredient = ingredient;\ndb.Persons.Add(person)	0
11892212	11891992	Design decision - inheritance with delegation	Is CheckoutAd a SiteAd? (yes inherit)\nDoes CheckOutAd have a SiteAd? (yes aggreate)\nNo to both, leave them the heck alone..	0
4842029	4842014	SQLite Date Query	var q = db.Query<MeasurementEntity>(sql,child.PK, t.ToString("s"));	0
28681517	28681351	data binding with a button with user control	public Form1()\n{\n    InitializeComponent();\n    Control[] control = userControl1.Controls.Find("textbox1", true);\n    control.First().Text = "Found!";\n}	0
9938602	9800553	Nested Json as input in POST method	public void MyMethod(string timestamp, theNewClass json) ;	0
18026219	18025263	Formatting chart axis labels	chart1.ChartAreas[0].AxisX.LabelStyle.Format = "{0:0,}K";	0
4107862	4107836	Unable to Compile with ImportMany attribute	[TestClass]\npublic class GlobalInterfacesUnitTest\n{\n    [ImportMany(AllowRecomposition = true)]\n    Lazy<IComponentGui, IImportComponentGuiCapabilites>[] Senders {get;set;}\n\n    [TestMethod]\n    public void TestMethod1()\n    {\n\n    }\n}	0
3464312	3464289	How to pass multiple arguments to a newly created process in C# .net?	string[] args = { "first", "second", "\"third arg\"" };\nProcess.Start("blah.exe", String.Join(" ", args));	0
18352405	18352173	Increasing date by the hour	private DateTime m_LastDateTime;\n\nprivate void Cld_SelectedDateChanged(object sender, EventArgs e)\n{\n    m_LastDateTime = e.Start;\n    textBox1.Text = m_LastDateTime.ToString();\n    txtHH.Text =m_LastDateTime.Hour.ToString();\n    txtMM.Text =m_LastDateTime.Minute.ToString();\n}\n\nprivate void btnAddHour_Click( object sender, RoutedEventArgs e )\n{\n    m_LastDateTime = m_LastDateTime.AddHours(1);\n    txtHH.Text = m_LastDateTime.ToString("HH");\n}\n\nprivate void btnAddMinute_Click( object sender, RoutedEventArgs e )\n{\n    m_LastDateTime = m_LastDateTime.AddMinutes(1);\n    txtMM.Text = m_LastDateTime.ToString( "mm" );\n}	0
28898725	28872780	Adding date in filename of RollingFileAppender files	_roller.DatePattern = "yyyy-mm-dd";\n        _roller.PreserveLogFileNameExtension = true;\n        _roller.File = Path.Combine(FileDirectory,".log");\n        _roller.StaticLogFileName = false;	0
9956405	9956382	Determine number of characters entered into textbox with C#	int jj = textBox1.Text.Length;	0
6375097	6375030	How to properly hide a base class property	[Obsolete(IsError=true)]\npublic new ComboBoxItemCollection Items\n{\n    get { return base.Items; } // Or throw an exception\n}	0
2543281	2543273	How do I get everything after a certain index in string c#	string str = "MyNamespace.SubNameSpace.MyClassName";\nstring str1 = str.Substring(str.LastIndexOf('.') + 1);	0
14531069	14530912	WinRt page navigaiton	On App.xaml.cs\n      public static Frame MainFrame{get;private set;}\n\n      protected override void OnLaunched(LaunchActivatedEventArgs args)\n            {\n                Frame rootFrame = Window.Current.Content as Frame;\n                MainFrame = rootFrame;\n(....)\n            }\nUsage:\n       App.MainFrame.Navigate(...);	0
15874949	15874785	Create a stream from a bitmap on Windows Runtime	StorageFile imageFile = await (await Windows.ApplicationModel.Package.Current.InstalledLocation.GetFolderAsync("Assets")).GetFileAsync("testimage.jpg");\nStream imgStream = await imageFile.OpenStreamForReadAsync();	0
23126564	23126398	Compare two dictionaries and merge in to other dictionary with keys and values present in both dictionaries	Dictionary<string, string> dict1 = new Dictionary<string, string>();\nDictionary<string, string> dict2 = new Dictionary<string, string>();\nDictionary<string, KeyValuePair<string, string>> complexdicts = new Dictionary<string, KeyValuePair<string, string>>();\n\ndict1.Add("A", "1");\ndict1.Add("B", "2");\n\ndict2.Add("A", "2");\ndict2.Add("C", "3");\ndict2.Add("D", "4");\n\nvar allKeys = dict1.Keys.Union(dict2.Keys);\n\nforeach (var key in allKeys)\n{\n    string val1;\n    if (!dict1.TryGetValue(key, out val1))\n    {\n        val1 = "Not Available";\n    } \n    string val2;\n    if (!dict2.TryGetValue(key, out val2))\n    {\n        val2 = "Not Available";\n    }\n    complexdicts.Add(key, new KeyValuePair<string, string>(val1, val2));\n}	0
5736021	5735886	How to convert Hex to RGB?	Color.GetBrightness()	0
6910831	6910762	How to modify the List view column?	string r = "1000.123456";\n var t = string.Format("{0:#.##}",decimal.Parse(r)); //1000.12	0
11233900	11233848	How to add a custom control to the toolbox?	class Foo\n{\n    public Foo() : this(SomeType.Value) { }\n    public Foo(SomeType whatever) : { /* do stuff /* }\n}	0
30535330	30534918	How to get file type from encrypted file?	NBCM CM UH YRUGJFY\nnbcm cm uh yrugjfy\nocdn dn vi zsvhkgz\npdeo eo wj atwilha\nqefp fp xk buxjmib\nrfgq gq yl cvyknjc\nsghr hr zm dwzlokd\nthis is an example\nuijt jt bo fybnqmf\nvjku ku cp gzcorng\nwklv lv dq hadpsoh\nxlmw mw er ibeqtpi\nymnx nx fs jcfruqj\nznoy oy gt kdgsvrk\naopz pz hu lehtwsl\nbpqa qa iv mfiuxtm\ncqrb rb jw ngjvyun\ndrsc sc kx ohkwzvo\nestd td ly pilxawp\nftue ue mz qjmybxq\nguvf vf na rknzcyr\nhvwg wg ob sloadzs\niwxh xh pc tmpbeat\njxyi yi qd unqcfbu\nkyzj zj re vordgcv\nlzak ak sf wpsehdw\nmabl bl tg xqtfiex\nnbcm cm uh yrugjfy	0
2772845	2772256	Initializing a value through a Session variable	var myIndex = <%=!string.IsNullOrEmpty( (string)Session["myIndex"] ) ? Session["myIndex"] : "1" %> ;	0
769452	769373	What's a clean way to break up a DataTable into chunks of a fixed size with Linq?	private List<List<DataRow>> ChunkifyTable(DataTable table, int chunkSize)\n{\n    List<List<DataRow>> chunks = new List<List<DaraRow>>();\n    for (int i = 0; i < table.Rows.Count / chunkSize; i++)\n    {\n        chunks.Add(table.Rows.Skip(i * chunkSize).Take(chunkSize).ToList());\n    }\n\n    return chunks;\n}	0
24037539	24037404	File Explorer for WPF - UnauthorizedAccessException	try\n{\n  foreach (DirectoryInfo DR in DIR.GetDirectories())\n{\n// stuff\n}\n}\ncatch(exception ex)\n{\n//do something with the failure. maybe ignore it\n}	0
25781164	25781032	how to get the total selected days from 2 calendars in asp.net	DateTime DtF = ceFromDate.SelectedDate.Value;\n        DateTime D1T = ceToDate.SelectedDate.Value;\n\n        double dd = (DtF - D1T).TotalDays;\n\n        total.Text = dd.ToString();	0
10546630	10546302	Find all pattern indexes in string in C#	string pattern = "##";\n string sentence = "45##78$$#56$$J##K01UU";\n IList<int> indeces = new List<int>();\n foreach (Match match in Regex.Matches(sentence, pattern))\n {\n      indeces.Add(match.Index);\n }	0
21688273	21688079	get list of files in directory that are 3 extensions and only numbers	Regex r = new Regex(@"^\.\d\d\d$");\nvar list = Directory.EnumerateFiles(AppDomain.CurrentDomain.BaseDirectory, \n                               _globalSetting.CompanyCode + "trn*.*", \n                               SearchOption.TopDirectoryOnly)\n                               .Where(x => r.IsMatch(Path.GetExtension(x)));	0
4721318	4721300	Getting values from a multiple constructor	string a	0
30614664	30602401	Telerik PdfViewer - Binding to a PDF source	public PdfViewerControl()  {  \nif (Application.Current == null)    \n    new Application();   \nInitializeComponent();  \n}	0
10568922	10568798	How to handle date in web app?	getTimezoneOffset()	0
14752978	14752241	hiding datapager in GridView when page number =1	protected void GridView1_DataBound(object sender, EventArgs e)\n{\n     pager.Visible = (pager.PageSize < pager.TotalRowCount); \n}	0
25298734	25298602	.Split() in a position rather than on a char?	string s = "CP1-P-CP2-001-A";\nMatch m  = Regex.Match(s, @"\d{3}(?=[A-]|$)");\nif (m.Success) {\n    int i = Convert.ToInt32(m.Value); i += 1;\n    Console.WriteLine(i.ToString("D3")); //=> "002"\n}	0
24133142	24133068	Optimization of sorting of subsequent child nodes under the tree like hierarchy	private void Sort()\n{\n     this.ChildNodes.Sort((x, y) => x.Name.CompareTo(y.Name)); // your sort\n\n     foreach (var node in this.ChildNodes)\n    {\n         node.Sort(); // this calls the Sort function for all children\n    }\n}	0
24163796	24163676	Load a second ASP.NET page into codebehind	Page.LoadControl(...)	0
20284908	20269406	Read DER private key in C# using BouncyCastle	var privKeyObj = Asn1Object.FromStream(privatekey);\nvar privStruct = new RsaPrivateKeyStructure((Asn1Sequence)privKeyObj);\n\n// Conversion from BouncyCastle to .Net framework types\nvar rsaParameters = new RSAParameters();\nrsaParameters.Modulus = privStruct.Modulus.ToByteArrayUnsigned();\nrsaParameters.Exponent = privStruct.PublicExponent.ToByteArrayUnsigned();\nrsaParameters.D = privStruct.PrivateExponent.ToByteArrayUnsigned();\nrsaParameters.P = privStruct.Prime1.ToByteArrayUnsigned();\nrsaParameters.Q = privStruct.Prime2.ToByteArrayUnsigned();\nrsaParameters.DP = privStruct.Exponent1.ToByteArrayUnsigned();\nrsaParameters.DQ = privStruct.Exponent2.ToByteArrayUnsigned();\nrsaParameters.InverseQ = privStruct.Coefficient.ToByteArrayUnsigned();\nvar rsa = new RSACryptoServiceProvider();\nrsa.ImportParameters(rsaParameters);\nreturn Encoding.UTF8.GetString(rsa.Decrypt(Convert.FromBase64String(ciphertext), true));	0
33835873	33830539	RallyAPI: How do I create a UserStory and relate it to a Feature?	toCreate["PortfolioItem"] = Ref.GetRelativeRef(createFeatureResult.Reference);	0
22691558	22690666	How to run an asp.net application in local IIS	Windows Authentication	0
5386495	5386267	Replicate steps in downloading file	Sub Search_Google()\nDim IE As Object\nSet IE = CreateObject("InternetExplorer.Application")\n\nIE.Navigate "http://www.google.com" 'load web page google.com\n\nWhile IE.Busy\n  DoEvents  'wait until IE is done loading page.\nWend\n\nIE.Document.all("q").Value = "what you want to put in text box"\nie.Document.all("btnG").Click \n'clicks the button named "btng" which is google's "google search" button\n\nWhile ie.Busy\n  DoEvents  'wait until IE is done loading page.\nWend\n\nEnd Sub	0
6158306	6158281	Clear controls Dynamically	public void ClearPanels(GroupBox control)\n{\n  control.Controls.Clear();\n}	0
21284099	21283948	Get keys (objects) from a dictionary that contains list and filtered by values	var myKeys = objAwithB.Where(\n    kvp => kvp.Value.Any(v => v.prop1.Equals(objB.prop1) )\n  ).Select(kvp => kvp.Key);	0
20341875	20341212	Implementing taglib# into a c# music player	TagLib.File tagFile = TagLib.File.Create(@"C:\MySong.mp3");\n\n    uint trackNumber = tagFile.Tag.Track;\n    string songTitle = tagFile.Tag.Title;\n    string artist = tagFile.Tag.AlbumArtists.FirstOrDefault();\n    string albumTitle = tagFile.Tag.Album;\n    uint year = tagFile.Tag.Year;\n    string genre = tagFile.Tag.Genres.FirstOrDefault();\n\n    MemoryStream ms = new MemoryStream(tagFile.Tag.Pictures[0].Data.Data);\n    System.Drawing.Image albumArt = System.Drawing.Image.FromStream(ms);	0
32892314	32891553	Escaping double quotes in JSON array using Json.NET	using Newtonsoft.Json;\nusing Newtonsoft.Json.Linq;\n\n...\n\ndynamic jsonObject = new JObject();\njsonObject.keyName1 = "XXX";\njsonObject.keyName2 = 180539;\njsonObject.keyName3 = new JArray() as dynamic;\n\ndynamic jsonArrayObject = new JArray() as dynamic;\n\ndynamic jsonObject2 = new JObject();\njsonObject2.what = "xxxxx";\njsonArrayObject.Add(jsonObject2);\n\njsonObject2 = new JObject();\njsonObject2.what = "yyyyy";\njsonObject2.duration = 30;\njsonArrayObject.Add(jsonObject2);\n\njsonObject2 = new JObject();\njsonObject2.what = "zzzz";\njsonArrayObject.Add(jsonObject2);\n\nvar jsonArrayString = JsonConvert.SerializeObject(jsonArrayObject, Formatting.None);\n\njsonObject.keyName3 = jsonArrayString;\njsonObject.keyName4 = "123";\n\nstring json = JsonConvert.SerializeObject(jsonObject, Formatting.None);	0
24897953	24790621	Nested Fluent Interface	public class A {}\npublic class B : A {}\npublic class C<T> : A where T : C<T>\n{/*most methods return T*/}\npublic class D:C<D>\n{/*all methods return this*/}\npublic class E<T>:C<T> where T:E<T>\n{/*all methods return T*/}\npublic class F:E<F>{}	0
18657775	18546124	Unable to cast String to DateTime	DateTime fromdate = DateTime.ParseExact(txtToDate.Text, "dd/MM/yyyy", null);\n\nQuery = Query + "And   CONVERT(DATETIME, FLOOR(CONVERT(FLOAT, ord_del_date))) >= '" + fromdate.ToString("yyyy'-'MM'-'dd") + "'";	0
16682584	16607099	Google Calendar sync with database	EventFeed calFeed = service.Query(query) as EventFeed;\n\nwhile (calFeed != null && calFeed.Entries.Count > 0) {\n    foreach(EventEntry entry in calFeed.Entries) {\n        DateTime modified = entry.Edited.DateValue;\n    }\n}	0
5143704	5143633	Use variable as part of textbox name in C#	for (int i = 0; i <= count; i++)\n        {\n            TextBox textbox = (TextBox)Controls.Find(string.Format("tbox{0}", i),false).FirstOrDefault();\n            CheckBox checkbox = (CheckBox)Controls.Find(string.Format("cbox{0}", i),false).FirstOrDefault();\n\n            string s = textbox.Text + (checkbox.Checked ? "true" : "false");\n        }	0
1137702	1137538	How to refresh a binding of the itemssource of a combobox programmatically?	private void theComboBox_OnGotFocus(object sender, RoutedEventArgs e)\n{\nComboBox theComboBox = sender as ComboBox;\n\nif (theComboBox != null)\n{\nMultiBindingExpression binding = BindingOperations.GetMultiBindingExpression(theComboBox, ComboBox.ItemsSourceProperty);\nif (binding != null)\n{\nbinding.UpdateTarget();\n}\n}\n}	0
14439436	14439361	Group a complex type by value	public class Group\n{\n    public int GroupId { get; set; }\n    public string Name { get; set; }\n\n    protected bool Equals(Group other)\n    {\n        return GroupId == other.GroupId;\n    }\n\n    public override bool Equals(object obj)\n    {\n        if (ReferenceEquals(null, obj)) return false;\n        if (ReferenceEquals(this, obj)) return true;\n        if (obj.GetType() != this.GetType()) return false;\n        return Equals((Group) obj);\n    }\n\n    public override int GetHashCode()\n    {\n        return GroupId;\n    }\n}	0
483815	422768	Attaching to a child process automatically in Visual Studio during Debugging	For Each process In DTE.Debugger.LocalProcesses\n        If (process.Name.IndexOf("aspnet_wp.exe") <> -1) Then\n            process.Attach()\n            Exit Sub\n        End If\n    Next	0
1957778	1957590	Detecting address type given an a string	public string DetectScheme(string address)\n{\n    Uri result;\n    if (Uri.TryCreate(address, UriKind.Absolute, out result))\n    {\n        // You can only get Scheme property on an absolute Uri\n        return result.Scheme;\n    }\n\n    try\n    {\n        new FileInfo(address);\n        return "file";\n    }\n    catch\n    {\n        throw new ArgumentException("Unknown scheme supplied", "address");\n    }\n}	0
33417394	30872023	Setting AutoScrollPosition when AutoScroll is set to false	Panel.SetBounds( 0, -ScrollBar.Value, Panel.Width, Panel.Height );	0
24176906	24175824	how to set order in placeholder.control in recursive c#	if (ds.Tables[0].Rows[i][2] != null)\n    {\n        parID = ds.Tables[0].Rows[i][2].ToString();\n        LevelControl(parID);\n    }\n    PlaceHolder1.Controls.Add(btn);	0
2255448	2235061	Indentation in a custom TraceListener	...\nif (entry.IndentLevel > 0)\n    writer.WriteLine(\n        new string(' ', entry.IndentLevel * IndentSize) +\n...	0
10500590	10500557	C# variable in an xpath selector	string myText = "foo";    \nAssert.IsTrue(Browser.IsElementPresent(String.Format("//option[contains(text(), {0})]", myText)));	0
6401615	6400164	WPF: Adding Shapes to a Canvas	Canvas.SetTop(path, 10);\nCanvas.SetLeft(path, 10);	0
10546246	10546186	how to escape html elements in c# .net using JavaScriptSerializer	var str = JsonConvert.SerializeObject(new {html="<>"}) //returns {"html":"<>"}	0
6022681	5998535	Set Drive VolumeLabel	public void SetVolumeLabel(string newLabel)\n    {\n        DriveInfo[] allDrives = DriveInfo.GetDrives();\n        foreach (DriveInfo d in allDrives)\n        {\n            if (d.IsReady && d.DriveType == DriveType.Removable)\n            {\n                d.VolumeLabel = newLabel;\n            }\n        }\n    }\n\n    public string VolumeLabel { get; set; }\n\n    // Setting the drive name\n    private void button1_Click(object sender, EventArgs e)\n    {\n        SetVolumeLabel("FlashDrive");\n    }	0
10781889	10781011	Get source of Webpage in Webbrowser C#	public partial class Form1 : Form {\n    public Form1() {\n        InitializeComponent();\n        webBrowser1.Url = new Uri("http://stackoverflow.com/questions/10781011/get-source-of-webpage-in-webbrowser-c-sharp");\n        webBrowser1.DocumentCompleted += webBrowser1_DocumentCompleted;\n        timer1.Interval = 100;\n        timer1.Tick += new EventHandler(timer1_Tick);\n    }\n\n    void timer1_Tick(object sender, EventArgs e) {\n        var elem = webBrowser1.Document.GetElementById("wmd-input");\n        label1.Text = elem.InnerText;\n    }\n\n    void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e) {\n        timer1.Enabled = true;\n    }\n}	0
9203952	9203847	Controlling volume in C# using WMPLib in Windows	private const int APPCOMMAND_VOLUME_MUTE = 0x80000;\n    private const int WM_APPCOMMAND = 0x319;\n    private const int APPCOMMAND_MICROPHONE_VOLUME_UP = 26 * 65536;\n    private const int APPCOMMAND_MICROPHONE_VOLUME_DOWN = 25 * 65536;\n\n    [DllImport("user32.dll")]\n    public static extern IntPtr SendMessageW(IntPtr hWnd, int Msg, IntPtr wParam, IntPtr lParam);\n    private void SetMicVolume()\n    {\n        SendMessageW(new WindowInteropHelper(this).Handle, WM_APPCOMMAND, new (IntPtr)APPCOMMAND_MICROPHONE_VOLUME_UP);//or _DOWN\n    }	0
23537552	23536502	How can I extend a custom LINQ operation?	static class Extensions\n{\n    public static void AddCustomObjects<T>(this List<T> source, List<T> list)\n    {\n        if(source!=null && list!=null)\n            source.AddRange(list);\n    }\n}	0
33303810	33302832	XML Serialization not exporting list correctly	public class XMLFile\n{\n    public XMLFile()\n    {\n\n    }\n\n    [XmlArray("channels")]\n    [XmlArrayItem(Type = typeof(Ch01), ElementName = "Ch01")]\n    [XmlArrayItem(Type = typeof(Ch02), ElementName = "Ch02")]\n    public List<channel> channels = new List<channel>();\n}	0
6669316	6667799	C# start Windows Service programmatically	ServiceController service = new ServiceController(serviceName, serverName);	0
24369731	24368170	MongoDB UTC DateTime Format To Local Time	[BsonDateTimeOptions(Kind = DateTimeKind.Local)]	0
17540510	17536296	Entity Framework join statement in a function	var query = (from s in entities.tableContacts\n             join o in entities.tableObject2Contacts\n                  on new { ContactID = s.contact_id, ObjectID = oid } \n                  equals new { ContactID = o.contact_id, ObjectID = o.objectID } \n                  into oTemp\n             from o in oTemp.DefaultIfEmpty()\n             select new { s });	0
12547180	12547100	Combine a number of groupboxes into a single searchable variable	var items = (groupBox1.Controls.OfType<CheckBox>()\n    .Concat(groupBox2.Controls.OfType<CheckBox>()))\n    .Where(ch => ch.Checked == true).Count();	0
19171338	19170928	Regex, match only if it exists in the current string	Regex regexUserCommented = new Regex(\n    @"(\[COMMENT\])\ " +  // COMMENT\n    @"((\[.*\]) )?" +        // Email, this needs to be optional but how?!\n    @"(\w(?<!\d)[\w'-]*)" // User\n);\n\nvar match = regexUserCommented.Match(test);\n\nif (match.Groups.Count == 5)\n{\n    Console.WriteLine("==> {0}", match.Groups[4].Value);\n}\nelse\n{\n    Console.WriteLine("==> Not matched");\n}	0
740904	740890	C#: How can i change the text of a label thats in form1 from another class?	class SomeClass\n{\n    public delegate void UpdateLabel(string value);\n\n    public event UpdateLabel OnLabelUpdate;\n\n    public void Process()\n    {\n        if (OnLabelUpdate != null)\n        {\n            OnLabelUpdate("hello");\n        }\n    }\n}\n\npublic partial class Form1 : Form\n{\n    public Form1()\n    {\n        InitializeComponent();\n    }\n\n    private void UpdateLabelButton_Click(object sender, EventArgs e)\n    {\n        SomeClass updater = new SomeClass();\n        updater.OnLabelUpdate += new SomeClass.UpdateLabel(updater_OnLabelUpdate);\n        updater.Process();\n    }\n\n    void updater_OnLabelUpdate(string value)\n    {\n        this.LabelToUpdateLabel.Text = value;\n    }\n}	0
19907475	19905143	How to set click Event to all cells in a Row ? Gridview Winforms Devexpress	gridControl1.DataSource = new List<Person> { \n    new Person(){ Name="John Smith"},\n    new Person(){ Name="Mary Smith"}\n};\ngridView1.OptionsBehavior.Editable = false; // disable editing\ngridView1.RowCellClick += gridView1_RowCellClick;\n//...\nvoid gridView1_RowCellClick(object sender, DevExpress.XtraGrid.Views.Grid.RowCellClickEventArgs e) {\n    if(e.Clicks == 2) { // Double Click\n        object cellValue = e.CellValue;\n        //do some stuff\n    }\n}\n//...\nclass Person {\n    public string Name { get; set; }\n}	0
10185391	10185120	C# Capture screen to 8-bit (256 color) bitmap	public static Bitmap ConvertTo8bpp(Image img) {\n        var ms = new System.IO.MemoryStream();   // Don't use using!!!\n        img.Save(ms, System.Drawing.Imaging.ImageFormat.Gif);\n        ms.Position = 0;\n        return new Bitmap(ms);\n    }	0
23000671	23000524	Ado.net, DateTime in SqlCommand	foreach (DataRow row in _cinameZone.Tables["SessionsCinema"].Rows)\n{\n    var sqlParameter = new SqlParameter("@paramName", SqlDbType.DateTime) \n                       { \n                           Value = Convert.ToDateTime(row["sessionDateTime"].Value);                              \n                       }\n    cmd.Parameters.Add(sqlParameter);\n}	0
25081196	25064780	ExpandoObject contains no public properties only in VS2013	var myObj = new object();\n\nList<Dictionary<string, object>> container = new List<Dictionary<string, object>>()\n{\n    new Dictionary<string, object> { { "Text", "Hello world" } }\n};\nJavaScriptSerializer json_serializer = new JavaScriptSerializer();\nvar converter = new ExpandoObjectConverter();\nvar obj = JsonConvert.DeserializeObject<IEnumerable<ExpandoObject>>(json_serializer.Serialize(container), converter);\n\nreturn View(obj);	0
3370099	3370075	String Cleaning in C#	string[] words = news.Split(' ');\n\nStringBuilder builder = new StringBuilder();\nforeach (string word in words)\n{\n    if (word.Length > 1)\n    {\n       if (builder.ToString().Length ==0)\n       {\n           builder.Append(word);\n       }\n       else\n       {\n           builder.Append(" " + word);\n       }\n    }\n}\n\nstring result = builder.ToString();	0
2268234	2268113	Way to color parts of the Listbox/ListView line in C# WinForms?	listBox1.DrawMode = OwnerDrawFixed;\nlistBox1.DrawItem += new System.Windows.Forms.DrawItemEventHandler(this.listBox1_DrawItem);\n\nprivate void listBox1_DrawItem(object sender, DrawItemEventArgs e)\n{\ne.DrawBackground();\ne.DrawFocusRectangle();\n// TODO: Split listBox1.Items[e.Index].ToString() and then draw each separately in a different color\ne.Graphics.DrawString(listBox1.Items[e.Index].ToString(),new Font(FontFamily.GenericSansSerif, 14, FontStyle.Bold),new SolidBrush(color[e.Index]),e.Bounds);\n}	0
13283664	13283595	multiple parent Entities with one child entity in EF code first	public class PostBase{\n    public ICollection<Comment> Comments{get; set; }\n}\n\n\npublic class Post:PostBase\n{\n    public string Title {get; set;}\n\n}\n\npublic class Photo:PostBase\n{\n    public string Path{get;set;}\n\n}\n\npublic class Comment\n{\n    public int? PostBaseId{get;set;}\n    public Virtual PostBase PostBase{get;set;}\n\n}	0
18212964	18212858	Set no. of copies in a System.Windows.Controls.PrintDialog	dialog.PrintTicket.CopyCount	0
14437133	14400943	Do not overwrite settings.settings file with clickonce	public static void UpgradeUserSettings()\n{\n  if (Settings.Default.upgradeRequired)\n  {\n    Settings.Default.Upgrade();\n    Settings.Default.upgradeRequired = false;\n    Settings.Default.Save();\n  }\n}	0
26614525	26612562	Fetch a value of a property of an object in arraylist (C#)	for (int i = 0; i < FormFields.Count; i++)\n{\n     CDatabaseField Db = (CDatabaseField)FormFields[i];\n     Label1.Text = Db.FieldName; //FieldName is the required property to fetch\n}	0
30517233	30363924	Reading file data using HttpWebResponse	var request = (HttpWebRequest) WebRequest.Create(new Uri(_targetUrl));\n\nrequest.Method = "GET";\nrequest.ContentType = "text/plain";\nrequest.ContentLength = 0;\nrequest.UseDefaultCredentials = true;\nrequest.Headers.Add("Ent-APRF:FileIdentifier");\n\nvar cfsResponse = (HttpWebResponse) request.GetResponse();\n\nusing (var rawResponseStream = cfsResponse.GetResponseStream())\n{\n     if (rawResponseStream != null)\n     using (var content = new StreamReader(rawResponseStream, Encoding.GetEncoding(1252)))\n     {\n         using (var ms = new MemoryStream())\n         {\n             content.BaseStream.CopyTo(ms);\n             var myBytes = ms.ToArray();\n\n             var encrypteddata = Convert.ToBase64String(myBytes);\n\n             // call decrypt function suppling encrypted string\n        }        \n    }\n}	0
20952932	20952585	Caching in asp.net for dynamic data in gridview	var cachedList = HttpContext.Current.Cache["cacheKey"];\nif (cachedList == null)\n{\n    var db = new YourDataContext();\n\n    //get your data from the db here somehow\n    cachedList = db.table\n        .Where(x => true)\n        .ToList();\n\n    HttpContext.Current.Cache.Add(\n        "cacheKey",\n        cachedList,\n        null,\n        DateTime.Now.AddMinutes(10),\n        System.Web.Caching.Cache.NoSlidingExpiration,\n        CacheItemPriority.Normal,\n        null);\n}\nreturn (List<YourDataType>)cachedList;	0
22489323	22388707	How to add a table row to a word document using syncfusion in C#	IWTable table = new IWTable();\ntable.AddRow(True);\n\ntable.Rows[0].Cells[0].AddParagraph().AddText("sample text");	0
30601676	30601418	Best practices to return entities with navigation properties as JSON in MVC with EntityFramework	return context.Users.Include(b => b.Orders).ToList();	0
2864987	2864953	C#: convert Unicode to use as url	var comparer = StringComparer.Create(new CultureInfo("ja-JP"), false);\n\nvar dict = new Dictionary<string, string>(comparer)\n{\n    { "",     ""        },\n    { "??", "product" },\n    { "?",   "car"     },\n};\n\nvar path = "/??/?";\n\nvar translatedPath = string.Join("/", path.Split('/').Select(s => dict[s]));	0
1622611	1622597	Renaming Directory with same name different case	var dir = new DirectoryInfo(@"F:\test");\ndir.MoveTo(@"F:\test2");\ndir.MoveTo(@"F:\TEST");	0
32200039	31601888	1GB of Data From MySQL to MS Access	Don't cache results of forward-only cursors	0
5279433	5279274	Screen-scraping for PDF links to download	string pdfLinksUrl = "http://www.google.com/search?q=filetype%3Apdf";\n\n// Load HTML content    \nvar webGet = new HtmlAgilityPack.HtmlWeb();\nvar doc = webGet.Load(pdfLinksUrl);\n\n// select all <A> nodes from the document using XPath\n// (unfortunately we can't select attribute nodes directly as\n// it is not yet supported by HAP)\nvar linkNodes = doc.DocumentNode.SelectNodes("//a[@href]");\n\n// select all href attribute values ending with '.pdf' (case-insensitive)\nvar pdfUrls = from linkNode in linkNodes\n    let href = linkNode.Attributes["href"].Value\n    where href.ToLower().EndsWith(".pdf")\n    select href;\n\n// write all PDF links to file\nSystem.IO.File.WriteAllLines(@"c:\pdflinks.txt", pdfUrls.ToArray());	0
12150446	12149197	How to attach the Content Control to the listbox?	public class GardenTemplateSelector : DataTemplateSelector\n{\n    public override DataTemplate SelectTemplate(object item, DependencyObject container)\n    {\n        var element = container as FrameworkElement;\n        if (element != null && item != null && item is GardenObject)\n        {   \n            if((item as GardenObject).image == "0")\n            {\n                return element.FindResource("TextTemplate") as DataTemplate;            \n            }\n            else\n            {\n                return element.FindResource("ItemTemplate") as DataTemplate;            \n            }           \n        }\n\n        return null;\n    }\n}	0
15831520	15830607	How to scroll ListView to the last element programatically - Compact Framework	listView.EnsureVisible(listView.Items.Count - 1);	0
30457332	30455489	How to split text with HTML tags to array	string value = @"Lorem Ipsum is <b>simply dummy</b> text of the printing and <b>typesetting industry</b>";\nvar parts = Regex.Split(value, @"(<b>[\s\S]+?<\/b>)").Where(l => l != string.Empty).ToArray();	0
12721346	12615867	C# update app.config element	XmlDocument doc = new XmlDocument();\ndoc.Load("MyApp.exe.config");\nXmlNodeList endpoints = doc.GetElementsByTagName("endpoint");\nforeach (XmlNode item in endpoints)\n{\n    var adressAttribute = item.Attributes["address"];\n    if (!ReferenceEquals(null, adressAttribute))\n    {\n        adressAttribute.Value = string.Format("net.tcp://{0}:44424/ServerService/", MachineIp);\n    }\n}\ndoc.Save("MyApp.exe.config");	0
533155	533111	How to change the url based on a Drop Down List?	protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)\n{\nResponse.Redirect(string.Format("Default.aspx?Dept=Shoes&Type={0}", this.DropDownList1.SelectedValue), true);\n}	0
7913545	7913536	C# for loop with already defined iterator	for (; i < 10; i++)\n{\n    Console.WriteLine(i);\n}	0
28694522	28530342	Detecting ajax requests in selenium	IJavaScriptExecutor jsScript = driver as IJavaScriptExecutor;\nif(!(Boolean)jsScript.ExecuteScript("return jQuery.active == 0"))\nretrun "ajax request occured";	0
14940301	14939731	Is it a programmatic way to get SQL keywords (reserved words)	public static class SqlReservedKeywords {\n\n   public bool isReserved(string in)\n   {\n      return SqlServerKeywords.Contains(in.ToUpper());\n   }\n\n   private static HashSet<string> SqlServerKeywords = new HashSet<string>();\n\n   static SqlReservedKeywords() \n   {\n      SqlServerKeywords.Add("ADD");\n      SqlServerKeywords.Add("EXISTS");\n      SqlServerKeywords.Add("PRECISION");\n\n   //. . .\n\n      SqlServerKeywords.Add("EXEC");\n      SqlServerKeywords.Add("PIVOT");\n      SqlServerKeywords.Add("WITH");\n      SqlServerKeywords.Add("EXECUTE");\n      SqlServerKeywords.Add("PLAN");\n      SqlServerKeywords.Add("WRITETEXT");\n   }   \n}	0
15025473	15025305	Counting instances of a date	var countByDate = items.GroupBy(x => x.Invoice.ReceivedDate) // Or whatever\n                       .Select(g => new { Date = g.Key, Count = g.Count() })\n                       .OrderBy(pair => pair.Date);\n                       .ToArray();	0
12105604	12105420	c# dllimport parameters shift	//C#\npublic string Function(int number, string str1, string str2)\n{\n    StringBuilder sbStr1 = new StringBuilder(str1);\n    StringBuilder sbStr2 = new StringBuilder(str2);\n    StringBuilder sbReturnStr = new StringBuilder(1024);\n    Function(number, sbStr1 , sbStr2 , sbReturnStr , sbReturnStr.Capacity);\n    return sbReturnStr.ToString();\n}\n\n//C# p/invoke\nprivate static extern void Function(int number, StringBuilder str1, StringBuilder str2, StringBuilder returnStrBuffer, int size);\n\n//C++\nextern "C" __declspec (dllexport) void __stdcall Function(int number, const char* str1, const char* str2, char* returnStrBuffer, int size)\n{\n     //fill the returnStrBuffer\n     strncpy(returnStrBuffer, "blablalb", size); //example!!\n}	0
2492905	2492847	Download multiple files from an array C#	foreach(var url in listOfStringURLS)\n{\n    WebClient.DownloadFile(url, ".");\n    updateProgressBar();\n}	0
2726230	2726185	PropertyInfo from Delegate	static PropertyInfo ExtractProperty<T>(Expression<Func<T>> selector)\n    {\n        return (selector.Body as MemberExpression).Member as PropertyInfo;\n    }	0
20627195	20626849	how to Append a json file without disturbing the formatting	var filePath = @"C:\Users\grahamo\Documents\Visual Studio 2013\Projects\WebApplication1\WebApplication1\bin\path.json";\n// Read existing json data\nvar jsonData = System.IO.File.ReadAllText(filePath);\n// De-serialize to object or create new list\nvar employeeList = JsonConvert.DeserializeObject<List<EmployeeDetail>>(jsonData) \n                      ?? new List<EmployeeDetail>();\n\n// Add any new employees\nemployeeList.Add(new EmployeeDetail()\n{\n    Name = "Test Person 1"\n});\nemployeeList.Add(new EmployeeDetail()\n{\n    Name = "Test Person 2"\n});\n\n// Update json data string\njsonData = JsonConvert.SerializeObject(employeeList);\nSystem.IO.File.WriteAllText(filePath, jsonData);	0
33805500	33803795	Is it possible to update fetched data	ctx.Entry(Logs).Reload();	0
13229209	13229076	How to register IRepository to Repository to all objects in Unity	container.RegisterType(typeof(IRepository<>), typeof(Repository<>));	0
17337403	17337083	Action as a optional parameter in a function	public void DrawWindow(Rect p_PositionAndSize, string p_Button2Text = "NotInUse", Action p_Button2Action = null)\n{\n    if (p_Button2Action == null)\n        p_Button2Action = delegate{ Debug.Log("NotInUse"); }\n\n    ...\n}	0
19828177	19787080	How to make the X axis shared for 2 charts in WPF in D3?	// Add handler\n        SpeedChart.Viewport.PropertyChanged += new EventHandler<ExtendedPropertyChangedEventArgs>(Viewport_PropertyChanged);\n\n\n// Respond to changes\n        void Viewport_PropertyChanged(object sender, ExtendedPropertyChangedEventArgs e)\n        {\n            if (e.PropertyName == "Visible")\n            {\n                StrokeChart.Viewport.Visible = new DataRect(SpeedChart.Viewport.Visible.XMin, StrokeChart.Viewport.Visible.YMin, SpeedChart.Viewport.Visible.Width, StrokeChart.Viewport.Visible.Height);\n            }\n        }	0
16744158	16744021	Access session object variables from a wrapper class	#region " Constructors "\nprivate EventSchoolsAndGradesSession()\n{\n    schoolgrade = new List<SchoolGrade>();\n    schoolgrade.Add(new SchoolGrade("0", "0"));\n}	0
9228995	9228878	How to mock a not implemented method with Rhino Mock?	Child target = new Child();\n\nParent mockParent = MockRepository.GenerateStub<Parent>();\nmockParent.Stub(x => x.GetSomeValue()).Return(1);\n\ntarget.MyParent = mockParent;\n\nint value = target.GetParentsValue();\n\nAssert.AreEqual(value, 1);	0
997879	997812	Putting date in front of xml file name	string dateString = "0615";\nstring fileName = string.Format(@"G:\project\{0}_tester.xml", dateString);\n\n... = new StreamWriter(fileName);	0
5669769	5669705	Add URL variables with Server.Transfer in asp.net	Context.Items["error"] = "UserNotFound";\nServer.Transfer("add_account.aspx");	0
7603197	2521569	How to detect working internet connection in C#?	System.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable()	0
22316177	22316119	How can I get the row's value start from 1,048,577 to end of the very large excel file?	int lineNr = 1;\nusing (FileStream fs = File.Open(pathToTheFile, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))\nusing (BufferedStream bs = new BufferedStream(fs))\nusing (CsvReader csv = new CsvReader(new StreamReader(bs), true))\n{\n    while (csv.ReadNextRecord())\n    {\n        if (YouCareAboutLine(lineNr))\n        {\n            DoSomethingWithThisLine();\n        }\n        lineNr++;\n    }\n}	0
3667310	3667242	Selecting items in a ListBox	internal void UpdateList() {\nList.Items.Clear(); // delete previos items\n foreach (Item item in Container.Items) // selected container\n  List.Items.Add(item);\n}	0
27129028	27128676	String list with comma separated values to int list	var stringList = new List<string>() { "4, 0, 7, -1,", "0, 1, 7, -1,", "7, 1, 6, -1," };\n        var intList = new List<int[]>();\n\n        foreach(var str in stringList)\n        {\n            // Call Trim(',') to remove the trailing commas in your strings\n            // Use Split(',') to split string into an array\n            var splitStringArray = str.Trim(',').Split(',');\n\n            // Use Parse() to convert the strings as integers and put them into a new int array\n            var intArray = new int[]\n            {\n                int.Parse(splitStringArray[0])\n                ,int.Parse(splitStringArray[1])\n                ,int.Parse(splitStringArray[2])\n                ,int.Parse(splitStringArray[3])\n            };\n\n            intList.Add(intArray);\n        }	0
6531367	6531341	How should my code deal with intentional use of the wrong crypto key?	try\n{\n... code ...\n}\ncatch(CryptographicException e)\n{\n... do something with it ...\n}	0
11671541	11671469	Request only first item Entity Framework	public static UserProfile GetUserProfile(Guid userID)\n{\n    UserProfile oProfile = null;\n\n    using (var context = new MyEntities())\n    {\n        oProfile = (from c in context.UserProfiles where c.UserID == userID select c).FirstOrDefault();\n    }\n\n    return oProfile;\n}	0
505892	505850	Can I ignore delegate parameters with lambda syntax?	Console.WriteLine...	0
11347887	11347840	Json Success Not Triggering On Valid Json	callback=	0
22026	22012	Loading assemblies and its dependencies	AppDomain currentDomain = AppDomain.CurrentDomain;\ncurrentDomain.AssemblyResolve += new ResolveEventHandler(MyResolveEventHandler);	0
15897088	15881862	C# array into MWarray Matlab	RGBImage image = _currentImage as RGBImage;\n\nint height = image.Height;\nint width = image.Width;\n\n//transform the 1D array of byte into MxNx3 matrix \n\nbyte[ , , ] RGBByteImage = new byte[3,height, width];\n\nif (image[0].Bpp > 16)\n{\n    for (int i = 0; i < height; i++)\n    {\n        for (int j = 0, k = 0; k < width; j = j + 3, k++)\n        {\n            RGBByteImage[0, i, k] = image[0].Data[3 * i * width + j];\n            RGBByteImage[1, i, k] = image[0].Data[3 * i * width + j + 1];\n            RGBByteImage[2, i, k] = image[0].Data[3 * i * width + j + 2]; \n        }\n    }\n}\n\nMWNumericArray matrix = null;\nmatrix = new MWNumericArray(MWArrayComplexity.Real, MWNumericType.Int8, 3,height, width);\nmatrix = RGBByteImage;	0
6296066	6295961	Loop through multiple subnodes in XML	var classNodes = doc.SelectNodes("/Sections/Classes/Class");\n// LINQ approach\nstring[] classes = classNodes.Cast<XmlNode>()\n                             .Select(n => n.InnerText)\n                             .ToArray();\n\nvar studentNodes = doc.SelectNodes("/Sections/Students/Student");\n// traditional approach\nstring[] students = new string[studentNodes.Count];\nfor (int i = 0; i < studentNodes.Count; i++)\n{\n    students[i] = studentNodes[i].InnerText;\n}	0
2988176	2988148	Linq/C#: Selecting and summing items from the result of a group by?	int cityTotals = cities\n    .GroupBy(c => c.City)\n    .Select(grp => new { City = grp.Key, Total = grp.Sum(c => c.Total) })\n    .Where(c => c.Total > 20)\n    .Sum(c => c.Total);	0
8218419	8218381	Can a conditional LINQ query be combined into one that runs every time?	IEnumerable<Foo> myFoos = bar.GetFoos()\n    .Where(f => \n        (f.Value1 == value1) && \n        (f.Value2 == value2) &&\n        ((editFoo == null) || (f.ID != editFoo.ID)));	0
18829068	18827930	Format imported text in excel c#	Excel.Application xlApp;\nExcel.Workbook xlWorkBook;\nExcel.Worksheet xlWorkSheet;\nint[,] fieldInfo = new int[4, 2] { { 1, 2 }, { 2, 4 }, { 3, 2 }, { 4, 2 } };\nobject oFieldInfo = fieldInfo;\nxlApp = new Excel.Application();\nobject missing = System.Reflection.Missing.Value;\nxlApp.Workbooks.OpenText(\n    filepath,Excel.XlPlatform.xlWindows,\n    1,\n    Excel.XlTextParsingType.xlDelimited,\n    Excel.XlTextQualifier.xlTextQualifierSingleQuote,\n    false,\n    false,\n    false,\n    true,\n    false,\n    false,\n    missing,\n    oFieldInfo,\n    missing,\n    missing, \n    missing, \n    missing, \n    missing \n        );	0
9521349	9520599	How to cast an object in generic collection?	dynamic currentCollection = ...;\ndynamic anotherCollection = ...;\ndynamic items = Enumerable.Except(currentCollection, anotherCollection);	0
3575805	3575722	Composition With StructureMap	For<IEmployeeLookup>().Add<EmployeeLookup>().\n   Named("employeeLookup");\n\nFor<IEmployeeLookup>().Use<CachedEmployeeLookup>()\n  .Ctor<IEmployeeLookup>().Is(\n     d => d.TheInstanceNamed("employeeLookup"));	0
4787351	4787339	How to assign multiple names simultaneously to a C# class	using C = System.Console;	0
4623840	4623752	Decode S-JIS string to UTF-8	public void Convert()\n{\n   using (TextReader input = new StreamReader(\n     new FileStream("shift-jis.txt", FileMode.Open), \n       Encoding.GetEncoding("shift-jis")))\n   {\n      using (TextWriter output = new StreamWriter(\n        new FileStream("utf8.txt", FileMode.Create), Encoding.UTF8))\n      {\n        var buffer = new char[512];\n        int len;\n\n        while ((len = input.Read(buffer, 0, 512)) > 0)\n        {\n          output.Write(buffer, 0, len);\n        }\n      }\n   }\n}	0
29633313	29618262	LinqToDB how to store enum as string value?	public enum OrderType\n{\n    [LinqToDB.Mapping.MapValue(Value = "NEW")]\n    New,\n    [LinqToDB.Mapping.MapValue(Value = "CANCEL")]\n    Cancel\n}	0
18326814	18326738	How to send email in ASP.NET C#	SmtpClient smtpClient = new SmtpClient("mail.MyWebsiteDomainName.com", 25);\n\nsmtpClient.Credentials = new System.Net.NetworkCredential("info@MyWebsiteDomainName.com", "myIDPassword");\nsmtpClient.UseDefaultCredentials = true;\nsmtpClient.DeliveryMethod = SmtpDeliveryMethod.Network;\nsmtpClient.EnableSsl = true;\nMailMessage mail = new MailMessage();\n\n//Setting From , To and CC\nmail.From = new MailAddress("info@MyWebsiteDomainName", "MyWeb Site");\nmail.To.Add(new MailAddress("info@MyWebsiteDomainName"));\nmail.CC.Add(new MailAddress("MyEmailID@gmail.com"));\n\nsmtpClient.Send(mail);	0
5352508	5352411	Can't change text of control	label.Text = "some Text";\nUpdate();	0
19076597	19076527	Splitting number and string using linq	var str = "ahde7394";\n\nvar regex = Regex.Match(str, @"([a-zA-Z]+)(\d+)");\n\nvar letters = regex.Groups[1].Value; // ahde\nvar numbers = regex.Groups[2].Value; // 7394	0
7501014	7500956	Call an EventHandler from another Method	protected void CustomValidatorDelLN_ServerValidate(object sender, ServerValidateEventArgs args)\n    {\n\n        args.IsValid = isValid();\n    }\n\n\nprotected bool isValid()\n{\n\n    bool is_valid = txtDeliveryLastName.Text != "";\n        txtDeliveryLastName.BackColor = is_valid ? System.Drawing.Color.White : System.Drawing.Color.LightPink;\n    return is_valid;\n}	0
34366101	34360963	Button Image that has a glow effect	private void button1_MouseHover(object sender, EventArgs e)\n    {\n        button1.Image = Resources.glow_Check_mark_PNG;\n    }\n\n    private void button1_MouseLeave(object sender, EventArgs e)\n    {\n        button1.Image = Properties.Resources.checkmark_icon;\n    }	0
5934383	5934300	C# inserting <input> in htmldocument	HtmlElement input = doc.CreateElement("input");	0
4822901	4822478	WinForms Chart: How can I identify a DataPoint within the DragDrop event?	var pos = chart1.PointToClient(new Point(e.X, e.Y));\nHitTestResult testResult = chart1.HitTest(pos.X, pos.Y, ChartElementType.DataPoint);	0
7482778	898265	How to setup caption for DataGridView	private void DataGrid_AutoGeneratingColumn(object sender, DataGridAutoGeneratingColumnEventArgs e)\n{\n    var dGrid = (sender as DataGrid);\n    if (dGrid == null) return ;\n    var view = dGrid.ItemsSource as DataView;\n    if (view == null) return;\n    var table = view.Table;\n    e.Column.Header = table.Columns[e.Column.Header as String].Caption;\n}	0
15560937	15560722	Updating ListBox with new list values through using a method	public void Showinlistbox()\n    {      \n        // Add a  listBox named  listBox1 \n\n        // Add Score\n        score++;\n        CallRandomQuestion();    \n        //if you want mutual-exclusion lock add lock (listBox1) \n        listBox1.Items.Add(Alphabet);\n     }	0
2114087	672032	Fluent NHibernate, working with interfaces	References(x => x.Address, "AddressId")\n    .Class(typeof(Address);	0
33562313	33561139	UWP location tracking even when the app was suspended	BackgroundTaskBuilder geofenceTaskBuilder = new BackgroundTaskBuilder();\ngeofenceTaskBuilder.Name = SampleBackgroundTaskName;\ngeofenceTaskBuilder.TaskEntryPoint = SampleBackgroundTaskEntryPoint;\n\nvar trigger = new LocationTrigger(LocationTriggerType.Geofence);\n\ngeofenceTaskBuilder.SetTrigger(trigger);\n\n\n_geofenceTask = geofenceTaskBuilder.Register();\n//...and do the rest (but look into the sample..everything is from there...)	0
5966306	5966272	How to define the operator ==	public static bool operator ==(YourClassType a, YourClassType b)\n{\n    // do the comparison\n}	0
4312390	4312291	How to let my web-user-control determine automatically the url of the page where it's placed	NavigateUrl='<%#string.Format("{2}?ID={0}&Type={1}",\n     Eval("arrange_by_id"),Eval("value"), Page.ResolveUrl("~/Palyer.aspx"))%>'	0
24476445	24476326	How can i parse specific string using indexof and substring?	string start = "data-token=";\n  string end = " href";\n\n  string source = "<a class='bizLink' data-token='-iUzEhgdscgbpj5VMi5zoh54FTeFt8M4mj5nsiodxR5VzZOhniodpj6nFQg0nce3MhUxFSgdxjM4JjUVzZuNu8o0sREnFSUzISUXzZWh4iodGQfdxR5VzZWh4iodGQfhli6fnce_=1\" href='";\n\n  int firstTag = source.IndexOf(start);\n  int lastTag = source.IndexOf(end, firstTag );\n  int startIndex = firstTag + start.Length +1;\n  int endIndex = lastTag;\n  string authenticityToken = source.Substring(startIndex, endIndex - startIndex -1);\n  Console.Write(authenticityToken);\n  Console.ReadLine();	0
1525034	1524982	looping through xml in .net	private  void GetChartData(string OC_Ttl1, string OC_Ttl2, string OC_OL31)\n    {\n        OC_Ttl_1 = OC_Ttl1;\n        OC_Ttl_2 = OC_Ttl2;\n        OC_OL3_1 = OC_OL31;\n\n\n        //Execute Stored Procedure\n        SqlCommand cmd_Org.Connection = conn_Org;\n        cmd_Org.CommandText = "dbo.usp_CreateOrgDataSet";\n        cmd_Org.CommandType = CommandType.StoredProcedure;\n        cmd_Org.Parameters.AddWithValue("@OC_Ttl_1", OC_Ttl1);\n        cmd_Org.Parameters.AddWithValue("@OC_Ttl_2", OC_Ttl1);\n        cmd_Org.Parameters.AddWithValue("@OC_OL3_1", OC_OL31);\n\n\n        //Output xml\n        DataSet orgDataSet = new DataSet();\n        orgDataSet.ReadXml(cmd_Org.ExecuteXmlReader(), XmlReadMode.Auto);\n        orgDataSet.WriteXml("InputXMLFiles/" + OC_OL3_1.Replace(" ","_") + ".xml");\n\n\n\n\n\n    }	0
12514385	12513853	How to apply SQL query to a C# DataTable/Dataset?	DataTable.Select	0
26956835	26953581	How does the Graphics CopyFromScreen method copy into a bitmap?	using (var g = Graphics.FromImage(bmpScreenshot)) {\n      g.CopyFromScreen(0, 0, 0, 0, Screen.PrimaryScreen.Bounds.Size);\n      return bmpScreenshot;\n  }	0
15449236	15449214	Can I Use Variables from One Method to another?	public class MyClass\n{\n    // New instance field\n    private string _path = null;\n\n    private void OnBrowseFileClick(object sender, RoutedEventArgs e)\n    {\n        // Notice the use of the instance field\n        _path = OpenFile(); \n    }\n\n    // OpenFile implementation here...\n\n    private void btnCreateReport_Click(object sender, RoutedEventArgs e)\n    {\n        string filename = "st_NodataSet.xls"; //Dummy Data\n        string functionName = "functionName"; //Dummy Data\n\n        AnalyzerCore.ViewModel.ReportGeneratorVM reportGeneratorVM = new AnalyzerCore.ViewModel.ReportGeneratorVM();\n        // Reuse the instance field here\n        reportGeneratorVM.ReportGenerator(filename, functionName, _path); \n    }\n}	0
9963637	9928386	Custom Application child class in Mono for Android	public AcraApp (IntPtr javaReference, JniHandleOwnership transfer)\n    : base(javaReference, transfer)\n{\n}	0
9274167	9274021	Failing to assign a value to an enum	BitmapCacheOption bitmapCacheOption1 =\n            (BitmapCacheOption)Enum.Parse(typeof(BitmapCacheOption), x);	0
20626830	20626688	Inserting a text box dynamically	public void addToStackPanel(string argBuiltAlarm)\n{\n   //creating a stackpanel with orientation horizontal\n   StackPanel stackPanel=new StackPanel\n        {\n           Orientation =System.Windows.Controls.Orientation.Horizontal\n        };\n\n   TextBox textBox=new TextBox{ Text =  "your text"};\n\n   CheckBox checkQueries = new CheckBox() { Content = argBuiltAlarm };\n\n   stackPanel.Children.Add(checkQueries);\n   stackPanel.Children.Add(textBox);\n\n   //adding the stackpanel containing both checkbox & textbox to the stackPanel1\n   stackPanel1.Children.Add(stackPanel);\n\n   //remaining codes here\n\n }	0
28825692	28792870	Print usps Shipping Label	public Image Base64ToImage(string base64String)\n {\n  // Convert Base64 String to byte[]\n  byte[] imageBytes = Convert.FromBase64String(base64String);\n  MemoryStream ms = new MemoryStream(imageBytes, 0,imageBytes.Length);\n    // Convert byte[] to Image\n    ms.Write(imageBytes, 0, imageBytes.Length);\n    Image image = Image.FromStream(ms, true);\n    return image;\n  }	0
23430014	21373227	C# SelectVoice not changing in windows application but does in console	using System.Speech.Synthesis;\n\nvar synth=new SpeechSynthesizer();\nvar builder=new PromptBuilder();\nbuilder.StartVoice("Microsoft David Desktop");\nbuilder.AppendText("Hello, World!");\nbuilder.EndVoice();\nsynth.SpeakAsync(new Prompt(builder));	0
14904568	14904541	Extracting information that always follows a specific string	var regex = new Regex(@"DeltaT=""(.*?)""");\nforeach (Match m in regex.Matches(inputText))\n{\n    Console.WriteLine(m.Groups[1].Value);\n}	0
23718280	23718104	How to use String.Format specifier in an expression?	Console.WriteLine("Number of Gallons paint needed:\t{0:F2}", area/450.0);	0
18914985	18914811	Creating variable amount of threads	Parallel.ForEach(Process.GetProcessesByName(application_name),\n        (Process obj) =>\n        {\n            logyaz("Waiting for " + obj.ProcessName + " to exit at " + DateTime.Now);\n            obj.CloseMainWindow();\n            obj.WaitForExit(60000);\n        });	0
15434661	15434494	WinRT application login by pressing Enter key with MVVM light	Windows.UI.Xaml.Window.Current.CoreWindow.KeyDown += (sender, arg) =>\n        {\n            if (arg.VirtualKey == Windows.System.VirtualKey.Enter)\n            {\n                //Your login method\n            }\n\n        };	0
6829902	6829570	Set columns width in a datagrid using Compact Framework	dataGrid1.TableStyles.Clear();\nDataGridTableStyle tableStyle = new DataGridTableStyle();\ntableStyle.MappingName = t.TableName;\nforeach (DataColumn item in t.Columns)\n{\n    DataGridTextBoxColumn tbcName = new DataGridTextBoxColumn();\n    tbcName.Width = 100;\n    tbcName.MappingName = item.ColumnName;\n    tbcName.HeaderText = item.ColumnName;\n    tableStyle.GridColumnStyles.Add(tbcName);\n }\n dataGrid1.TableStyles.Add(tableStyle);	0
12986414	12986406	Index of inserted ListView item	flatListView1.Items.Add(name).SubItems.AddRange(row1);\nint index = flatListView1.Items.Count -1;	0
27407849	27403781	IMAP: Detecting all catch-all addresses that an email was sent to	if envelope "from" :is :domain "mailtjenester.no" {\n    redirect "brenden@telemeny.com";\n}	0
24313628	24313491	Saving the results of an SQL query to an Excel file on a button click	application/vnd.ms-excel	0
8175900	8175873	Returning a value from Database	[HttpPost]\n    public ActionResult InsertData(int? key)\n    {\n        var TestData = new Data();\n        DataContext.InsertData(TestData);\n\n        return Content(TestData.Key.ToString());\n    }	0
1349638	1349482	How do i launch a url in monodevelop c#?	Process.Start ("http://www.mono-project.com");	0
18387548	18387419	C# building permutations with wildcards using recursion	List<String> permutations(String original, int numberOfWildcards) {\n        //add 1 more wildcard to each posible position in the original string\n        List<String> perm = new List<String>();\n        for (int i = 0; i < original.Length; ++i)\n        {\n            if (original[i] != '_')\n                perm.Add(original.Substring(0, i) + "_" + original.Substring(i + 1, original.Length));\n        }\n        if ( numberOfWildcards == 1)\n        {\n              return perm;\n        }\n\n        //now if we need to search deeper we recusively do this for each substring\n        List<String> permWithMoreWildmark = new List<String>();\n        foreach (var str in perm)\n        {\n            permWithMoreWildmark.AddRange(permutations(str,numberOfWildcards-1));\n        }\n        return permWithMoreWildmark;\n    }	0
25898830	25898646	Loop and update object value in a collection using LINQ	public void WhatIfCalculation(string Product, string SiteID, List<DAL.OMS_StockStatus> prodStatus, List<PivotViewModel> activityInfo)\n{\n    var sff = activityInfo.Where(a => a.Activity == "System Forecast"); // Do this in the calling function >> .Where(a => a.SiteID == SiteID).ToList();\n\n    aSFF = new double?[sff.Count()];\n    for (var i = 0; i < sff.Count(); i++)\n    {\n        aSFF[i] = sff.ElementAt(i).Value + 1;\n    }\n\n    var prf = activityInfo.Where(a => a.Activity == "Planned Receipts");\n    aPRF = new double?[prf.Count()];\n    for (var i = 0; i < prf.Count(); i++)\n    {\n        aPRF[i] = prf.ElementAt(i).Value + 2;\n    }\n\n    // Will perform some calculation here. And then update back my collection.\n\n    for (var i = 0; i < aSFF.Length; i++)\n    {\n        sff.ElementAt(i).Value = aSFF[i];\n    }\n\n    for (var i = 0; i < aPRF.Length; i++)\n    {\n        prf.ElementAt(i).Value = aPRF[i];\n    }\n}	0
14842849	14842693	How to link the TableAdapter to my Project?	public void button_login_Click(object sender, EventArgs e)\n{\n     ReadersTableAdapter rdrsTblAdapter = new ReadersTableAdapter();\n     rdrsTblAdapter.GetBy();\n     rdrsTblAdapter.FilBy();\n}	0
27269729	27269474	How to implement inheritance with multiple sub objects .net	public class NewService<T> : BaseService<T>\n{\n    private readonly FooService<T> _fooService;\n    private readonly AuditableService<T> _auditableService;\n    public NewService (AuditableService<T> auditableService, FooService<T> fooService)\n    {\n        if(auditableService  == null)\n            throw new ArgumentNullException("auditableService ");\n\n        if(fooService == null)\n            throw new ArgumentNullException("fooService");\n\n        _auditableService = auditableService;\n        _fooService = fooService;\n    }\n\n    public override Task<int> AddAsync(T t)\n    {\n         return _fooService.UpdateAsync(t);\n    }\n\n    public override Task<int> DeleteAsync(T t)\n    {\n         return _auditableService.DeleteAsync(t);\n    }\n}	0
6074859	6015726	How to search AD Global Caalogue rather than Domain Controller?	GC://<url> to LDAP://<ur>	0
7270228	7270187	How do I display a property from a child element in a ListBox bound with ItemsSource?	DisplayMemberPath="Name"	0
13353296	13352896	Split string by capital letters (excluding hyphenated words)	using System;\nusing System.Text;\n\nnamespace SplitOnUppercase\n{\n    class Program\n    {\n        static void Main()\n        {\n            const string text = "Test42-10 UltraCorrosion-ResistantCoated Alloy-SteelNumberTest42";\n            var result = new StringBuilder(text.Length);\n            for (var i = 0; i < text.Length - 1; i++)\n            {\n                result.Append(text[i]);\n                if (text[i] != ' ' && text[i] != '-' && (char.IsUpper(text[i + 1]) || !char.IsDigit(text[i]) && char.IsDigit(text[i + 1])))\n                    result.Append(' ');\n            }\n            result.Append(text[text.Length - 1]);\n\n            Console.WriteLine(result);\n        }\n    }\n}	0
11724021	11721864	Routing in WCF REST with hierarchical resources	/Chapters/{ChapterID}?Book={BookID}	0
28719644	28719512	Can't change datagrid text alignment (devexpress grid control)	gdData.Columns[2].AppearanceCell.Options.UseTextOptions = true;\ngdData.Columns[2].AppearanceCell.TextOptions.HAlignment = DevExpress.Utils.HorzAlignment.Center;	0
8912797	8912232	Get instance name of local sql server	using Microsoft.SqlServer.Management.Smo.Wmi;\n....\n\nManagedComputer mc = new ManagedComputer();\n\nforeach (ServerInstance si in mc.ServerInstances)\n{\n     Console.WriteLine("The installed instance name is " + si.Name);\n}	0
11105299	11105262	How to know if a form is shown as dialog	this.Modal	0
32983563	32983424	SUM values from a table and subtract it to a SUM of values from another table having the same IDs	"SELECT inventory_tbl.product_id As 'Product ID', SUM(inventory_tbl.quantity) - SUM(withdrawal_tbl.quantity), SUM(inventory_tbl.total) - SUM(withdrawal_tbl.total) \nFROM withdrawal_tbl inner join inventory_tbl on inventory_tbl.product_id = withdrawal_tbl.product_id  GROUP BY inventory_tbl.product_id"	0
18888193	18888026	Add/set title of an <li> element	test1.Attributes["title"] = "hello";\ntest2.Attributes["title"] = "juhu";	0
15246941	15246689	How to pass parameter from C# code to JavaScript?	clientStageCommand = new ClientStepCommand\n{\n    CommandType = ClientStageCommandType.Eval,\n    Argument = string.Format(@"WelcomeMessageMaster(""{0}"")", this.Grid.UniqueID)\n};	0
1794934	1794920	C# Conversion of lambda expression	// The underscore is simply a placeholder for the "state"\n// parameter that the WaitCallback delegate expects - you could\n// use any character but you must specify one as lamba expressions cannot\n// omit parameters like anonymous functions can.\nThreadPool.QueueUserWorkItem((_) =>\n    {\n    Console.WriteLine("Current Thread Id is {0}:",\n    Thread.CurrentThread.ManagedThreadId);\n    Console.WriteLine("I will be used as Callback");\n    });	0
33727568	33726247	How do I return value to main from Button_Click	public partial class MainWindow : Window\n    {\n        public MainWindow()\n        {\n            InitializeComponent();\n        }\n\n        private void Button_Click(object sender, RoutedEventArgs e)\n        {\n            var dialog = new System.Windows.Forms.FolderBrowserDialog();\n            System.Windows.Forms.DialogResult result = dialog.ShowDialog();\n            ProcessFolderLocation(dialog.SelectedPath);\n        }\n\n        private void ProcessFolderLocation(string location)\n        {\n            // ... Do something with your selected folder location\n        }\n    }	0
19874330	19873852	How to split a text file by a given separator in c#	foreach (string line in File.ReadAllLines(Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + "\\ArchivoaSeparar.txt"))\n            {\n                String checkItem = cadenaTextBox.Text.ToString();\n                string[] parts = line.Split(checkItem.ToCharArray());\n\n                foreach (string item in parts)\n                {\n                    listBox1.Items.Add((line.Contains(checkItem) ? item + checkItem : item));\n                }\n            }	0
21636524	21636362	Convert Bracket (negative) to double	// using System.Globalization\ndouble d = double.Parse("(1,000.90)", NumberStyles.AllowParentheses | \n                                      NumberStyles.AllowThousands | \n                                      NumberStyles.AllowDecimalPoint)\n\n/* d = -1000.9 */	0
232444	232395	How do I sort a two-dimensional array in C#?	// assumes stringdata[row, col] is your 2D string array\nDataTable dt = new DataTable();\n// assumes first row contains column names:\nfor (int col = 0; col < stringdata.GetLength(1); col++)\n{\n    dt.Columns.Add(stringdata[0, col]);\n}\n// load data from string array to data table:\nfor (rowindex = 1; rowindex < stringdata.GetLength(0); rowindex++)\n{\n    DataRow row = dt.NewRow();\n    for (int col = 0; col < stringdata.GetLength(1); col++)\n    {\n        row[col] = stringdata[rowindex, col];\n    }\n    dt.Rows.Add(row);\n}\n// sort by third column:\nDataRow[] sortedrows = dt.Select("", "3");\n// sort by column name, descending:\nsortedrows = dt.Select("", "COLUMN3 DESC");	0
25098394	25098032	How to check if FormView is empty from code behind	protected void FormView1_DataBound(object sender, EventArgs e) {\n        if (FormView1.DataItemCount == 0) {\n        }\n        else {\n        }\n    }	0
3982307	3982287	How do you convert a DataSet/DataTable into a generic list of certain type?	var list = (from dr in dt.AsEnumerable()\n           select new Property { .... }).ToList();	0
10596298	10595551	Can't deserialize XML to object	[DataContract]\npublic class CreateSubscribersResultCollection : RequestBase\n{\n    [XmlArray("CreatedSubscriberIds")]\n    [XmlArrayItem(typeof(long), Namespace="http://schemas.microsoft.com/2003/10/Serialization/Arrays")]\n    public List<long> CreatedSubscriberIds { get; set; }\n\n    [XmlElement("FailedCreatedSubscribers")]\n    public string FailedCreatedSubscribers { get; set; }\n}	0
13480494	13477376	Filter RadGrid results and store into a new datatable	if (e.CommandName == "Filter")\n     {\n        DataTable dt = new DataTable();\n        td.Columns.Add("Column1");\n        td.Columns.Add("Column2");\n        //etc.\n        //add same columns as you have in RadGrid2\n\n        foreach (GridDataItem item in RadGrid2.Items)\n        {\n\n            for (int i = 0; i < RadGrid2.Items.Count; i++ )\n            {\n\n                dt.Rows.Add(item);\n            }\n        }	0
29903719	29903285	WPF: binding based on column index	public class MyDataGridTextColumn :DataGridTextColumn \n{\n   public int ColumnIndex {get;private set;}\n\n   public MyDataGridTextColumn (int columnIndex)\n   {\n       ColumnIndex = columnIndex;\n   }\n}	0
3698928	3698731	How to terminate a worker thread correctly in c#	private ManualResetEvent _event = new ManualResetEvent(false);\n\n\npublic void Run() \n{\n while (true)\n {\n    DoSomethingThatTakesSeveralSeconds();\n    if (_event.WaitOne(timeout))\n      break;\n }\n}\n\npublic void Stop() \n{\n   _event.Set();\n   thread.Join();\n}	0
30003691	30003630	Modify a specific line in a text file	string old = "old string";\nstring nw =" new string";\nint counter = 0;\n\n    Using(StreamWriter w =new StreamWriter("newfile");\n    foreach(string s in File.ReadLines(path))\n    {\n        if (s = old) \n        {\n              w. WriteLine(nw);\n        }\n        else\n        {\n              w. WriteLine(s);\n        } \n        counter ++;\n    }	0
24824901	24824824	c# split string value by numeric	string[] result = value.Replace("10", "1,0").Replace("01", "0,1").Split(',');	0
9831370	9830977	Get Active Directory User Context from AD username string - use with IsInRole()	WindowsPrincipal pFoo = new WindowsPrincipal(new WindowsIdentity("domain\user"));	0
3253533	3236202	Inserting value at a specific position using sqlserver 2005	int startIndex = test.LastIndexOf(",|1");  \nstring insert = test.Insert(startIndex, ",color");  \nSqlCommand cmd = new SqlCommand("update tableName set value='" + insert + "' where Id='1'", con);  \ncmd.ExecuteNonQuery();	0
4909180	4907099	Silverlight app for select windows users	Application.Current.IsRunningOutOfBrowser	0
33835510	33835441	Regex to match the first letter in a word ONLY	Regex regex = new Regex(@"^(x|y|z).+$");	0
9012969	9012703	Passing by reference, a member, of an object in a generic collection being accessed by indexer	Deque<Card> deck_of_cards = new Deque<Card>();  // standard deck of 52 playing cards\nvar tmp = deck_of_cards[4];\nModifyRank( ref tmp.rank, 8);  // Changes the rank (int) of the 5th card to 8\ndeck_of_cards[4] = tmp;	0
6883949	6883932	Getting selected value of listbox windows phone 7	if(null != listBox.SelectedItem)\n{\n    string text = (listBox.SelectedItem as ListBoxItem).Content.ToString();\n}	0
6526763	6526567	How to populate a Grid programatically in Silverlight?	Grid holdingGrid = new Grid();\nint row = 0;\n\nfor (int i = 0; i < 10; i++) {\n   Expander expander = new Expander();\n   holdingGrid.RowDefinitions.Add(new RowDefinition());\n   holdingGrid.Children.Add(expander);\n   Grid.SetRow(expander, row);\n   Grid.SetColumn(expander, 0);\n   row++;\n}	0
32511823	32500025	Find pixel size of a glyph in WPF	var size = typeface.GetGlyphOutline(charIndex, emSize, 0d).Bounds.Size;	0
1927785	1927770	Setting Far Future Expires Header In Code - ASP.NET	context.Response.Cache.SetMaxAge(TimeSpan.FromDays(365.));	0
23323429	23321975	Notify user if he enters a value into the Textbox which is not allowed in WPF	private void OnPreviewTextInput(object sender, System.Windows.Input.TextCompositionEventArgs e)\n    {\n        e.Handled = !IsValid(e.Text, false);\n        if(e.Handled)\n        {\n            var be = BindingOperations.GetBindingExpression(AssociatedObject, TextBox.TextProperty);\n            Validation.MarkInvalid(be, new ValidationError(new DummyValidationRule(), be.ParentBinding));\n        }\n    }\n\n    private class DummyValidationRule : ValidationRule\n    {\n\n        public override ValidationResult Validate(object value, System.Globalization.CultureInfo cultureInfo)\n        {\n            return new ValidationResult(false, "ErrorMessage");\n        }\n    }	0
13526337	13193374	Outlook Mapi access shared contacts	Recipient recip = Application.Session.CreateRecipient("Firstname Lastname");\nMAPIFolder sharedContactFolder = Application.Session.GetSharedDefaultFolder(recip, OlDefaultFolders.olFolderContacts);	0
17091901	17089697	ShareLinkTask, check if a user has connected to a network	(new Contacts()).Accounts	0
25425326	25425216	Encryped sql connction info in webconfig	aspnet_regiis.exe	0
13210137	13209742	Inheritance - change variable upon initialization based on child value	public class Tile\n{\n    private string _texturePath = String.Empty;\n    private Texture2D _texture;\n    protected virtual string TexturePath { private get { return _texturePath; } set { _texturePath = value; } }\n\n    public Tile()\n    {\n        if (!string.IsNullOrWhiteSpace(TexturePath))\n            _texture = LoadTexture(TexturePath);\n    }\n    private Texture2D LoadTexture(string texturePath)\n    {\n        throw new NotImplementedException();\n    }\n}\n\ninternal class Texture2D\n{\n}\n\npublic sealed class Free:Tile\n{\n    protected override string TexturePath\n    {\n        set\n        {\n            if (value == null) throw new ArgumentNullException("value");\n            base.TexturePath = "Content/wall.png";\n        }\n    }\n}	0
3087942	3087891	How can I move an XML element above the previous element using LINQ to XML?	static void MoveElementUp(XElement element)\n{\n    // Walk backwards until we find an element - ignore text nodes\n    XNode previousNode = element.PreviousNode;\n    while (previousNode != null && !(previousNode is XElement))\n    {\n        previousNode = previousNode.PreviousNode;\n    }\n    if (previousNode == null)\n    {\n        throw new ArgumentException("Nowhere to move element to!");\n    }\n    element.Remove();\n    previousNode.AddBeforeSelf(element);\n}	0
13363415	13325808	Getting dependencies between assemblies programatically by NDepend APIs	from m in Assemblies.WithNameIn( "mscorlib").ChildMethods()\nwhere m.IsUsedBy ("pnunit-launcher")\nselect new { m, m.NbLinesOfCode }\n//--------------------------------------------------------------------\n// 52 methods of the assembly\n// mscorlib\n// v4.0.0.0\n// \n// are used by\n// 24 methods of the assembly\n// pnunit-launcher\n// v1.0.4661.29691\n//	0
19564519	19564446	Extract substring from a string having specific set of characters in c#	var s = @"<span id=""lblEnt"" class=""selected"">Enterprise</span>\n<span id=""lblDept"" class=""selected"">Department</span>";\n\nvar t = Regex.Replace(s, @"<[^>]+>", "");	0
4670729	3447589	Copying Http Request InputStream	Stream webStream = null;\n\ntry\n{\n    //copy incoming request body to outgoing request\n    if (requestStream != null && requestStream.Length>0)\n    {\n        long length = requestStream.Length;\n        webRequest.ContentLength = length;\n        webStream = webRequest.GetRequestStream();\n        requestStream.CopyTo(webStream);\n    }\n}\nfinally\n{\n    if (null != webStream)\n    {\n        webStream.Flush();\n        webStream.Close();    // might need additional exception handling here\n    }\n}\n\n// No more ProtocolViolationException!\nusing (HttpWebResponse response = (HttpWebResponse)webRequest.GetResponse())\n{\n    ...\n}	0
10349540	10349324	From Date and To Date From Previous Weeks	static void Main(string[] args)\n        {\n            Console.WriteLine("Enter week number");\n            int week = int.Parse(Console.ReadLine());\n            var weekStartDay = DayOfWeek.Monday;\n            int daysInAWeek = 7;\n            DateTime thisWeekStarttingDate = DateTime.Now.Subtract(new TimeSpan((int)DateTime.Now.DayOfWeek - (int)weekStartDay, 0, 0, 0)).Date;\n\n            DateTime fromDate = thisWeekStarttingDate.Subtract(new TimeSpan(daysInAWeek * week, 0, 0, 0));\n            DateTime toDate = fromDate.AddDays(daysInAWeek-1);\n\n            Console.WriteLine("from date:" + fromDate.ToShortDateString());\n            Console.WriteLine("to date:" + toDate.ToShortDateString());\n            Console.ReadKey();\n        }	0
1337507	1337296	Creating all objects using reflection of an object properties!	var properties = item.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance);\n            List<Address> retVal;\n            foreach (var property in properties)\n            {\n                var propertyType = property.PropertyType;\n                if (!propertyType.IsGenericType) continue;\n\n\n                retVal = property.GetValue(item, new object[] { }) as List<Address>;\n\n                if (retVal != null)\n                    break;\n            }\n\n            //now you have your List<Address> in retVal	0
15275069	15253259	SetBinding() on Custom Image Control	partial void VidContentItemsGrid_Activated() {\n  int index = 0;\n  foreach (var item in this.VidContentItems) {\n    if (item.Active == false) {\n      this.FindControlInCollection("TrueIconInd", this.VidContentItems.ElementAt(index)).IsVisible = false;\n    }\n    index++;\n  }\n}	0
26381747	26381656	Share a dictionary within a C# windows form	Dictionary<string, marketdata> dataMap;\nprivate void button4_Click(object sender, EventArgs e) \n{\n    loadXL myMap = new loadXL();\n    dataMap = myMap.myDataLoader(Convert.ToDateTime(AsOfDate.Text),Convert.ToDouble(Underlying.Text));\n}\n\nprivate void function()\n{\n\n    dataMap.//\n}	0
2005041	2004855	How to iterate through set of custom control objects in WPF?	private IEnumerable<MyCustControl> FindMyCustControl(DependencyObject root)\n{\n    int count = VisualTreeHelper.GetChildrenCount(root);\n    for (int i = 0; i < count; ++i)\n    {\n        DependencyObject child = VisualTreeHelper.GetChild(root, i);\n        if (child is MyCustControl)\n        {\n            yield return (MyCustControl)child;\n        }\n        else\n        {\n            foreach (MyCustControl found in FindMyCustControl(child))\n            {\n                yield return found;\n            }\n        }\n    }\n}	0
18929536	18928809	Click Button - No Action	OnClick="btnDisplay_Click"	0
645549	645518	How can I hide a panel that is on a SplitContainer?	splitContainer1.Panel2Collapsed = true;\nsplitContainer1.Panel2.Hide();	0
12494745	12494654	Compare Row Count & Count in a dataset	var allCount = (from row in odt.AsEnumerable() select row).Count(); //Count all rows\n\nvar specificCount = (from row in odt.AsEnumerable() select row.Field<string>("FILE_ID")).Distinct().Count();	0
20413229	20413125	Regular expressions in C# for extracting parts	"((?:[A-Za-z0-9\-]+)/NNS :/: (?:[A-Za-z0-9\-/s]+))"	0
1906402	1906391	regular expression to reject non-alphanumeric characters	string s = Regex.Replace(InputString.Trim(),@"[^A-Za-z0-9]+","");	0
13977030	13976221	Query to return pairs of related rows, but only when both rows exist	WITH TempTable AS \n( \n    select distinct a.id, b.idIndice, b.valor  \n    from tgpwebged.dbo.sistema_Documentos as a  \n        join tgpwebged.dbo.sistema_Indexacao as b on a.id = b.idDocumento \n    join tgpwebged.dbo.sistema_DocType as c on a.idDocType = c.id\n    join tgpwebged.dbo.sistema_DocType_Index as d on c.id = d.docTypeId \n    where d.docTypeId = 40      \n        and (b.idIndice = 11 AND b.valor = '11111111' OR b.idIndice = 12 AND b.valor = '22222' ) \n)\n\nSELECT *  \nFROM TempTable t1 \nWHERE (select count(*)          \n       from TempTable t2        \n       where t1.id = t2.id AND t1.valor != t2.valor) = 1	0
7121666	7121288	How to add a special item to a listview and keep it at the top?	private void Sort(string sortBy, ListSortDirection direction)\n{\n    ICollectionView dataView = CollectionViewSource.GetDefaultView(this.ItemsSource);\n\n    if (dataView != null)\n    {\n        dataView.SortDescriptions.Clear();\n\n        dataView.SortDescriptions.Add(new SortDescription("IsAtTop", ListSortDirection.Ascending));\n        SortDescription sd = new SortDescription(sortBy, direction);\n        dataView.SortDescriptions.Add(sd);\n        dataView.Refresh();\n    }\n}	0
13865131	13865022	How do I remove the Where condition of my lambda expression?	var query = duplicates.SelectMany(c => c).AsQueryable();	0
5683127	5677144	Insert row in DB while using multithreads?	public class PostService\n{ \n    public void callthreads()\n    {\n        for (int i = 0; i < 100; i++)\n        {\n            Thread th = new Thread(postingProcess);\n            th.Start();\n        }\n    }\n\n    public void postingProcess()\n    {\n        using (MessageRepository objFbPostRespository = new MessageRepository())\n        {\n           objFbPostRespository.AddLog("Test Multithread", DateTime.Now);\n        }\n    }\n}	0
18232537	18232508	how to access method of parent class with instance of child class in c#	Child ch = new Child();\nvar parent = (Parent)ch;\nparent.sleep();	0
4599830	4599681	SQLite issues, escaping certain characters	SQLiteCommand Command = "UPDATE SUBCONTRACTOR SET JobSite = NULL WHERE JobSite = @JobSite";\nCommand.Parameters.Add(new SQLiteParameter("@JobSite", JobSiteVariable));\ncommand.ExecuteNonQuery();	0
12855520	12799196	ServicePoint.Expect100Continue for Windows Store Apps	using (HttpClient client = new HttpClient())\n {\n      client.DefaultRequestHeaders.ExpectContinue = false;\n\n      ....code!\n }	0
22308830	22308475	How can I find the decorated method from within a custom attribute?	var actionName = filterContext.ActionDescriptor.ActionName	0
29845446	29842226	String was not recognized as valid Datetime after converting Db from MSSQL to SQLite	String query = "INSERT INTO TableName(DateColumn) VALUES (CONVERT(Date, @DateValue, 103)"; // 103 is this format: dd/mm/yyyy\nSqlParameter DateParam = new SqlParameter("@Invoice_Date", System.Data.DbType.Char, 10);\nDateParam.Value = dateTimePicker1.Value.ToString("dd/MM/yyyy");\nicommand.Parameters.Add(DateParam);	0
12239265	12238966	itextsharp image with hyperlink	Chunk cImage = new Chunk(yourImage, 0, 0, false); \nAnchor anchor = new Anchor(cImage); \nanchor.Reference = "www.yourAddress.com"; \ndocument.Add(anchor);	0
23272820	23270900	Upload a file in a directory using C# allow to view it	public PictureDisplay()\n{\n    InitializeComponent();\n}\n\nprivate void btnBrowse_Click(object sender, EventArgs e)\n{\n    OpenFileDialog newDialog = new OpenFileDialog();\n    if (newDialog.ShowDialog() == DialogResult.OK)\n    {\n        try\n        {\n            picBoxDisplay.Load(newDialog.FileName);\n            picBoxDisplay.SizeMode = PictureBoxSizeMode.Zoom;\n        }\n        catch\n        {\n            MessageBox.Show("Wrong file type!", "Error");\n        }\n    }\n}	0
13529925	13529798	How do I load a typelib to parse it in C#?	[DllImport("oleaut32.dll", PreserveSig=false)]\npublic static extern ITypeLib LoadTypeLib([In, MarshalAs(UnmanagedType.LPWStr)] string typelib);	0
13916026	13915897	How to Skip HttpWebResponse 404	for (int i=1; i < 1000; i++)\n{\n    string id = i.ToString();\n    try\n    {\n         string url_source = get_url_source("http://mysite.com/"+id);\n    }\n    catch(WebException ex)\n    {\n        HttpWebResponse webResponse = (HttpWebResponse)ex.Response;          \n        if (webResponse.StatusCode == HttpStatusCode.NotFound)\n        {\n            continue;\n        }\n        else\n        {\n            throw;\n        }\n    }\n\n}	0
12301212	12300744	A function to convert null to string	static string NullToString( object Value )\n{\n\n    // Value.ToString() allows for Value being DBNull, but will also convert int, double, etc.\n    return Value == null ? "" : Value.ToString();\n\n    // If this is not what you want then this form may suit you better, handles 'Null' and DBNull otherwise tries a straight cast\n    // which will throw if Value isn't actually a string object.\n    //return Value == null || Value == DBNull.Value ? "" : (string)Value;\n\n\n}	0
14993429	14993021	How to connect data base and insert data	cmd.Parameters.Add("p1", OleDbType.Char).Value = MemoDate ;	0
34093899	34093691	How can I add a where clause to an in included entity in EF?	var customer = db.tbl_Person\n    .Include(t => t.tbl_Customer.tbl_Address)\n    .Where(t => t.VendorID == person.VendorID &&\n                t.FirstName == person.FirstName &&\n                t.LastName == person.LastName)\n    .ToList()\n    .Where(t => t.tbl_Customer?.tbl_Address != null &&\n                t.tbl_Customer.tbl_Address.State == address.State &&\n                t.tbl_Customer.tbl_Address.City == address.City).ToList();	0
32919468	32919429	How can I set up my model to perform this transaction?	var score = new Score { name = nsp.name, score1 = nsp.score };\n  SD.Scores.ADD(score);\n  db.savechanges();\n  var id = score .Id;	0
9935330	9935263	How do I determine the sender of an email via Exchange Web Services in C#?	findResults = exchangeService.FindItems(folder.Id, messageFilter, view);\n            foreach (Item item in findResults)\n            {\n                if (item is EmailMessage)\n                {\n                    EmailMessage message;\n                    if (!toFromDetails)\n                        message = (EmailMessage)item;\n                    else\n                        message = EmailMessage.Bind(exchangeService, item.Id);	0
4196974	4196952	How to create a CSV string from a Generic List<T>	string list = "";\nforeach (ReportCriteriaItem item in GetCurrentSelection(...)) {\n    if (!string.IsNullOrEmpty(list)) list += ",";\n    list += item.???;\n}\n// do something with the list.	0
4137184	4137142	c# saving an image of a control	chart1.SaveImage(ms, ChartImageFormat.Bmp);\nBitmap bm = new Bitmap(ms);\n\nSaveFileDialog saveFileDialog1 = new SaveFileDialog(); \nsaveFileDialog1.InitialDirectory = Environment.SpecialFolder.MyDocuments; \nsaveFileDialog1.Filter = "Your extension here (*.bmp)|*.*" ; \nsaveFileDialog1.FilterIndex = 1; \n\nif(saveFileDialog1.ShowDialog() == DialogResult.OK) \n{ \n        bm.Save (saveFileDialog1.FileName);//Do what you want here\n}	0
30991089	30971237	Running powershell with C#	List<DomainControllerLists> dcList = new List<DomainControllerLists>();\n        using (PowerShell inst = PowerShell.Create())\n        {\n            inst.AddCommand("Import-Module").AddParameter("Name", "ActiveDirectory");\n            inst.AddScript(command);\n            Collection<PSObject> results = inst.Invoke();\n            foreach (PSObject obj in results)\n            {\n                dcList.Add(new DomainControllerLists() { Name = obj.Members["Name"].Value.ToString(), OperatingSystem = obj.Members["OperatingSystem"].Value.ToString(), OperatingSystemServicePack = obj.Members["OperatingSystemServicePack"].Value.ToString(), Site = obj.Members["Site"].Value.ToString() });\n            }\n        }\n        return dcList;	0
20151828	20151556	How to Get the HTTP Post data in C#?	string[] keys = Request.Form.AllKeys;\nfor (int i= 0; i < keys.Length; i++) \n{\n   Response.Write(keys[i] + ": " + Request.Form[keys[i]] + "<br>");\n}	0
6263183	6263134	Setting a value to a variable from another class	class SomeClass\n{\n\n  public int comboindex\n  {\n    get; set;\n  }\n\n}\n\nSomeClass c = new SomeClass();\n\nc.comboindex = mycombo.selectedindex;	0
22595153	22595134	Implementing string variables from an interface	public string FilterGridId\n{\n   get { return _WrappedHelper.FilterGridId; }\n}\n\npublic string Id\n{\n   get { return _WrappedHelper.Id; }\n}\n\npublic string PagerId\n{\n   get { return _WrappedHelper.PagerId; }\n}	0
22322977	22322558	Handling commands in WPF application without window	CommandManager.RegisterClassCommandBinding(typeof(Popup), aboutBinding);\nCommandManager.RegisterClassCommandBinding(typeof(Popup), exitBinding);	0
3616461	3616444	Ternary operator in foreach	foreach (String control in controls)\n{\n if(control.Equals(String.Empty))\n      continue;\n // Do some stuff\n foreach (Int32 someStuff in moreStuff)\n {\n  if(someStuff.Equals(0))\n      continue;\n  // More stuff\n }\n}	0
7159624	7159530	Backup Files in use by another Process	FileStream fStream = new FileStream(FileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);\nStreamReader FileReader = new StreamReader(fStream, Encoding.UTF8);	0
24729476	24729202	How to disable Spacebar in a TextBox C#	private void InfoSend_Click(object sender, EventArgs e)\n{\n    System.Threading.Thread.Sleep(3000);\n    input_info = input_info.Replace(" ", string.Empty);\n    SendKeys.Send(input_info);\n}	0
13473931	13473777	How to download memoryStream file	byte[] bytes = memoryStream.GetBuffer();\nResponse.Buffer = true;\nResponse.Clear();\nResponse.ContentType = "application/pdf";\nResponse.AddHeader("content-disposition", "attachment; filename=report.pdf");\nResponse.BinaryWrite(bytes);\nResponse.Flush();	0
22111678	22111157	Unable To Fetch Records From SQL Table To DataGridView In C#	string sql = "SELECT * FROM Customers "\nstring condition = String.Empty;\n\nif(!String.IsNullOrEmpty(txtFullName.Text))\n  condition  += "WHERE ContactName LIKE '%" + txtFullName.Text + "%' "\n\nif(!String.IsNullOrEmpty(txtAddress.Text))\n  if(!String.IsNullOrEmpty(condition))\n     condition  += "OR Address LIKE '%" + txtAddress.Text + " %' "\n  else\n     condition  += "WHERE Address LIKE '%" + txtAddress.Text + " %' " \n\n//and so on....\n\n\nsql = sql + condition;\nSqlCommand cmd = new SqlCommand(sql, con);	0
9635552	9635214	How can I implement a Bitboard in VB.NET?	'Create bit array to store white rooks\nDim whiteRooks As New BitArray(64)\n\n'Set white rooks at initial position\nwhiteRooks(0) = True 'Corresponds to A1 on chess board\nwhiteRooks(56) = True 'Corresponds to H1 on chess board	0
5641074	5641047	Override the enter key, but keep default behavior for other keys in a wpf datagrid	base.OnKeyDown(sender, args);	0
29393531	29392980	using linq on datatable and putting result back into datatable with same format	newtable2 = ADataTable.AsEnumerable().GroupBy(a => new\n{\n    PLANT = a.Field<int>("PLANT"),\n    PDCATYPE_NAME = a.Field<int>("PDCATYPE_NAME"),\n    Month = a.Field<int>("Month"),\n    Year = a.Field<int>("Year"),\n    STATUS_NAME_REPORT = a.Field<string>("STATUS_NAME_REPORT")\n}).Select(g =>\n{\n    var row = newtable2.NewRow();\n    row.ItemArray = new object[]\n            {\n                g.Key.PLANT, \n                g.Key.PDCATYPE_NAME,\n                g.Key.Month,\n                g.Key.Year,\n                g.Key.STATUS_NAME_REPORT,\n                g.Sum(r => r.Field<double>("SAVINGS_PER_MONTH"))\n            };\n    return row;\n}).CopyToDataTable();	0
7554950	7553855	Accessing forms from different locations in WPF	Application.Current.Windows	0
11180942	11180905	Generic T in method parameter in C#	public static List<string> ItemsOfEnum<typeT>()\n        where typeT: struct, IComparable, IFormattable, IConvertible {\n    List<string> items = new List<string>();\n    foreach (typeT tItem in Enum.GetValues(typeof(typeT)))\n       items.Add(tItem.ToString());\n    return items;\n}	0
19410693	19408505	Tile Creation Fails even though Application is in Foreground	Dispatcher.BeginInvoke(()=>{\nShellTile TileToFind = ShellTile.ActiveTiles.FirstOrDefault(x => x.NavigationUri.ToString().Contains("any string of uri or search for unique prop"));\nif (TileToFind == null)\n{\n   ShellTile.Create(Navi_Uri , tileData, true);\n   MessageBox.Show("Tile is created.");\n}\nelse\n{\n   TileToFind.Update(tileData);\n   MessageBox.Show("Tile is updated");\n}});	0
23570241	23569917	How to display search results on a separate page	//1) On the source page with the search box, you would redirect the user \n//     to the search results page and append the search query to the URL: \nResponse.Redirect("search.aspx?search=" + HttpUtility.UrlEncode(query));\n\n//2) On the search results page, parse the query string values\nString searchQuery = Request.QueryString["search"];\n\n//3) Perform your search action in code and display the results.\nprotected void btnSubmit_Click(object sender, EventArgs e){\n    //your search code\n    using (ELibraryEntities entities = new ELibraryEntities())\n    {\n        var search = from books in entities.Reviews\n                where books.Title.Contains(searchQuery)\n                select books;\n        ListView1.DataSource = search;\n        ListView1.DataBind();\n    }\n}	0
32749068	32748992	How to get all <asp:Label> controls within an HTML Table?	for (int i = 0 ; i < length; i++) \n{\n     Label ans = FindControl(string.Format("lbl{0}",i)) as Label ;\n          if (ans!=null) and.Text = myVariable\n\n}	0
3782324	3782299	Strange syntax behavior in C#	int i=0; // that's one statement\n; // that's another	0
13787243	13787191	Ordering 2 list's elements, according to 1 list's elements	List<int> timeStamp = new List<int>();\nList<string> ownerStamp = new List<string>();\n\nint[] timeStampArray = timeStamp.ToArray();\nstring[] ownerStampArray = ownerStamp.ToArray();\n\nArray.Sort(timeStampArray, ownerStampArray);\n\ntimeStamp = new List<int>(timeStampArray);\nownerStamp = new List<string>(ownerStampArray);	0
23941705	23941645	How to use managed variable as global in Visual C++?	gcroot<Namespace::Something^> MyClass2::var;	0
31033535	31014679	DatetimePicker.Value Property Changes After Setting MaxDate	private void Models_Load(object sender, EventArgs e)\n{\n    DateTime dtNow = new DateTime();\n    dtNow = dateTimePicker1.Value;\n    dateTimePicker1.MaxDate = DateTime.Now;\n    dateTimePicker1.Value = dtNow;\n}	0
4426066	4425882	C# Registry (How to remove spacing between letters from array)?	static void Main(string[] args)\n    {\n        try\n        {\n            RegistryKey rk = Registry.CurrentUser;\n            rk = rk.OpenSubKey(@"Software\Microsoft\Windows\CurrentVersion\Explorer\ComDlg32\LastVisitedMRU", false);\n            PrintKeys(rk);\n        }\n\n        catch (Exception ex)\n        {\n            Console.WriteLine("An error has occurred: " + ex.Message);\n        }\n    }\n\n    static void PrintKeys(RegistryKey rk)\n    {\n        if (rk == null)\n        {\n            Console.WriteLine("No specified registry key!");\n            return;\n        }\n\n        foreach (String s in rk.GetValueNames())\n        {\n            if (s == "MRUList")\n            {\n                continue;\n            }\n            Byte[] byteValue = (Byte[])rk.GetValue(s);\n\n            UnicodeEncoding unicode = new UnicodeEncoding();\n            string val = unicode.GetString(byteValue);\n\n            Console.Out.WriteLine(val);\n        }\n        Console.ReadLine();\n    }	0
20468252	20468082	Interface inheritance and abstract method overriding	internal class Concrete : Base<ChildThing>\n{\n    public override IBaseThing<ChildThing> Thing\n    {\n        get { return ChildThing; }\n    }\n\n    public IChildThing ChildThing { get; set; }\n}	0
11850577	11841676	Changing name of Message Part element	[ServiceContract]\npublic interface IService1\n{\n    [OperationContract(Name="GetDataUsingDataContractInput")]   \n    CompositeType GetDataUsingDataContract(CompositeType composite);\n}	0
8677922	8677775	How to search for multiple text patterns in files / folders recusively	public void NavigateFolder(DirectoryInfo d)\n{\n    foreach (FileInfo f in d.GetFiles())\n    {\n        //create a streamreader and try to match regex to file contents here\n    }\n\n    foreach (DirectoryInfo d in d.GetDirectories())\n    {\n        NavigateFolder(d);\n    }\n}	0
22063086	22061894	C# Sqlite throwing ConstraintException with DataTable	DataTable dataTable;\ncmd.CommandText = @"SELECT \n    sectors.name AS sector_name,\n    domains.name AS domain_name\n    FROM sectors_domains\n    INNER JOIN domains ON (sectors_domains.domain = domains.id)\n    INNER JOIN sectors ON (sectors_domains.sector = sectors.id)";\n\n\n// Create data adapter\nSQLiteDataAdapter da = new SQLiteDataAdapter(cmd);\n\n// Populate dataTable based on DB query\nda.Fill(dataTable);\nda.Dispose();	0
4111887	4111847	How do I send an email to an address with a dash in it?	joe-blow@me.com	0
15176685	15176538	.NET HttpClient. How to POST string value?	using System;\nusing System.Collections.Generic;\nusing System.Net.Http;\n\nclass Program\n{\n    static void Main()\n    {\n        using (var client = new HttpClient())\n        {\n            client.BaseAddress = new Uri("http://localhost:6740");\n            var content = new FormUrlEncodedContent(new[] \n            {\n                new KeyValuePair<string, string>("", "login")\n            });\n            var result = client.PostAsync("/api/Membership/exists", content).Result;\n            string resultContent = result.Content.ReadAsStringAsync().Result;\n            Console.WriteLine(resultContent);\n        }\n    }\n}	0
18042136	18041920	Multithreading on one WPF Window	public partial class MainWindow : Window\n{\n    private bool _continue = false;\n\n    public MainWindow()\n    {\n        InitializeComponent();\n\n        worker.WorkerSupportsCancellation = true;\n        worker.DoWork += delegate \n        {\n            Hello();\n        };\n    }\n\n    BackgroundWorker worker = new BackgroundWorker();\n\n    private void startWrite(object sender, RoutedEventArgs e)\n    {\n        startButton.IsEnabled = false;\n        stopButton.IsEnabled = true;\n        _continue = true;\n        worker.RunWorkerAsync();\n    }\n\n    private void stopWrite(object sender, RoutedEventArgs e)\n    {\n        worker.CancelAsync();\n        startButton.IsEnabled = true;\n        stopButton.IsEnabled = false;\n        _continue = false;\n    }\n\n    public void Hello()\n    {\n        while (_continue)\n        {\n            Application.Current.Dispatcher.Invoke((Action)(() =>\n            {\n                HelloText.AppendText("Hello World!\n");\n            }));                \n        }\n    }\n}	0
17862141	17861978	Use of local unassigned variable - even with else-statement	MediaDescription media = null;\n...    \n    case FieldType.Information:\n        if(media == null)    <-- Use of local unassigned variable\n            message.Description = field.Value;	0
10643602	10643550	How to zip all files in folder	using (ZipFile zip = new ZipFile())\n  {\n    zip.AddDirectory(@"MyDocuments\ProjectX", "ProjectX");\n    zip.Save(zipFileToCreate);\n  }	0
5796427	5796383	Insert spaces between words on a camel-cased token	Regex.Replace("ThisIsMyCapsDelimitedString", "(\\B[A-Z])", " $1")	0
21957991	21957841	Regex match whole word and punctuation	(?<=\s)(yes.)	0
3566329	3565995	How to override an inherited property from RichTextBox?	string[] lines = ((RichTextBox)myEditor1).Lines;	0
22545850	22545799	Can multiple actions serve the same view?	public ActionResult Contact()\n{\n    ViewBag.Message = "Your contact page.";\n    return View("About");\n}	0
32530894	32530689	How can I keep WCF from timing out?	private void btn_Test_Click(object sender, EventArgs e)\n{\n    using(ServiceReference1.EngineClient eng = new EngineClient())\n    {\n        textBox1.Text = eng.Test();\n    }\n}	0
7122241	7122205	Passing two different property values to a method	class CalculatorInputs\n{\n  public int numberone;\n  public int numbertwo;\n}\n\nclass CalculatorOperations\n{\n  public int Add(CalculatorInputs input)\n  {\n    return input.numberone + input.numbertwo;\n  }\n\n}	0
25025062	25024785	How to create start menu shortcut	using IWshRuntimeLibrary;\n\nprivate static void AddShortcut()\n{\n    string pathToExe = @"C:\Program Files (x86)\TestApp\TestApp.exe";\n    string commonStartMenuPath = Environment.GetFolderPath(Environment.SpecialFolder.CommonStartMenu);\n    string appStartMenuPath = Path.Combine(commonStartMenuPath, "Programs", "TestApp");\n\n    if (!Directory.Exists(appStartMenuPath))\n        Directory.CreateDirectory(appStartMenuPath);\n\n    string shortcutLocation = Path.Combine(appStartMenuPath, "Shortcut to Test App" + ".lnk");\n    WshShell shell = new WshShell();\n    IWshShortcut shortcut = (IWshShortcut)shell.CreateShortcut(shortcutLocation);\n\n    shortcut.Description = "Test App Description";\n    //shortcut.IconLocation = @"C:\Program Files (x86)\TestApp\TestApp.ico"; //uncomment to set the icon of the shortcut\n    shortcut.TargetPath = pathToExe;\n    shortcut.Save(); \n}	0
11299933	11299210	How to put in 3 sets of data into asp.net	DataSet dataSet = new DataSet();\nSqlDataAdapter ad = new SqlDataAdapter(cmd);\n        ad.Fill(dataSet);\n\n        GridView1.DataSource = dataset.Tables[0];\n        GridView1.DataBind();\n        GridView2.DataSource = dataset.Tables[1];\n        GridView2.DataBind();\n        GridView3.DataSource = dataset.Tables[2];\n        GridView3.DataBind();	0
3289923	3289802	Does regex allow you to parse strings? If so, how?	var inputString = "+Name=Bob+Age=39+";\nvar regex = new Regex("Name=(?<Name>[A-Z][a-z]*)\\+Age=(?<Age>[0-9]*)");\n\nvar match = regex.Match(inputString);\n\nSystem.Console.WriteLine("Name: {0}", match.Groups["Name"]);\nSystem.Console.WriteLine("Age: {0}", match.Groups["Age"]);\n\nSystem.Console.ReadKey();	0
8472039	3865193	How to change Header in WebClient	Client.Headers["Content-Type"] = "application/json";\nClient.UploadData("http://www.imageshack.us/upload_api.php", "POST", Encoding.Default.GetBytes("{\"Data\": \"Test\"}"));	0
21674725	21674004	Change the border color of a label on user selection	Color selectedColor;\n\nprivate void label1_Paint(object sender, PaintEventArgs e)\n{\n    base.OnPaint(e);\n    ControlPaint.DrawBorder(e.Graphics, label1.DisplayRectangle, selectedColor, ButtonBorderStyle.Solid);\n}\n\nprivate void comboBox1_SelectedIndexChanged(object sender, EventArgs e)\n{\n    if (comboBox1.SelectedIndex == 0)\n    {\n        selectedColor = Color.Red;         \n    }\n    if (comboBox1.SelectedIndex == 1)\n    {\n        selectColor = Color.Blue;\n    }\n    label1.Invalidate();\n    label1.Update();\n}	0
6093978	6093879	Begin and End Invoke in a single extension method properly	public static Func<R> HandleInvoke<T, R>(this Func<T, R> function, T arg)\n    {\n        R retv = default(R);\n        bool completed = false;\n\n        object sync = new object();\n\n        IAsyncResult asyncResult = function.BeginInvoke(arg, \n            iAsyncResult =>\n            {\n                lock(sync)\n                {\n                    completed = true;\n                    retv = function.EndInvoke(iAsyncResult);\n                    Monitor.Pulse(sync); // wake a waiting thread is there is one\n                }\n            }\n            , null);\n\n        return delegate\n        {\n\n            lock (sync)\n            {\n                if (!completed) // if not called before the callback completed\n                {\n                    Monitor.Wait(sync); // wait for it to pulse the sync object\n                }\n                return retv;\n            }\n        };\n    }	0
24692053	24654274	Getting selected non-regular shape from image in C#	public static bool IsInPolygon(Point[] poly, Point clickedPoint)\n{\n    if (poly.Length < 3)\n    {\n        return false;\n    }\n\n    Point p1, p2;\n\n    bool inside = false;\n\n    Point oldPoint = new Point(poly[poly.Length - 1].X, poly[poly.Length - 1].Y);\n\n    for (int i = 0; i < poly.Length; i++)\n    {\n        Point newPoint = new Point(poly[i].X, poly[i].Y);\n\n        if (newPoint.X > oldPoint.X)\n        {\n            p1 = oldPoint;\n            p2 = newPoint;\n        }\n        else\n        {\n            p1 = newPoint;\n            p2 = oldPoint;\n        }\n\n        if ((newPoint.X < clickedPoint.X) == (clickedPoint.X <= oldPoint.X)\n            && (clickedPoint.Y - (long)p1.Y) * (p2.X - p1.X) < (p2.Y - (long)p1.Y) *(clickedPoint.X - p1.X))\n        {\n            inside = !inside;\n        }\n\n        oldPoint = newPoint;\n    }\n\n    return inside;\n}	0
590015	587836	LINQ - Add property to results	public partial class Courses\n{\n    public String NewProperty { get; set; }\n}	0
8801021	8800925	How to check sql connection status in application start-up?	try\n{\nvar b = db.Table.FirstOrDefault();\n}\ncatch(Exception e)\n{\nShowMessageBox(e.Message);\n}	0
21973416	21973131	Need to speed up pattern matching in jagged array	Parallel.ForEach(whitePatterns, wp =>\n{\nint col = wp.pattern.Length;\nint row = wp.pattern[0].Length;\nfor (int x = 0; x < myBoard.Size - col + 1; ++x)\n{\n    for (int y = 0; y < myBoard.Size - row + 1; ++y)        \n    {\n        for (int xx = 0; xx < col; ++xx)\n            for (int yy = 0; yy < row; ++yy)\n        {\n            count++;\n            if ((myBoard.board[x + xx][y + yy] & wp.pattern[xx][yy]) == 0)\n            {\n                goto loopY;\n\n            }\n        }\n\n        // Found a match!\n\n    loopY: ;\n    }       \n}\n});	0
2573247	2573222	Scrolling textboxes programmatically using WndProc messages	private const int WM_VSCROLL = 0x115;\nprivate const int SB_BOTTOM = 7;\n\n[DllImport("user32.dll", CharSet=CharSet.Auto)]\nprivate static extern int SendMessage(IntPtr hWnd, int wMsg, IntPtr wParam,\nIntPtr lParam);\n\n// Scroll to the bottom, but don't move the caret position.\nSendMessage(TabContents.Handle, WM_VSCROLL, (IntPtr) SB_BOTTOM, IntPtr.Zero);	0
8971099	8970461	Windows Forms dialog icon without control box	private const int GWL_STYLE = -16;\n    private const int WS_CLIPSIBLINGS = 1 << 26;\n\n    [DllImport("user32.dll", CharSet = CharSet.Auto, EntryPoint = "SetWindowLong")]\n    public static extern IntPtr SetWindowLongPtr32(HandleRef hWnd, int nIndex, HandleRef dwNewLong);\n    [DllImport("user32.dll", CharSet = CharSet.Auto, EntryPoint = "GetWindowLong")]\n    public static extern IntPtr GetWindowLong32(HandleRef hWnd, int nIndex);\n\n    protected override void OnLoad(EventArgs e) {\n        int style = (int)((long)GetWindowLong32(new HandleRef(this, this.Handle), GWL_STYLE));\n        SetWindowLongPtr32(new HandleRef(this, this.Handle), GWL_STYLE, new HandleRef(null, (IntPtr)(style & ~WS_CLIPSIBLINGS)));\n\n        base.OnLoad(e);\n    }	0
12412085	9936646	Reading Excel InterMixed DataType Without Modifying Registry Key	var MyConnection = new OleDbConnection("provider=Microsoft.Jet.OLEDB.4.0; Data Source='" + path + "';Extended Properties='Excel 8.0;HDR=No;IMEX=1;'");	0
17025389	17025285	SQL server remove space before value when I insert data	SqlCommand cmd1 = new SqlCommand("INSERT INTO [Contracts].[dbo].[Contract] " + \n     "([Contract_Id],[Name],[Description],[Contracted_by],[Vendor_Name],[Related_Dept]," + \n     "[Start_date],[Expiration_Date],[TypeofContract],[Contact_Person]," + \n     "[Contact_No],FileName,FileData,FileType) VALUES (" + \n     "@cid, @name, @desc, @cby, @vname, @rdept, @stdate, @expdate, " + \n     "@tc, @cp, @cno, @file, @fdate, @ftype",con)\n\n  SqlParameter p = new SqlParameter("@cid", SqlDbType.Int).Value = Convert.ToInt32(textBox1.Text));\n  cmd.Parameters.Add(p);\n  .... and so on for the other parameters required	0
20119259	20117691	Check if OS is 32 bit or 64 bit before application install in C# windows application	Environment.Is64BitOperatingSystem	0
32756817	32756735	How to center a table in MigraDoc?	table.Rows.LeftIndent	0
3484287	3461736	Selecting Text in ICSharpCode Text Editor	// Two lines of text.\ntextEditorControl.Text = \n    "First\r\n" +\n    "Second\r\n";\n\n// Start of selection - columns and lines are zero based.\nint startCol = 0;\nint startLine = 1;\nTextLocation start = new TextLocation(startCol, startLine);\n\n// End of selection.\nint endCol = 6;\nint endLine = 1;\nTextLocation end = new TextLocation(endCol, endLine);\n\n// Select the second line.\ntextEditorControl.ActiveTextAreaControl.SelectionManager.SetSelection(start, end);\n\n// Move cursor to end of selection.\ntextEditorControl.ActiveTextAreaControl.Caret.Position = end;	0
21680915	21680572	How to increment a List Name?	List<PointF>[] lists = {new List<PointF>(), new List<PointF>(), new List<PointF>(), new List<PointF>()};\n\nfor(int i=0;i<20;i++) lists[i/5].Add(points[i]);	0
10141126	10141106	Testing Database Connectivity in C# Console Application	using(SqlConnection conn = new SqlConnection(connectionString))\n{\n    try\n    {\n        conn.Open();\n        // Do what you please here        \n    }\n    catch (Exception ex)\n    {\n        // Write error to file\n        File.Append(..., \n            DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss") + " " + \n            ex.Message);\n    }\n    finally \n    { \n        conn.Close();\n    } \n}	0
2790771	2790750	How do I use C# and ASP.net to proxy a WebRequest?	using (Stream answer = webResp.GetResponseStream()) {\n    byte[] buffer = new byte[4096];\n    for (int read = answer.Read(buffer, 0, buffer.Length); read > 0; read = answer.Read(buffer, 0, buffer.Length)) {\n        Response.OutputStream.Write(buffer, 0, read);\n    }\n}	0
10934751	10934126	return value from javascript should be assigned to an array in C#	Request.QueryString	0
27500541	27495177	Angular JS object key value - key prefixed with "@"	{{ story["@title"] }}	0
9824566	9824444	How to include a document in my C# project?	using (Stream stream = Assembly.GetExecutingAssembly()\n                               .GetManifestResourceStream("template.html"))\nusing (StreamReader reader = new StreamReader(stream))\n{\n    string result = reader.ReadToEnd();\n}	0
5174021	5173871	c# custom group by really slow for large data set	List<Campaign> listCampaigns = new List<Campaign>();\nforeach (var g in campaigns.GroupBy(c => new { c.CampaignName, c.Term }))\n{\n    var campaign = g.First();\n    campaign.TotalVisits = g.Sum(x => x.TotalVisits);\n    campaign.Conversions = g.SelectMany(c => c.Conversions).ToArray();\n    listCampaigns.Add(campaign);\n}	0
31606674	31600763	Need Help in ASP.Net C# login page	if ((UserName == Dr["UserName"].ToString()) & (Password == Dr["Password"].ToString()))\n{\n    boolReturnValue = true;\n    break;\n}	0
27371984	27371902	How do I parse a double with optional decimal seperator	(([0-9]+(?:[,.]?[0-9]*?))[\s]*(cm|mm))	0
33116513	33116402	LINQ How to make a BETWEEN condition	string FindGrade(double score,string rule)\n{  \n    List<Scoremaster> scores = (from p in dbcontext.Scoremasters\n                         where p.GradeRule==rule && score>= p.MinScore && score<= p.MaxScore\n                         select p).ToList();\n}	0
19747639	19718410	How does one tell Ninject to treat any Class<T> as a singleton	Bind(typeof(EntitySignal<>))\n    .ToSelf()\n    .InSingletonScope()	0
12713597	12713254	sort list of objects by list of longs	var q = (from i in TheListOfIDs\n        join m in TheListOfModels on i equals m.MyModelID\n        select m).ToList();	0
580264	579665	How can I show a systray tooltip longer than 63 chars?	using System;\nusing System.Windows.Forms;\nusing System.Reflection;\n\n    public class Fixes {\n      public static void SetNotifyIconText(NotifyIcon ni, string text) {\n        if (text.Length >= 128) throw new ArgumentOutOfRangeException("Text limited to 127 characters");\n        Type t = typeof(NotifyIcon);\n        BindingFlags hidden = BindingFlags.NonPublic | BindingFlags.Instance;\n        t.GetField("text", hidden).SetValue(ni, text);\n        if ((bool)t.GetField("added", hidden).GetValue(ni))\n          t.GetMethod("UpdateIcon", hidden).Invoke(ni, new object[] { true });\n      }\n    }	0
504378	504208	How to read command line arguments of another process in C#?	string wmiQuery = string.Format("select CommandLine from Win32_Process where Name='{0}'", processName);\nManagementObjectSearcher searcher = new ManagementObjectSearcher(wmiQuery);\nManagementObjectCollection retObjectCollection = searcher.Get();\nforeach (ManagementObject retObject in retObjectCollection)\n    Console.WriteLine("[{0}]", retObject["CommandLine"]);	0
9639467	9639044	How to make a Excel CommandBarButton Invisible on create?	.Visible = false	0
7303690	7301682	making a cylinder point an object in unity3d	Quaternion.FromToRotation(...)	0
5304669	5304430	Suggestion For Data Access Layer with Entity Framework	using(var context = new YourDataContext())\n{\n   //use context for CRUD operation\n   Entity1 entity1 = context.Entities1.Where(e1 => e1.Id == 1);\n   entity1.Prop1 = "New Value";  \n\n   context.Entities2.Add(entity2)\n\n   context.SaveChanges();\n}	0
25991371	25991089	Selenium - Modal dialog present - how to accept information?	IAlert alert = driver.SwitchTo().Alert();\nalert.Accept();	0
5347308	5347211	How to Send a Web Request to Log Out?	WebRequest.DownloadString("http://rapideo.pl/wyloguj")	0
13501508	13500456	How to convert an IEnumerable<Task<T>> to IObservable<T>	tasks.Select(t => Observable.FromAsync(() => t))\n     .Merge();	0
33974645	33974480	Passing parameters in a method, in an if-else statement C#	if (String.IsNullOrEmpty(param3)) // you could say that only 3 params were given\n{\n\n}\nelse // you could say that all 4 params were given\n{\n\n}	0
3187936	3187900	Convert DateTime to string with format YYYYMMDD	date.ToString("yyyyMMdd");	0
5083926	5083854	C# Scroll to top of listbox	if(results.Items.Count > 0)\n    results.ScrollIntoView(results.Items[0]);	0
26800789	26800696	How to Convert Items of Dropdownlist to datetime?	DateTime date = Convert.ToDateTime(DropDownListDate.SelectedValue.ToString());	0
22773121	22773020	split string with regular expression by elements	var str = "['A','B', ''],['A','D', 'F'],['A','G', 'G']";\nvar topLevelLists = new List<string>();\nvar arrStart = -1;\nvar nesting = 0;\nfor (int i = 0; i != str.Length; ++i) {\n    if (str[i] == '[') {\n        if (nesting == 0) {\n            arrStart = i;\n        }\n        ++nesting;\n    }\n    else if (str[i] == ']') {\n        if (nesting <= 0) {\n            // Error, ']' without matching '[' at i\n            break;\n        }\n        --nesting;\n        if (nesting == 0) {\n            topLevelLists.Add(str.Substring(arrStart, i - arrStart + 1));\n        }\n    }\n}\nif (nesting > 0) {\n    // Error, unmatched '[' at arrStart\n}\n\n// topLevelLists => [ "['A','B', '']", "['A','D', 'F']", "['A','G', 'G']" ];	0
253945	253843	Best way to refresh DataGridView when you update the base data source	dataGridView1.DataSource = typeof(List); \ndataGridView1.DataSource = itemStates;	0
33255499	33255372	controls with same name in different panels in C#	private Control SearchControl(IContainerControl container, string name)\n{\n    foreach (Control control in this.Controls)\n    {\n        if (control.Name.Equals(name))\n        {\n            return control;\n        }\n\n        if (control is IContainerControl)\n        {\n            return SearchControl(control as IContainerControl, name);\n        }\n    }\n\n    return null;\n}	0
23237948	23237793	Implement interface's IEnumerable<BaseClass> with IEnumerable<DerivedClass>?	class Implementation : IImplementMe\n{\n    public IEnumerable<DerivedClass> Member;\n\n    IEnumerable<BaseClass> IImplementMe.Member { get { return Member; } }\n}	0
22832118	21574793	Deactivate selection for specific items in listbox / listview	private void ItemList_SelectionChanged(object sender, SelectionChangedEventArgs e)\n{\n   foreach (var item in e.AddedItems)\n     {\n       if (!item.IsBad())\n       {\n         ItemList.SelectedItems.Remove(item);\n       }\n       else\n       {\n         isBadAdd = true;\n       }\n     }\n}	0
4124493	4124458	Rounding a number	var output = Math.Ceiling(amount / 4);	0
11472914	11469681	how to pass a parameter value from rdlc report to a method in web forms project?	var p = new Product();\n\n//fill class properties with data\n\nReportParameter[] params = new ReportParameter[2]; \nparams[0] = new ReportParameter("Name ", p.Name , false); \nparams[1] = new ReportParameter("Quantity ", p.Quantity , false); \nthis.ReportViewer1.ServerReport.SetParameters(params);     \nthis.ReportViewer1.ServerReport.Refresh();	0
11084112	11084027	C#:Search from treeview	treeView1.Nodes.Find()	0
28320952	28318906	Keep it on the same page if there isn't any file to download	public ActionResult GetXML(long productionOrderId) //Changed Return Type\n{\n    ProductionOrderReport poReport = null;\n\n    poReport = new ProductionOrderReport(m_Repository, m_AggRepo, m_AggChildsRepo);\n\n    // Get the XML document for this Production Order.\n    XDocument doc = poReport.GenerateXMLReport(productionOrderId);\n\n    if (doc != null)\n    {\n        // Convert it to string.\n        StringWriter writer = new Utf8StringWriter();\n        doc.Save(writer, SaveOptions.None);\n\n        // Convert the string to bytes.\n        byte[] bytes = Encoding.UTF8.GetBytes(writer.ToString());\n\n        return File(bytes, "application/xml", "report.xml");\n    }\n    else\n        return RedirectToAction("ViewName","ControllerName"); //Instead of returning null, you can redirect back to the GET action of the original view.\n}	0
4879978	4879197	Using reflection read properties of an object containing array of another object	public static void GetMyProperties(object obj)\n{\n  foreach (PropertyInfo pinfo in obj.GetType().GetProperties())\n  {\n    var getMethod = pinfo.GetGetMethod();\n    if (getMethod.ReturnType.IsArray)\n    {\n      var arrayObject = getMethod.Invoke(obj, null);\n      foreach (object element in (Array) arrayObject)\n      {\n        foreach (PropertyInfo arrayObjPinfo in element.GetType().GetProperties())\n        {\n          Console.WriteLine(arrayObjPinfo.Name + ":" + arrayObjPinfo.GetGetMethod().Invoke(element, null).ToString());\n        }\n      }\n    }\n  }\n}	0
9776216	9776101	logic with bool	bool status = true;\nif (xxx > 100)\n{ \n    errMsg = "Number of xxx should be <= 100";\n    swRpt.WriteLine(errTitle + errMsg);\n    status = false;\n}\n// sizing\n\nswRpt.WriteLine("   Epsilon");\n\n//Repair\nsuccess = Numerical.Check("repair", inputs.repair.ToString(), \n                          out dtester, out errMsg);\nif (!success)\n{\n    swRpt.WriteLine(errTitle + errMsg);\n    status = false;\n}\nsuccess = Numerical.Check("prob", inputs.prob.ToString(), \n                          out dtester, out errMsg);\nif (!success)\n{\n    swRpt.WriteLine(errTitle + errMsg);\n    status = false;\n}\n\nreturn status;	0
23347881	23344528	Creating many to many junction table in Entity Framework	public class SupplierUsers\n{\n    public int SupplierUsersId { get;set; }\n    public string UserId { get; set; }\n    public int SupplierId { get; set; }\n    public SupplierUserPermission Permission { get; set; }\n    public virtual Supplier Supplier { get; set; }\n    public virtual User User { get; set; } \n}	0
8146708	8146702	Select a section out of the middle of a list in C#	using System.Linq;\n\nlist.Skip(10).Take(20)	0
9636512	9634969	WP7 & XNA - How to multiply RotationMatrix in Landscape mode	viewMatrix = motion.CurrentValue.Attitude.RotationMatrix * Matrix.CreateRotationZ(MathHelper.PiOver2);	0
168362	167232	Changing the application pool through a Web Deployment Project	Private Sub assignApplicationPool(ByVal WebSite As String, ByVal Vdir As String, ByVal appPool As String)\n   Try\n     Dim IISVdir As New DirectoryEntry(String.Format("IIS://{0}/W3SVC/1/Root/{1}", WebSite, Vdir))\n     IISVdir.Properties.Item("AppPoolId").Item(0) = appPool\n     IISVdir.CommitChanges()\n   Catch ex As Exception\n     Throw ex\n   End Try\n End Sub\n\n Private strServer As String = "localhost"\n Private strRootSubPath As String = "/W3SVC/1/Root"\n Private strSchema As String = "IIsWebVirtualDir"\n Public Overrides Sub Install(ByVal stateSaver As IDictionary)\n   MyBase.Install(stateSaver)\n   Try\n     Dim webAppName As String = MyBase.Context.Parameters.Item("TARGETVDIR").ToString\n     Dim vdirName As String = MyBase.Context.Parameters.Item("COMMONVDIR").ToString\n     Me.assignApplicationPool(Me.strServer, MyBase.Context.Parameters.Item("TARGETVDIR").ToString, MyBase.Context.Parameters.Item("APPPOOL").ToString)\n   Catch ex As Exception\n     Throw ex\n   End Try\n End Sub	0
23727573	23724931	sqlite EF DbUpdateException	Database.SetInitializer<BloggingContext>(new DropCreateDatabaseIfModelChanges<BloggingContext>());	0
14381974	14381656	Recursively find the most recent file from each folder in folder hierarchy.	if(Directory.Exists("YourPath"))\nforeach (string _tempFiles in Directory.GetDirectories("YourPath","*", SearchOption.AllDirectories)\n                       .Select(directory => Directory.GetFiles(directory, "*.*" )\n                       .OrderByDescending(File.GetLastWriteTime)\n                       .FirstOrDefault()))\n{\n MessageBox.Show(_tempFiles);\n}	0
11545574	11545238	C#, convert a database value to a string?	//select query here and your connectionstring\n //then fill table as seen below\n SqlDataAdapter sDA = new SqlDataAdapter(query, connectionString);\n DataTable table = new DataTable();\n sDA.Fill(table);\n\n foreach (DataRow row in table.Rows)\n {\n    string pc = (row["PCs"].ToString());\n     //send files\n }	0
21259951	21251389	Close child window whenever mouse leave in silverlight	private void ShowButton_Click(object sender, RoutedEventArgs e)\n    {\n        ChildWindow cw = new ChildWindow();\n        cw.Width = 300;\n        cw.Height = 300;\n        cw.HorizontalContentAlignment = System.Windows.HorizontalAlignment.Stretch;\n        cw.VerticalContentAlignment = System.Windows.VerticalAlignment.Stretch;\n        Grid g = new Grid();\n        g.Background = new SolidColorBrush(Colors.Gray);\n        g.Children.Add(new TextBlock() { Text = "Child window content." });\n        g.MouseLeave += ChildWindowContent_MouseLeave;\n        cw.Content = g;\n        cw.Show();\n    }\n\n    private void ChildWindowContent_MouseLeave(object sender, MouseEventArgs e)\n    {\n        ChildWindow cw = ((Grid)sender).Parent as ChildWindow;\n        cw.Close();\n    }	0
14206645	14183861	Resizing and position a SharpDX sprite	private static byte[] ResizeAlbumArt(byte[] originalAlbumArtData)\n{\n    using (var originalStream = new MemoryStream(originalAlbumArtData))\n    {\n        var original = new Bitmap(originalStream);\n        var target = new Bitmap(AlbumArtDimensions, AlbumArtDimensions);\n\n        using (var g = Graphics.FromImage(target))\n        {\n            g.SmoothingMode = SmoothingMode.HighQuality;\n            g.InterpolationMode = InterpolationMode.HighQualityBicubic;\n            g.PixelOffsetMode = PixelOffsetMode.HighQuality;\n            g.DrawImage(original, 0, 0, target.Width, target.Height);\n        }\n\n        using (var outputStream = new MemoryStream())\n        {\n            target.Save(outputStream, ImageFormat.Bmp);\n            return outputStream.ToArray();\n        }\n    }\n}	0
11199446	11198050	Converting C++ pointer to member to C#	class C\n{\n    public int Method1() { return 1; }\n    public int Method2() { return 2; }\n}\n\nclass Program\n{\n    static void Main(string[] args)\n    {\n        C myC = new C();\n        Func<C, int> ptrToMember1 = (C c) => { return c.Method1(); };\n        int i = Method(myC, ptrToMember1 );\n    }\n\n    static int Method(C c, Func<C, int> method)\n    {\n        return method(c);\n    }\n}	0
9916541	9916269	How do I get property names of a type using a lambda expression and anonymous type?	public static string[] Foo<T>(Expression<Func<T, object>> func)\n{\n    var properties = func.Body.Type.GetProperties();\n\n    return typeof(T).GetProperties()\n        .Where(p => properties.Any(x => p.Name == x.Name))\n        .Select(p =>\n        {\n            var attr = (ColumnAttribute) p.GetCustomAttributes(typeof(ColumnAttribute), true).FirstOrDefault();\n            return (attr != null ? attr.Name : p.Name);\n        }).ToArray();\n}	0
17841559	17840623	Getting matches from a query and not keeping anything else	var ds = new DataSet();\n        var table1 = ds.Tables.Add("Table1");\n        table1.Columns.Add("Expression", typeof (string));\n        table1.Rows.Add("SN123");\n        table1.Rows.Add("SN456");\n        table1.Rows.Add("SN789");\n        var table2 = ds.Tables.Add("Table2");\n        table2.Columns.Add("Expression", typeof (string));\n        table2.Rows.Add("SN000");\n        table2.Rows.Add("SN456");\n        table2.Rows.Add("SN999");\n\n        var table1Rows = table1.AsEnumerable();\n        var table2Rows = table2.AsEnumerable();\n\n        var matches = table1Rows.Join(table2Rows, l => l["Expression"], r => r["Expression"], (l, r) => l["Expression"]);\n        foreach (var match in matches)\n        {\n            Console.WriteLine(match);\n        }	0
30926091	30925679	Tiny stub of bogus code purely for the purpose of setting a breakpoint (that doesn't create a compiler warning)	System.Diagnostics.Debugger.Break()	0
3429784	3429747	How do I make somthing visible when the mouse moves across a button?	propertyGrid1.Leave += (object sender, EventArgs e) => { propertyGrid1.Hide(); };	0
537652	537573	How to get IntPtr from byte[] in C#	IntPtr unmanagedPointer = Marshal.AllocHGlobal(bytes.Length);\nMarshal.Copy(bytes, 0, unmanagedPointer, bytes.Length);\n// Call unmanaged code\nMarshal.FreeHGlobal(unmanagedPointer);	0
17900405	17891472	directx transformedcolored color field alpha value	graphics.GraphicsDevice.RenderState.AlphaBlendEnable = true;\ngraphics.GraphicsDevice.RenderState.SourceBlend = Blend.SourceAlpha;\ngraphics.GraphicsDevice.RenderState.DestinationBlend = Blend.InverseSourceAlpha;\ngraphics.GraphicsDevice.RenderState.BlendFunction = BlendFunction.Add;	0
19974759	19973982	How to find column id by cell value?	object misValue = System.Reflection.Missing.Value;\n\nMicrosoft.Office.Interop.Excel.Range xlRange = xlWorkSheet.get_Range("A2", "A2");\n\nMicrosoft.Office.Interop.Excel.Range xlFound = xlRange.EntireRow.Find("ID Number",\nmisValue, Excel.XlFindLookIn.xlValues, Excel.XlLookAt.xlPart,\nExcel.XlSearchOrder.xlByColumns, Excel.XlSearchDirection.xlNext, \ntrue, misValue, misValue);\n\n//~~> Check if a range was returned\nif (!(xlFound == null))\n{\n    int ID_Number = xlFound.Column;\n    MessageBox.Show(ID_Number.ToString());\n}	0
17051767	17051713	Grouping into an array	return Json.Encode(\n    Models\n    .GroupBy(e => e.Gender)\n    .Select(g => new object[] { g.Key, g.Count() })\n    .ToArray()\n);	0
7360845	7360581	How to read DateTimeOffset serialized by DataContractJsonSerializer	var date = new DateTime(1970, 1, 1).AddMilliseconds(1315565098519);\nvar dateWithOffset = new DateTimeOffset(date, TimeSpan.FromMinutes(300));	0
19846183	19846014	In a C# Console Application, how do you use \n in a table?	Console.WriteLine(table, "Total cost of paint", ":", paintTotalWithVAT, "\n");	0
4647600	4647494	Compare 2 string with Regex (C#)	static bool IsEqual(String left, String right)\n    {\n        left = Regex.Replace(left, ":[0-9]*:[0-9]*", "");\n        right = Regex.Replace(right, ":[0-9]*:[0-9]*", "");\n        return left.Equals(right);\n    }\n\n    static void Main(string[] args)\n    {\n        Console.WriteLine(IsEqual("SAAT:232:34", "SAAT:12:23")); // True\n        Console.WriteLine(IsEqual("PAAT:23:34", "SAAT:12:23")); // False\n        Console.WriteLine(IsEqual("SAAT:23:34:HAT", "SAAT:12:23:HAT")); // True\n    }	0
18854582	18853655	how to make google map coordinates request more precise/accurate with c# winform?	...\n"geometry" : {\n        "bounds" : {\n           "northeast" : {\n              "lat" : 40.91525559999999,\n              "lng" : -73.70027209999999\n           },\n           "southwest" : {\n              "lat" : 40.495908,\n              "lng" : -74.2590879\n           }\n        },\n        "location" : {\n           "lat" : 40.7143528,\n           "lng" : -74.00597309999999\n...	0
30628955	30628012	Fixing a System.FormatException	foreach(string line in a)\n{\n    Match m = Regex.Match(line, @"Savings\s+found:\s*\$(?<savings>\d+\.\d+)\s*\(\s*(?<percent>\d+\.\d+)\s*%");\n    if (m.Success)\n    {\n        decimal savings = decimal.Parse(m.Groups["savings"].Value, CultureInfo.InvariantCulture);\n        decimal percent = decimal.Parse(m.Groups["percent"].Value, CultureInfo.InvariantCulture);\n        string prefix = string.Empty;\n        if (percent >= 30)\n        {\n            if (savings >= 500)\n                prefix = "**";\n            else\n                prefix = "*";\n        }\n        Console.WriteLine(prefix + line);\n    }\n}	0
26163653	26089089	How to convert Func<T1, bool> to Func<T2,bool> in C#	Func<User,bool> userFunc = u=>func(UserToCustomUser(u))\nthis.GetUser(userfunc)	0
11690814	11690593	Center aligining text in compact framework?	float fontHeight = e.Graphics.MeasureString("ABC", Font).Height;\ne.Graphics.DrawString("ABC", Font, b, new RectangleF(0, Height / 2.0f - fontHeight/2.0f, Width, Height), format);	0
8603377	8600381	Save File Using Windows Service	System.Threading.Timer	0
18279826	18279781	Regex to match words separated by '!' and enclosed between curly brackets '{' '}'	{([^}]+![^}]+)}	0
13108642	13108583	Combine two lists of entities with a condition	var result = List1.Concat(List2)\n                  .GroupBy(o => o.ID)\n                  .Select(g => new Object() { \n                                   ID=g.Key,\n                                   Property=g.Any(o=>o.Property=="1")?"1":""\n                   })\n                  .ToList();	0
19892033	19891999	How do I force SqlCommand to not encode parameters as unicode/nvarchar?	command.Parameters.Add(new SqlParameter\n{\n    SqlDbType = SqlDbType.VarChar,\n    ParameterName = "url",\n    Value = url\n});	0
21436893	21436827	Unable to add reply to in mail header C#	MailMessage mail = new MailMessage("\"Company Name\" <info@company.com>", textBox_Email_to.Text);\n\n        SmtpClient client = new SmtpClient();\n        client.DeliveryMethod = SmtpDeliveryMethod.Network;\n        client.UseDefaultCredentials = false;\n        client.Host = "host name";\n\n        mail.Subject = "test email";\n        mail.Body = file; // file contains some text\n\n        //mail.Headers.Add("reply-to", "service@company.de");\n        mail.ReplyToList.Add(new MailAddress("service@company.de", "reply-to"));\n\n        mail.IsBodyHtml = true;\n        client.Send(mail);	0
5992291	423921	XmlDocument and slow schema processing	private class DummyResolver : XmlResolver\n{\n   public override System.Net.ICredentials Credentials\n   {\n    set\n    {\n     // Do nothing.\n    }\n   }\n\npublic override object GetEntity(Uri absoluteUri, string role, Type ofObjectToReturn)\n   {\n    return new System.IO.MemoryStream();\n   }\n}	0
22981062	22980967	Avoiding loss of session variables when web.config and bin folder changes	web.config	0
508675	508590	Open a file and write contents to a DIV, span, label, some kind of container	lable1.text= System.IO.File.ReadAllText( path );	0
333786	333767	How to get the installation directory in C# after deploying dll's	Assembly.GetExecutingAssembly().Location	0
10209604	10209311	How to do multi row selection in a GridView in C#	DataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect;\nDataGridView1.MultiSelect = true;	0
33712588	33712382	WPF: How to clone an image multiple times in a loop?	for (int i = 0; i < 1000; i++)\n    {\n        rtb.Clone(); // Exception\n        GC.Collect();\n    }	0
3105428	3105399	Avoid double control search in LINQ query	dic\n .Select(kvp => new { Control = this.FindControl(kvp.Key), Visible = kvp.Value })\n .Where(i => i.Control != null)\n .ToList()\n .ForEach(p => { p.Control.Visible = p.Visible; });	0
5299176	5298707	Modify xml file with a dataset and child relations	DataSet ds = new DataSet();\nds.ReadXml("XMLFile1.xml", XmlReadMode.InferSchema);\nds.Tables[1].Rows.Add(new string[] {"0","0","0","0"});\nds.Tables[1].Rows[1].SetParentRow(ds.Tables[0].Rows[0]);\nds.Tables[1].Rows[0]["prop_id"] = 1;\nds.WriteXml("xmlfile2.xml", XmlWriteMode.IgnoreSchema);\n\n\n<einginedesign>\n<object om_id="111" objname="DelivaryInfo">\n<objprop prop_id="1">\n  <prop_name>OrderRef</prop_name>\n  <prop_desc>Order Reference</prop_desc>\n  <prop_dtype>varchar</prop_dtype>\n</objprop>\n<objprop prop_id="0">\n  <prop_name>0</prop_name>\n  <prop_desc>0</prop_desc>\n  <prop_dtype>0</prop_dtype>\n</objprop>	0
7146147	7146080	Closing Applications	Application.Exit	0
24174104	24174018	Multiple models in the same view?	public class OnBoardEmployeeViewModel\n{\n   public Employee Employee { get; set; }\n   public SoftwareNeeded SoftwareNeeded { get; set; }\n}	0
21173153	21172526	SQL Server transactions and transaction isolation - getting errors that I don't know how to fix	Process 1\nDEBIT BANK ACCOUNT\nCREDIT VENDOR ACCOUNT\n\nProcess 2\nCREDIT VENDOR ACCOUNT\nDEBIT BANK ACCOUNT	0
22232773	22232734	Converting something like 0x0EB8 from a string to an int32 type?	int blah = Convert.ToInt32(blahString, 16);	0
25417548	25417428	Format the string with escape characters	string path = String.Format(@"""\""\{0}\c$\Packages Log\", Environment.MachineName);\n        StringBuilder buildLogcmd = new StringBuilder();\n        buildLogcmd.Append("/LOGGER ");\n        buildLogcmd.Append(String.Format(@"{0}SSISErrors.txt\""""", path));	0
16511277	16511244	How to create connection string dynamically in C#	private void Form1_Load(object sender, EventArgs e)\n{\n     SqlConnectionStringBuilder connectionString = new SqlConnectionStringBuilder();\n     connectionString.DataSource = @".\SQLEXPRESS";\n     connectionString.InitialCatalog = "MyDatabase";\n     connectionString.IntegratedSecurity = true;\n     MessageBox.Show(connectionString.ConnectionString);\n}	0
16896221	16896100	Should I use a property to access a base class global variable?	public class ProviderRequest\n{\n    protected Dictionary<int, string> ResidentialService { get; set; }\n}	0
17413559	17413523	Add strings between curly braces using string formatter in c#	private const string formatString = "{{{0}}}{{{1}}}";	0
25297712	25297509	Repeater Skipping First Row on ItemDataBound	foreach (RepeaterItem ri in rep_FeaturedProds.Items)	0
7237093	7237075	HTML Agility Pack Find specific span	var doc = new HtmlDocument();\ndoc.Load("foo.html");\nvar node = doc.DocumentNode.SelectSingleNode("//span[@id='foo']");\nif (node != null)\n{\n    var innerText = node.InnerText;\n}	0
9434491	9434336	Parse Datetime string	var date = DateTime.ParseExact( dateString\n   ,"yyyyMMdd\THHmmsszzz"\n   ,CultureInfo.InvariantCulture \n   );	0
32295525	32293980	C#: How to import excel to datagridview?	public DataTable ImportExceltoDatatable(string filepath)\n    {\n        string sqlquery = "Select * From [Sheet1$]";\n        DataSet ds = new DataSet();\n        string constring = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + filepath + ";Extended Properties=\"Excel 12.0;HDR=YES;\"";\n        OleDbConnection con = new OleDbConnection(constring + "");\n        OleDbDataAdapter da = new OleDbDataAdapter(sqlquery, con);\n        da.Fill(ds);\n        DataTable dt = ds.Tables[0];\n        return dt;\n    }	0
32930089	32930038	Is there a way to check the version of a file?	var version = FileVersionInfo.GetVersionInfo(path).FileVersion;	0
30767342	30761871	linq multi left join to same property	...\nfrom ttdmx in db.testtabledetails.Where(x => \n    tt.id == x.causeid && \n    tt.maxcausedetailorder == x.detailorder).DefaultIfEmpty()\n...	0
18054359	18054221	How to prevent radio button change status	IsEnabled=false	0
26502908	26502789	C# - Get path of project , n o bin path	string path = AppDomain.CurrentDomain.BaseDirectory ;	0
979670	979667	Regular Expression to find src from IMG tag	class Program\n{\n    static void Main(string[] args)\n    {\n        var web = new HtmlWeb();\n        var doc = web.Load("http://www.stackoverflow.com");\n\n        var nodes = doc.DocumentNode.SelectNodes("//img[@src]");\n\n        foreach (var node in nodes)\n        {\n                Console.WriteLine(node.src);\n        }\n    }\n}	0
3445652	3445642	Cannot add items to listbox	private void DisplayFiles()\n{\n    lstPhotos.Items.AddRange(files.ToArray<object>);\n}	0
31867771	31866395	Providing an specific overloaded method to a method that accepts Func as parameter	class Test<X>\n    {\n        private readonly Func<string, X> ParseMethod;\n\n        public Test(Func<string, X> parseMethod)\n        {\n            this.ParseMethod = parseMethod;\n        }\n\n        public X GetDataValue(int id)\n        {\n            string idstring = "3-mar-2010";\n            return this.ParseMethod(idstring);\n        }\n    }\n\n    [TestMethod]\n    public void TestParse()\n    {\n        var parser = new Test<DateTime>(DateTime.Parse);\n        DateTime dt = parser.GetDataValue(1);\n        Assert.AreEqual(new DateTime(day: 3, month: 3, year: 2010), dt);\n    }	0
4887690	4887572	Is it possible to re-DataBind a DropDownList upon postback triggered by SelectedIndexChanged event?	protected void Page_Init(object sender, EventArgs e)\n{\n    // here you bind your dropdown\n    // don't check IsPostBack\n    DropdownList1.DataSource = db.GetCategories();\n    DropdownList1.DataTextField = "TextField";\n    DropdownList1.DataValueField = "ValueField";\n    DropdownList1.DataBind();\n}	0
27354027	27353981	Place list item at specific position in CheckBox List	checkboxlist2.Items.Insert(index , listitemselectedfromcheckboxlist1)	0
22240146	22240014	Data Adapter Filter	string qString = "cust_postcode = 'CF48 4JY'";	0
21137076	21136805	What is the most efficient way of retrieving data from a DataReader?	int idIdx = rdr.GetOrdinal("Id");\nint createdIdx = rdr.GetOrdinal("Created");\n\nwhile(rdr.Read())\n{\n    var myObj = new myObj();\n\n    myObj.Id = rdr.GetFieldValue<int>(idIdx);\n\n    //more populating of myObj from rdr\n\n    myObj.Created = rdr.GetFieldValue<DateTime>(createdIdx);\n}	0
16415919	16415774	How do you go through two int arrays and sum their values if they exist	int[] ArrTotal(int[] a, int[] b)\n    {\n        if (a == null || b == null) \n        {\n            return (int[])(a ?? b).Clone();\n        }\n        int length = Math.Max(a.Length, b.Length);\n        int[] result = new int[length];\n        for (int i = 0; i < length; i++)\n        {\n            int sum = 0;\n            if (a.Length > i) sum += a[i];\n            if (b.Length > i) sum += b[i];\n            result[i] = sum;\n        }\n        return result;\n    }	0
18293847	18293613	How to populate Table View in Xamarin?	// populate this in constructor, via service, setter, etc - whatever makes sense\nprivate string[] data;\n\n// how many rows are in the table\npublic int NumberOfRowsInTableView(NSTableView table)\n{\n  return data.length;\n}\n\n// what to draw in the table\npublic NSObject ObjectValueForTableColumn (NSTableView table, NSTableColumn col, int row)\n{\n  // assume you've setup your tableview in IB with two columns, "Index" and "Value"\n\n  string text = string.Empty;\n\n  if (col.HeaderCell.Title == "Index") {\ntext = row.ToString();\n  } else {\n    text = data [row];\n  }\n\n  return new NSString (text);\n}	0
9168143	9167756	Substitute for Group_Concat to customize existing Entity Framework model	class Book \n{ \n    public int ID { get; set; } \n    public string Title { get; set; } \n    public List<Genre> Genres { get; set; }\n\n    public string Gen\n    {\n        get\n        {\n            return string.Join("; ", Genres.Select(g => g.Name));\n        }\n    }\n}	0
12612346	9187256	Facebook Channel File in ASP.NET	public class FacebookChannel : IHttpHandler\n{\n\n    public void ProcessRequest(HttpContext context)\n    {\n\n        HttpResponse response = context.Response;\n        response.ClearHeaders();\n\n        const int cacheExpires = 60 * 60 * 24 * 365;\n        response.AppendHeader("Pragma", "public");\n        response.AppendHeader("Cache-Control", "max-age=" + cacheExpires);\n        response.AppendHeader("Expires", DateTime.Now.ToUniversalTime().AddSeconds(cacheExpires).ToString("r"));\n        context.Response.ContentType = "text/html";\n        context.Response.Write("<script src=\"//connect.facebook.net/en_US/all.js\"></script>");        \n    }\n    public bool IsReusable { get { return false; } }\n}	0
14797802	14797664	Original file bytes from StreamReader, magic number detection	using(FileStream fs = new FileStream(@"C:\file", FileMode.Open, FileAccess.Read))\n{\n    using (var reader = new BinaryReader(fs, new ASCIIEncoding()))\n    {\n        byte[] buffer = new byte[10];\n        buffer = reader.ReadBytes(10);\n        if(buffer[0] == 31 && buffer[1] == 139 && buffer[2] == 8)\n            // you have a signature match....\n    }\n}	0
21364347	21364192	testing data pattern in excel file	Regex rx = new Regex("^(?:0?[0-9]|1[0-9]|2[0-3]):[0-5][0-9]:[0-5][0-9]$");\nif (rx.Match(str).Success)\n{\nlistBox1.Items.Add(str);\n}	0
12029670	12021428	NHibernate Join Table Mapping has repeated objects	public class Category\n{\n    public virtual IDictionary<Locale, string> Names { get; private set; }\n\n    public virtual string Name { get { return Names[GetActiveLocaleFromSomewhere()]; } }\n}\n\npublic CategoryMap()\n{\n    HasMany(x => x.Names)\n        .Table("CategoryLocale")\n        .KeyColumn("CategoryId")\n        .AsEntityMap("LocaleId")\n        .Element("CategoryName")\n}	0
34396730	34396632	How to order a list alphabetically depending on another list	var model = _service.List()\n    .OrderBy(o => o.GroupId)\n    .ThenBy(x => x.Company)\n    .ToList()\nreturn View(model);	0
23926781	23926584	In c# I would like to increment an integer every time another integer increases by a set amount	class Whatever\n{\n    private int extraLifeRemainder;\n\n    private int totalScore;\n    public int TotalScore\n    {\n        get { return totalScore; }\n        set\n        {\n            int increment = (value - totalScore);\n            DoIncrementExtraLife(increment);\n            totalScore = value;\n        }\n    }\n\n    public int ExtraLife { get; set; }\n\n    private void DoIncrementExtraLife(int increment)\n    {\n        if (increment > 0)\n        {\n            this.extraLifeRemainder+= increment;\n            int rem;\n            int quotient = Math.DivRem(extraLifeRemainder, 5, out rem);\n            this.ExtraLife += quotient;\n            this.extraLifeRemainder= rem;\n        }\n    }\n}\n\nprivate static void Main()\n{\n    Whatever w = new Whatever();\n    w.TotalScore += 8;\n    w.TotalScore += 3;\n\n    Console.WriteLine("TotalScore:{0}, ExtraLife:{1}", w.TotalScore, w.ExtraLife);\n    //Prints 11 and 2\n}	0
10750050	10677934	Fluent nhibernate copy of a child object	void UpgradeToCustomer(Prospect p)\n{\n    var customer = new Customer\n    {\n        Entity = p.Entity\n    };\n\n    p.Entity = null; // prevent cascading\n\n    session.Delete(p);\n    session.Save(customer);\n}	0
1983210	1982916	How to revert back to 'default' XML serialization when implementing IXmlSerializable in a base class?	[Serializable]\n[TypeDescriptionProvider(typeof(PropertyBagDescriptionProvider))]    \npublic abstract class PropertyBagWrapper\n{\n    [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)]    \n    public PropertyBag DynamicProperties { get; set; }\n\n    public object this[string name]\n    {\n        get { return DynamicProperties[name]; }\n        set { DynamicProperties[name] = value; }\n    }\n    protected PropertyBagWrapper()\n    {\n        DynamicProperties = new PropertyBag(this.GetType());\n    }\n}\n\n[Serializable]    \npublic class Person : PropertyBagWrapper\n{\n    [Browsable(true)]\n    public string Name { get; set; }\n}	0
69985	69277	Rhino Mocks: How do I return numbers from a sequence	var meas = new int[] { 3, 6, 9, 12, 15, 18 };\nusing (mocks.Record())\n{\n    int forMockMethod = 0;\n    SetupResult.For(mocked_class.GetValue()).Do(\n    new Func<int>(() => meas[forMockMethod++])\n    );\n}\n\nusing(mocks.Playback())\n{\n    foreach (var i in meas)\n    Assert.AreEqual(i, mocked_class.GetValue());\n}	0
10630475	10597005	C# Regex for URL's	String regex = @"(?<!(""|'))((http|https|ftp|file):\/\/|www\.|ftp\.)(?:\([-A-Z0-9+&@#\/%=~_|$?!:;,.]*\)|[-A-Z0-9+&@#\/%=~_|$?!:;,.])*(?:\([-A-Z0-9+&@#\/%=~_|$?!:;,.]*\)|[A-Z0-9+&@#\/%=~_|$])";	0
18299815	18299807	What the Error in my Regex to to check a string contains a-z or A-Z	if (! pattern.IsMatch(txtCustName.Text))	0
30102734	29212311	Get xml child elements from parent via button to new form	foreach (var m in menu)\n            {\n                //display button array\n            }\n            foreach (var sectionItem in m.sectionItems.Where(x => x.itemGroupID == m.sectionID))\n            {\n                //display sub in textbox & combobox array\n            }	0
1657945	1657864	How to pass an unknown type to a function?	MethodInfo mi = typeof(AuditLogger).GetMethod("GetAuditLogRecord");\nType[] genericArguments = new Type[] { original.GetType() };\nMethodInfo genericMI = mi.MakeGenericMethod(genericArguments);\nAuditLog au = \n    (AuditLog)genericMI.Invoke(\n        null, new object[] { original, update, "", userName });	0
4360037	4359934	return multiple rows from an asmx service	public class sample\n    {\n        public string val1;\n        public string val2;\n\n    }\n[WebMethod]\npublic sample[] UpdateBold(int count, float lat, float lng)\n\n{\n\n            DataTable dt = new Gallery().DisplayNearestByLatLong(count, lat, lng);\n            var samples = new List<sample>();\n\n            foreach(DataRow item in dt.Rows)\n            {\n                var s = new sample();\n                s.val1 = item[0].ToString();\n                s.val2 = item[1].ToString();\n                samples.Add(s);\n            }\n            return samples.ToArray();\n}	0
8486925	8486901	The ObjectContext instance has been disposed - Even with a using(context) statement and ToList()	public ActionResult Index()\n{\n    var IndVM = new IndexVM();\n    using (QuoteContext QDomain = new QuoteContext())\n    {\n        QDomain.ContextOptions.LazyLoadingEnabled = false;\n        // Query and populate IndVM here...\n    }\n    return View(IndVM);\n}	0
4099079	4088469	How to add an attribute to an XML with a count of that element with an element	public XDocument FormatcountPreProcData(XDocument inputDoc)\n    {\n        if (inputDoc != null)\n        {\n            var elementsToChange = inputDoc.Elements("NEWFILE").Elements("NEWRECORD").Elements();\n\n            foreach (var element in elementsToChange)\n            {\n                if (element.Descendants().Any())\n                {\n                    Int32 count = inputDoc.Elements("NEWFILE").Elements("NEWRECORD").Elements(element.Name.ToString()).Count();\n                    element.Add(new XAttribute("count", count));\n                }\n            }\n        }\n        return inputDoc;\n    }	0
7097675	7097624	How to create array DbParameter[]	var parameters = new[]{\n            new SqlParameter(){ ParameterName="foo", Value="hello" },\n            new SqlParameter(){ ParameterName="bar", Value="World" }\n        };\nx.ExecuteScalar<int>(commandText, commandType, parameters);	0
29681298	29681164	How to extend an Interface?	public interface BaseInterface\n{\n    string FirstName { get; set; }\n    string LastName { get; set; }\n\n    void Method1();\n}\n\npublic interface ExtendedInterface\n{\n    string FulllName { get; set; }\n\n    void Method2();\n}\n\npublic class ClassA : BaseInterface\n{\n    public string FirstName { get; set; }\n    public string LastName { get; set; }\n\n    public void Method1()\n    { \n    }\n}\n\npublic class ClassB : BaseInterface, ExtendedInterface\n{\n    public string FirstName { get; set; }\n    public string LastName { get; set; }\n\n    public string FullName { get; set; }\n\n    public void Method1()\n    {\n    }\n\n    public void Method2()\n    {\n    }\n}	0
6554482	6554380	How to get the parameters passed to the asynchronous method in the callback	var registrationToUser = ...;\n    var label = ...;\n\n    sendRegistrationDelegate.BeginInvoke(registrationToUser, label, ar =>\n    {\n        var responceFromServer  = sendRegistrationDelegate.EndInvoke(ar);\n        if (responceFromServer.IsError)\n        {\n            label.Text = "";\n        }\n        else\n        {\n\n        }\n    }, null);	0
17687508	17687484	Combine each element from Array 1 with each element from Array 2	var result = from x in array1\n             from y in array2\n             select string.Format("{0} {1}", x, y);	0
12821848	12820182	Dynamicaly add 2nd control after 1st control	int glHeightAccumalator = Control.Height; ' I would set this on the form load when you already have your first control in the Flow Layout Panel.\n\n''Button Click Event\n\nControl ctrl = new Control();\nctrl.Location = Drawing.Point(ctrl.Location.X, glHeightAccumalator);\nFlowLayoutPanel.Controls.Add(ctrl);\nglHeightAccumalator += ctrl.Height;	0
15700236	15699752	How to access unbounded Item in DataList	var myTable = (Table)DataListProducts\n             .Controls[0]\n             .FindControl("TableCategories");	0
4145151	4145111	can request querystring be accessed from htmlhelper	public static string DoThis(this HtmlHelper helper)\n{\n   string qs = helper.ViewContext.HttpContext.Request.QueryString.Get("val");\n   //do something on it\n}	0
25061174	25061119	Unable to reach Object from void - C#	SqlConnection SQLObject = new SqlConnection("Data Source = {SourceRemoved}; user id={UserRemoved}; password={Removed}; Initial Catalog = Testing;");	0
31247594	31197636	Create a SuiteTalk transaction search that gets all sales order with a certain status	status = new SearchEnumMultiSelectField() {\n    @operator = SearchEnumMultiSelectFieldOperator.anyOf,\n    operatorSpecified = true,\n    searchValue = new string[] {\n        "_salesOrderPendingApproval"\n    }\n\n}	0
2129038	2128711	C# how to trigg a key event in a tabcontrol specific tab?	protected override bool ProcessCmdKey(ref Message m, Keys keyData)  \n        {  \n            bool blnProcess = false;  \n            if (keyData == Keys.Left)  \n            {  \n                blnProcess = true;  \n                MessageBox.Show("Key left");  \n                if (myTabControl1.SelectedIndex == 1)  \n                    MessageBox.Show("inside");  \n\n\n             }\n       }	0
1196273	1196217	Reading SQL column name from querystring and building secure query from it	[this [should]] be a valid name too]	0
16639450	16639435	How can i change the Image to be in the same size of the pictureBox?	PictureBox1.SizeMode = PictureBoxSizeMode.Zoom;	0
3910694	3910671	Getting Folder Name(s) from Path	Path.GetFileName(Path.GetDirectoryName(something))	0
13085523	13085416	Get items selected from another form	TextBox activeText;\n    private void txtBox1_Enter(object sender, EventArgs e)\n    {\n          lstMyList.dataSource = list1Data;\n          activeText = (TextBox)sender;\n\n    }\n\n    private void lstMyList_SelectedValueChanged(object sender, EventArgs e)\n    {\n         ListBox myList = (ListBox)sender; \n         activeText.Text = myList.SelectedValue.ToString();\n\n    }	0
11759381	11759346	Create a defined number of Label in a for loop	List<Label> labels = new List<Label>();\nfor (int i = 0; i < 10; i++)\n{\n    Label label = new Label();\n    // Set properties here\n    labels.Add(label);\n}	0
2879052	2878886	A controller method that calls a different method on the same controller	public ActionResult ManipulatorMethod(int id) \n{ \n    //[stuff that manipulates id] \n    int _id = id++;\n\n    //[syntax to call Details(manipulatedID)] \n    return RedirectToAction("Details", new { id = _id });\n}	0
11782244	11780621	How do you extract the user data from the xml and send it to a string?	System.Xml.XmlDocument xmlDoc = new System.Xml.XmlDocument();\nTwitterUser user = new TwitterUser();\n\nstring url = "http://api.twitter.com/1/account/verify_credentials.xml";\nstring xml = oAuth.oAuthWebRequest(oAuthTwitter.Method.GET, url, String.Empty);\n\nxmlDoc.LoadXml(xml);\n\nuser.id = xmlDoc.SelectSingleNode("user/id").InnerText;\nuser.screen_name = xmlDoc.SelectSingleNode("user/screen_name").InnerText;\nuser.name = xmlDoc.SelectSingleNode("user/name").InnerText;	0
2562676	2562542	FileSystemWatcher running under impersonated user	using ( new Impersonator( "myUsername", "myDomainname", "myPassword" ) )\n{\n   ...\n\n   <code that executes under the new context>\n\n   ...\n}	0
27721540	27721433	How to Display Splashscreen and login form at same time using c#	private void Form1_Load(object sender, EventArgs e)\n{\n    var f = new SplashImageForm ();\n    f.Show( this );\n}	0
9309698	9264065	Is it possible to go back automatically into the application after calling a Number?	this.btnCall.TouchUpInside+= delegate {\n\n        UIWebView web = new UIWebView();\n            NSUrl url = new NSUrl("tel:07777777777");\n\n        web.LoadRequest(new NSUrlRequest(url));\n\n\n        };	0
22317283	22311242	Drag textbox in a grid	private void Handle_Drag(object sender,System.Windows.Input.ManipulationDeltaEventArgs e)\n    {\n        TextBox Text = sender as TextBox;\n\n        var parent = Text.Parent as Grid;\n        if (parent  != null)\n        {\n            parent.Children.Remove(Text);\n            myCanvas.Children.Add(Text);\n        }\n\n        Text.Text = "I'm moved";\n        double currentX = Canvas.GetLeft(Text);\n        double currentY = Canvas.GetTop(Text);\n\n        MessageBox.Show(currentX.ToString());\n        MessageBox.Show(currentY.ToString());\n\n        Canvas.SetLeft(Text, currentX + e.DeltaManipulation.Translation.X);\n        Canvas.SetTop(Text, currentY + e.DeltaManipulation.Translation.Y); \n    }	0
531741	531659	C#: How to know whether certain Office 2003 or 2007 application is installed?	HKLM\SOFTWARE\Microsoft\Office\12.0\Word\InstallRoot	0
19268923	19268588	Sql query execution inside a for loop	SqlCommand cmd4 = new SqlCommand("update TrackingFaculty_det " + \n                                    "SET EmailsentDate=@Email WHERE FID=@FID", cn1);\n   cn1.Open();\n   cmd4.Parameters.Add("@Email", SqlDbType.DateTime, 8);\n   cmd4.Parameters.Add("@FID",SqlDbType.VarChar,10);\n   for (int i = 0; i <= GridView1.Rows.Count - 1; i++)\n   {\n       .....\n       if (Ckbox.Checked == true)\n       {\n          ....\n          cmd4.Parameters["@Email"].Value = sdt;\n          cmd4.Parameters["@FID"].Value = FID1;\n          cmd4.ExecuteNonQuery();\n       }\n   }\n   cn1.Close();	0
25047314	25046202	Trouble with foreign key and inserting record with EF	modelBuilder.Entity<MatchedInstrument>().HasKey(m => m.Id)\n       .HasRequired(m => m.Instrument)\n       .WithMany().HasForeignKey(m => m.InstrumentId);	0
21488785	21488496	Merge nodes of the same kind to a single node	XmlDocument myDocument = new XmlDocument();\n           myDocument.Load(XMLFile);\n           var NodeToadd = myDocument.ChildNodes.OfType<XmlElement>().Where(nodeVariant => nodeVariant.Name == "Clubs").SelectMany(o => o.ChildNodes.OfType<XmlElement>()).ToList();\n           var nodeToDelete = myDocument.ChildNodes.OfType<XmlElement>().Where(nodeVariant => nodeVariant.Name == "Clubs");\n           foreach (var m in nodeToDelete)\n           {\n               myDocument.RemoveChild(m);\n           }\n             XmlNode newNode = myDocument.CreateElement("Clubs");\n            foreach(var m in NodeToadd)\n            {\n            newNode.AppendChild(m);\n            }\n            myDocument.AppendChild(newNode);\n            myDocument.Save(XMLFile);	0
4672154	4672112	entity variable get list based on where	var aCategories = from cat in context.Categories\n                  where cat.StartsWith("a")\n                  select cat;	0
7754392	7754353	Round to the next higher number	Math.Ceiling(v / 2.5) * 2.5	0
17589346	16717427	EAGetMail, How to read all emails from POP3 Gmail server?	private void readMails(){\n        MailServer oServer=new MailServer("imap.gmail.com", "something@gmail.com", "noneedtoseethis", ServerProtocol.Imap4);\n        MailClient oClient = new MailClient("Client");\n        oServer.SSLConnection = true;\n        oServer.Port = 993;\n        try {\n            oClient.Connect(oServer);\n            MailInfo[] infos = oClient.GetMailInfos();\n            Console.WriteLine(infos.Length);\n            for (int i = 0; i < infos.Length; i++){\n                MailInfo info = infos[i];\n                Mail oMail = oClient.GetMail(info);\n\n                Console.WriteLine("From: {0}", oMail.From.ToString());\n                //oClient.Delete(info);\n            }\n            oClient.Quit();\n        } catch (Exception ep) {\n            Console.WriteLine(ep.Message);\n        }\n    }	0
27253435	27253089	How can i set selected item property from the list using code behind?	for (int i = 0; i < myGroupList.Items.Count; i++)\n    {\n        if (element.Children[i].InnerText == "abc_group")\n        {\n            element.SetAttribute("selected", "selected");\n            break;\n        }\n    }	0
6077406	6077125	How can I access active directory to load email groups into an array?	string domainName = "yourDomain";\n        DirectoryEntry entry = new DirectoryEntry("LDAP://DC=" + domainName + ",DC=com");\n        DirectorySearcher search = new DirectorySearcher(entry);\n        string query = "(&(&(& (mailnickname=*) (| (objectCategory=group) ))))";\n        search.Filter = query;\n        search.PropertiesToLoad.Add("name");\n\n        SearchResultCollection mySearchResultColl = search.FindAll();\n\n        List<string> groups = new List<string>();\n\n        foreach (SearchResult sr in mySearchResultColl)\n        {\n            DirectoryEntry de = sr.GetDirectoryEntry();\n            groups.Add(de.Properties["Name"].Value.ToString());\n        }	0
25882259	25881235	C# Custom Assembly Directory	AppDomain.CurrentDomain.AssemblyResolve += new ResolveEventHandler(CurrentDomain_AssemblyResolve);\n\nprivate Assembly CurrentDomain_AssemblyResolve(object sender, ResolveEventArgs e)\n{\n    Assembly ass = Assembly.LoadFile(AppDomain.CurrentDomain.BaseDirectory + "\\Libraries\\" + e.Name.Split(new char[] { ',', ' ' })[0] + ".dll");\n    return ass;\n}	0
3364407	3364286	Read specific data from XML file	XmlDocument xDoc = new XmlDocument();\nxDoc.Load(yourXml)\nvar nodes = xDoc.SelectNodes(nodeName);	0
1665967	1665941	C# 30 Days From Todays Date	string dateInString = "01.10.2009";\n\nDateTime startDate = DateTime.Parse(dateInString);\nDateTime expiryDate = startDate.AddDays(30);\nif (DateTime.Now > expiryDate) {\n  //... trial expired\n}	0
18717774	18716802	Merge multiple xml files into one using linq to xml	private void BindDataInGrid(string[] argFilePaths)\n{\n    List<Parent> recordsList = new List<Parent>();\n\n        for (int i = 0; i < argFilePaths.Length; i++)\n        {\n           recordsList.AddRange\n               (\n                     XDocument.Load(argFilePaths[i]).Root.Descendants("Resident")\n                     .Select(data => new Parent()\n                     {\n                         Child1 = data.Element("Child1").Value,\n                         Child2 = data.Element("Child2").Value,\n                     }).ToList()\n                );\n        }\n}	0
2860364	2684954	Silverlight 4 Data Binding with anonymous types	[assembly: System.Runtime.CompilerServices.InternalsVisibleTo("System.Windows")]	0
4766234	4766171	After creating separate Models and Controllers projects, I get "no suitable method found to override" on my Initialize method declaration	using System.Web.Routing	0
8171818	8170921	Using data retrieved from custom action in installation location	[ProgramFilesFolder][Manufacturer] [ProductName] [INSTANCE]	0
11474665	11474505	C# File Association: passing double clicked file path to string	public static void Main(string[] args){            \n     if (args.Length == 0){\n       // Show your application usage or show an error box              \n       return;\n     }\n     string file = args[0];\n     Application.Run(new MyProgram(file));           \n}	0
1361035	1360931	Data Bind a WPF Listbox?	ItemsSource="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Window}}, Path=Categories}"	0
25973343	25972982	Keeping PInvoked method alive	static FirstScanForDevicesDoneFunc callbackDelegate;\n\n   static public void Init() {\n        callbackDelegate = new FirstScanForDevicesDoneFunc(FirstScanForDeviceDone);\n        Initialize(callbackDelegate);\n   }	0
12895965	12895885	give same property to all textbox controls	private void SetProperty(Control ctr)\n    {\n        foreach(Control control in ctr.Controls)\n        {\n            if (control is TextBox)\n            {\n                control.ContextMenu = new ContextMenu();               \n            }\n            else\n            {\n                if (control.HasChildren)\n                {\n                    SetProperty(control);\n                }                    \n            }\n        }\n    }	0
8998003	8997614	Create type parameter based on another value	var dispatches = new Dictionary<LocationType, Action<int, int>>();\ndispatches.Add(LocationType.Country, SomeMethod<DataCountry>);\ndispatches.Add(LocationType.State, SomeMethod<DataState>);\n//... and etc.\n\ndispatches[LocationType.Country](1, 2); // the same as SomeMethod<DataCountry>(1,2)	0
19804277	19804213	best practice for parsing a complex json string	var channel = wInfo.query.results.channel;\nvar title = channel.title;\nvar link = channel.link;	0
11892304	11892272	Find specific bit value in c# binary string	int val = s[28 - 1] - '0';  ///////	0
20000838	20000806	Replaying a video continuously in a WPF media element	me.Position = TimeSpan.FromSeconds(0);\nme.Play();	0
8613345	8558770	Read values from a datatable of a dataset	string _seperator1 = "-------------------------------------------------------------------------------------------------------------------------------- \n"; \nstring isbn = _tbIsbnSuche.Text;\nDataView custView = new DataView(_dset.Tables["Book"], "", "ISBN", DataViewRowState.CurrentRows);\n{\n    _lBdatenOutput.Items.Clear(); //Delete existing Objects from the Output\n    foreach (DataRowView myDRV in custView)\n    {\n        DataRow dr = myDRV.Row;\n        if((dr["ISBN"].ToString().IndexOf(isbn) >= 0))\n        {\n            foreach (DataColumn cl in custView.Table.Columns)\n            {\n                _lBdatenOutput.Items.Add("Spalten-Name:  " + " \t " + cl.ColumnName + " \t" + dr[cl]);\n            }\n            _lBdatenOutput.Items.Add(_seperator1); //Insert a seperator\n        }\n    }\n}	0
21379504	21379444	What data structure do I need or how to implement a "LIFO-like" queue?	public class DroppingStack<T> : IEnumerable<T>\n{\n    T[] array;\n    int cap;\n    int begin;\n    int end;\n    public DroppingStack (int capacity)\n    {\n        cap = capacity+1;\n        array = new T[cap];\n        begin = 0;\n        end = 0;\n    }\n\n    public T pop()\n    {\n        if (begin == end) throw new Exception("No item");\n        begin--;\n        if (begin < 0)\n            begin += cap;\n        return array[begin];\n    }\n\n    public void push(T value)\n    {\n        array[begin] = value;\n        begin = (begin+1)%cap;\n        if (begin == end)\n            end = (end + 1) % cap;\n    }\n\n    public IEnumerator<T> GetEnumerator()\n    {\n        int i = begin-1;\n        while (i != end-1)\n        {\n            yield return array[i];\n            i--;\n            if (i < 0)\n                i += cap;\n        }\n    }\n\n    System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()\n    {\n        return this.GetEnumerator();\n    }\n}	0
23911171	23891152	Have I Structure Map with Entity Framework constructed correctly with Context management in a wcf project	For<Entities>().LifecycleIs(new WcfInstanceContextLifecycle()).Use(c\n=> new Entities());	0
20410109	20410043	C# custom object in combobox	((Reviewer)UserList.CheckedItems[i]).GetID()	0
747917	747893	How to accept any kind of number into a function as an argument in C#?	public void AddData (Int32 i)\n{...}\n\npublic void AddData (Int16 i)\n{...}	0
22928200	22928073	DataGridView editing	protected void myGridView_RowUpdating(object sender, GridViewUpdateEventArgs e)\n        {\n            string id=// To find key of current row. e.g: myGridView.DataKeys[e.RowIndex].Value.ToString();\n            string text=//To find the text value from the current row.\n            conn.Open();\n            SqlCommand UpdateCmd = new SqlCommand(" your query");\n            UpdateCmd.ExecuteNonQuery();\n            conn.Close();\nGridView1.EditIndex = -1; //After updating, please set EditIndex and re-bind the GridView.\n            BindGridView();\n    }	0
23077110	23076961	how to delete a single value from mysql table	DELETE FROM cms.wine WHERE price = '300' LIMIT 1	0
9352782	9346926	Trying to create a default ASP.NET MVC Route with AttributeRouting	[RouteArea("Documentation")]\npublic class DocumentationController : Controller\n{\n    [GET("Index", Order = 1)] // will handle "/documentation/index"\n    [GET("")] // will handle "/documentation"\n    [GET("", IsAbsoluteUrl = true)] // will handle "/"\n    public ActionResult Index()\n    {\n        return View();\n    }\n}	0
15262221	15261877	How to check if a node has a single child element which is empty?	static void Main(string[] args)\n{\n    var xml = @"<root><child><thenode>hello</thenode></child><child><thenode></thenode></child></root>";\n    XDocument doc = XDocument.Parse(xml);\n\n    var parentsWithEmptyChild = doc.Element("root")\n        .Descendants() // gets all descendants regardless of level\n        .Where(d => string.IsNullOrEmpty(d.Value)) // find only ones with an empty value\n        .Select(d => d.Parent) // Go one level up to parents of elements that have empty value\n        .Where(d => d.Elements().Count() == 1); // Of those that are parents take only the ones that just have one element\n\n\n    parentsWithEmptyChild.ForEach(Console.WriteLine);\n\n    Console.ReadKey();\n}	0
4739955	4739946	Sorting a list with null values	var sortedList = listOfPeople\n                 .OrderBy(p => p.DateOfBirth.HasValue)\n                 .ThenBy(p => p.DateOfBirth);	0
7687104	7685148	Rendering a program icon to the Image Control using TPL	bi.Freeze();	0
2872765	2872741	Dynamically Add iFrame to a Page?	PlaceHolder1.Controls.Add(new LiteralControl("<iframe src='mypage.aspx'></iframe>"));	0
12493687	12493641	Entity with default filter on EF	partial class DatabaseContext // same name as your generated context\n{\n    IQueryable<Client> ActiveClients { get { return Clients.Where(c => c.active == 1); } }\n}	0
7367100	7356677	Stored Procedure not being recognized in LINQ to SQL as a ISingleResult	using System.Data.Linq	0
3655100	3655030	How to disambiguate a call to member that takes a string or parameter list	ShowMessage ("Unable to load file {0}", (object) myStringFilename);	0
4775002	4774265	Set anonymous type to null	static List<T> GimmeANullListOf<T>(T t) { return (List<T>)null; }\n...\nvar products = GimmeANullListOf(new { X = 1, Y = "hello" });	0
9423871	9417929	Using regular expressions to remove all the GOs in a sql script file	(?i-msnx:\b(?<!-{2,}.*)go[^a-zA-Z])	0
10350756	10350699	Replace the first occurrence in a string	string x = "Hello my name is Marco";\n  int index = x.IndexOf(" ");\n  x= index >=0 ? x.Insert(index, @"<br />") : x;	0
8694290	8694235	Attach event to dynamic object	public delegate void eReadyHandler();\n\nstatic void Main(string[] args)\n{\n    var comType = Type.GetTypeFromProgID("PDFCreator.clsPDFCreator");\n    dynamic pdfCreator = Activator.CreateInstance(comType);\n    //dynamic pdfCreator = new PDFCreator.clsPDFCreator();\n\n    //pdfCreator.eReady = null;\n    pdfCreator.eReady += new eReadyHandler(_PDFCreator_eReady);\n}\n\npublic static void _PDFCreator_eReady()\n{\n\n}	0
24605643	24604843	Getting data from xml with specific data name and value key	var doc = XDocument.Parse(xml);\nXNamespace d = doc.Root.GetDefaultNamespace();\nvar result = (string)\n    doc.Descendants(d + "Data")\n       .Elements(d + "Value")\n       .FirstOrDefault(o => (string) o.Attribute("key") == "Error")\n       .Attribute("value");\nConsole.WriteLine(result);	0
20124019	20123983	Custom Where expression	public static IQueryable<T> WhereValidOnDate<T>(this IQueryable<T> source, DateTime other)\n   where T : IValid\n{\n    return source.Where(x => x.From<= other && (x.To == null || x.To <= DateTime.Today));\n}	0
34433934	34433685	Querying a list of key value pair	tableIds.GroupBy(v => v.Key).Where(c => c.Count() > 1).SelectMany(c=> c).ToList()	0
11688958	11688764	Not able to open second page of my wpf browser application in a new browser window?	1. Add a new window NewWindow  \n\n2. var newWindow= new NewWindow();\nnewWindow.Show(); // works\n\n//Or use ShowDialog, if parant wait close of child window\nnewWindow.ShowDialog();	0
29558434	29447370	Wp8 cant find csv file in project	var dest = App.GetResourceStream(new Uri(@"StartUpViewModels/" + destination, UriKind.Relative));	0
3375367	3375342	Iterate through databound listbox	protected void lstInstructors_DataBound(object sender, EventArgs e)\n{\n    foreach (object o in arrList)\n    {\n        foreach (ListItem i in lstInstructors.Items)\n        {\n            if (i.Text == o.ToString())\n                i.Selected = true;\n        }\n    }\n}	0
19825721	19825669	C# Setting a maximum / minimum return of an Int or Float	public int Speed\n{\n  get\n  {\n     return CurrentSpeed + CarAcceleration;\n  {\n}\n\npublic int CarAcceleration{\n    get\n    { \n        if(Speed >= MaxSpeed)\n        {\n            return MaxSpeed\n        }\n\n        return Speed;\n    }\n    set;\n    }	0
11705174	11704978	Extracting URL from string	using System.Text.RegularExpressions;\n\npublic static List<string> ParseUrls(string input) {\n    List<string> urls = new List<string>();\n    const string pattern = "http://"; //here you may use a better expression to include ftp and so on\n    string[] m = Regex.Split(input, pattern);\n    for (int i = 0; i < m.Length; i++)\n        if (i % 2 == 0){\n            Match urlMatch = Regex.Match(m[i],"^(?<url>[a-zA-Z0-9/?=&.]+)", RegexOptions.Singleline);\n            if(urlMatch.Success)\n                urls.Add(string.Format("http://{0}", urlMatch.Groups["url"].Value)); //modify the prefix according to the chosen pattern                            \n        }\n    return urls;\n}	0
5675212	5674939	C# HTML table from a website to a Datagridview	Html Agility Pack	0
10257344	10257277	How to change datagrid cell fore colors as dynamically using c#	dataGridView1[col, row].Style.ForeColor = Color.Blue;	0
2493539	2493495	Open "Folder Options" dialog programmatically	ProcessStartInfo psi = new ProcessStartInfo\n   {\n       FileName = "RUNDLL32.EXE",\n       Arguments = "shell32.dll,Options_RunDLL 0"\n   };\nProcess.Start(psi);	0
24635626	24635482	CreateInstance from Type name and Assembly name	var type = typeof(IAssessmentObject).Assembly\n                                    .GetTypes()\n                                    .Single(t => t.Name == "Question");\nvar instance = (IAssessmentObject) Activator.CreateInstance(type);	0
26387163	26377866	Differentiate Route Based On QueryString in Web API	[RoutePrefix("api/pagination")]\npublic class MyController\n{\n    [HttpGet]\n    [Route("users")]\n    public IEnumerable<Users> GetUsers() { }\n\n    [HttpGet]\n    [Route("users-paginated")]\n    public IHttpActionResult UsersPagination(int startindex = 0, int size = 5, string sortby = "Username", string order = "DESC") { }\n}	0
23989748	23989674	TreeListView.RowDetailsTemplate new for each row	Value="{Binding Number}"	0
6724249	6724174	How to update all the values in a Dictionary<string, bool>	List<string> keys = new List<string>(parameterDictionary.Keys);\nforeach (string key in keys)\n  parameterDictionary[key] = false;	0
16529139	16529064	Put a Session variable into a textbox	if(Session["customerID"] != null)\n{\n  TextBox1.Text = Session["customerID"].ToString();\n}	0
18031847	18031668	How do I display images in a Windows Forms Application without knowing the number of images that need to be displayed?	string path = @"D:\";\nvar query = from f in Directory.GetFiles(path, "*.jpg")\n            select new { Path = f, FileName = Path.GetFileName(f) };\n\nvar files = query.ToList();\npictureBox1.DataBindings.Add("ImageLocation", files, "Path");\nlabel1.DataBindings.Add("Text", files, "FileName");\ndataRepeater1.ItemHeaderVisible = false; // to hide headers\ndataRepeater1.DataSource = files;	0
11865530	11864557	MediaPlayerLauncher on WP7 - how to resume previously playing media?	mpl.Media = new Uri(trailerurl, UriKind.Absolute);\nmpl.Controls = MediaPlaybackControls.All;\nmpl.Show();\n\nMediaPlayer.Resume();	0
16314204	16313765	How can I get this string replacement in hebrew to work?	public void Fancy_placeholder_should_be_replaced()\n    {\n        const string input = "(???? @%1$ ??? ??? (@%2$ ????? ?????";\n        const string expected = "(???? {0} ??? ??? ({1} ????? ?????";\n\n        var formatted = input.Replace("@%2$", "{1}");\n        formatted = formatted.Replace("@%1$", "{0}");\n\n        bool same2 = expected == formatted;\n        Assert.AreEqual(expected, formatted);\n    }	0
11332761	9318895	How to integrate WebSockets on top of a classic ASP web application?	routes.IgnoreRoute("{resource}.asp/{*pathInfo}");	0
158675	158634	Doing a Cast Within a LINQ Query	from TabSection t in content.ChildControls	0
19341266	19341241	Can I use the same local variables for two different events in C#?	private int number1; // Declared at the form level\nprivate int number2; \nprivate void GenerateRandoms()\n{\n    // create random number variable\n    Random randomNumber = new Random();\n    number1 = randomNumber.Next(100, 501);\n    number2 = randomNumber.Next(100, 501);\n    ...\n}\nprivate void checkButton_Click(object sender, EventArgs e)\n{\n    int answer = number1 + number2;\n    ...\n}	0
4774481	4774472	Implementing a bubble sort to a class with multiple variable types in C#	private string text = "";\n\npublic string Text\n{\n  get { return text; }\n  set { text = value; }\n}	0
21580876	21580537	How to comment an XMLElement using C#?	XmlComment DirCom = doc.CreateComment(XmlElementName.OuterXml);\ndoc.InsertAfter(DirCom, XmlElementName);    \ndoc.RemoveChild(XmlElementName)	0
33254638	33254562	How to delete datarow cells from certain index?	for(int cellIndex = 6; cellIndex < dtSecondTab.Columns.Count; cellIndex++)\n{\n    dtSecondTab.Rows[i][cellIndex] =  DBNull.Value;\n}	0
27047135	27044989	How do I find out which button clicked inside asp:AsynPostBackTrigger?	if (Page.IsPostBack)\n{\n    string eventArgument = Request.Params["__EVENTARGUMENT"];\n    string eventTarget = Request.Params["__EVENTTARGET"];\n}	0
31414775	31412381	How can I close a video with MediaElement?	PlayTour.Stop();	0
32523627	32523098	Using Xpath to select single node, when node contains namespace	XmlNode md5_node = xmlDoc.SelectSingleNode("//msbld:UploadIsoResponse/msbld:md5", ns);\n     XmlNode md5_status_node = xmlDoc.SelectSingleNode("//msbld:UploadIsoResponse/msbld:status", ns);	0
15947566	15947150	Exception while trying to save an image into Media Library in Windows Phone 8	private bool SavePhotoToImageHub(WriteableBitmap bmp)\n    {\n\n        using (var mediaLibrary = new MediaLibrary())\n        {\n            using (var stream = new MemoryStream())\n            {\n                var fileName = string.Format("Gs{0}.jpg", Guid.NewGuid());\n                bmp.SaveJpeg(stream, bmp.PixelWidth, bmp.PixelHeight, 0, 100);\n                stream.Seek(0, SeekOrigin.Begin);\n                var picture = mediaLibrary.SavePicture(fileName,stream);\n                if (picture.Name.Contains(fileName)) return true;\n            }\n        }\n        return false;\n    }	0
30030892	30002437	Strange mapping behaviour from String to Boolean	public static class LinkerHelper {\n    public static object BecauseAzureDeploymentsAreDumb() {\n        var foo = typeof(HashSetMapper);\n        return foo;\n    }\n}	0
6452506	6452278	Entity Framework and MVC applications - How	ctx.Baskets.AddObject(newBasket)	0
6065642	6065623	How to explicitly initialize array of enums [C#]	public Class1()\n    {\n        myEnum = new MyEnum[]\n        {\n            MyEnum.First,\n            MyEnum.First,\n            MyEnum.First\n        };\n    }	0
22019338	22019267	How to limit the number a loop does in C#	int count = 0;\nwhile (purchase != QUIT && ++count < 5)	0
18310826	18310738	Search for something in HTML C#	string strRegex = @"http.*720.mp4";\nRegexOptions myRegexOptions = RegexOptions.None;\nRegex myRegex = new Regex(strRegex, myRegexOptions);\nstring strTargetString = @"<html> " + "\n" + @"    ....." + "\n" + @"    <script>" + "\n" + @"        {" + "\n" + @"           http:\\\/\\\/cs513404v4.vk.me\\\/u3692175\\\/videos\\\/49a2e8d28c.720.mp4 " + "\n" + @"        }" + "\n" + @"        ....." + "\n" + @"    </script>" + "\n" + @"  </html>";\n\nforeach (Match myMatch in myRegex.Matches(strTargetString))\n{\n  if (myMatch.Success)\n  {\n    // Add your code here\n  }\n}	0
12090982	12090952	How can I make my console application call a function when a key is pressed?	Console.ReadKey();	0
11692423	11692329	Finding an item within a list within another list?	List<Car> cars = ...\nvar carToFind = cars.FirstOrDefault(car => car.Parts.Any(part => part.Id == idToFind));	0
30970523	30970479	Unable to download file into AppData folder	IIS AppPool\DefaultAppPool	0
12767595	12748467	How to add image to a Border object in WP7	// Assume you have a border named Border1\nBorder1.Child = new Image() { /* ... */ };	0
11161984	11159119	cant get data to save using element host	CarView car = (CarView) CarHost.Child;\n        CarViewModel cvm = (CarViewModel) car.DataContext;	0
9972714	9617372	I am merging two Word documents with OpenXML SDK but get a corrupt document when copying an image into a header	private MemoryStream _memoryStream;\n    private WordprocessingDocument _wordDocument;\n      ...\n    _wordDocument = WordprocessingDocument.Open(_memoryStream, true);\n      ... \n\n    private void ReopenDocument() {\n      _wordDocument.Package.Flush();\n      _wordDocument.Close();\n      MemoryStream newStream = new MemoryStream();\n      _memoryStream.WriteTo(newStream);\n      _memoryStream.Close();\n      _memoryStream = newStream;\n      _memoryStream.Position = 0L;\n      _wordDocument = WordprocessingDocument.Open(_memoryStream, true);\n    }	0
32140933	32140200	How to click the div tag "update Patient information" after clicking the Update button in the Gridview column?	.click()	0
20229023	20228797	How to use T parameter for evaluating its type c#	public abstract class BaseManager<T> where T : class {\n    public virtual void SaveObject() {\n        // Some common save logic if it can be done\n    }\n}\n\npublic class EmployeeManager : BaseManager<Employee> {\n    public override void SaveObject() \n    {\n        // Your save logic\n    }\n}	0
3953989	3953970	Constructing a Sorted List with priority items	var sorteditems = newsItems.OrderByDescending(item => item.IsPriority)\n                           .ThenBy(item => item.Date);	0
163134	162986	Including arrary index in XML Serialization	[XmlAttribute("Index")]\npublic int Order\n{  { get; set; }   }	0
6019295	5821671	Reference to configuration manager via httpcontext	System.Configuration.ConfigurationManager	0
9264132	9263486	Select Linq-to-XML from Linq-to-Entities?	XElement xml = new XElement("People");\n\nxml.Add(from p in Context.People.ToList()\n        select new XElement("Person",\n            new XElement("Id", p.Id),\n            new XElement("Name", p.Name)));	0
11495164	11404582	A C# Linq to Sql query that uses SUM, Case When, Group by, outer join, aggregate and defaults	var pd = db.UserProfiles.AsEnumerable()\n    .Where(up => up.ManagerUserProfileID.Equals(null))\n    .Select(up => new\n    {\n        UserProfileID = up.UserProfileID,\n        FirstName = up.FirstName,\n        LastName = up.LastName,\n        TotalScore = up.UserLearnings\n            .Where(ul => ul.CompletionDate.HasValue && ul.Score.HasValue)\n            .DefaultIfEmpty()\n            .Sum(ul => ul != null && ul.Score.HasValue ? ul.Score : 0)\n    });	0
10540332	10539428	How to get all possible image URLs from RSS feed item?	foreach (SyndicationElementExtension extension in f.ElementExtensions)\n{\n    XElement element = extension.GetObject<XElement>();\n\n    if (element.HasAttributes)\n    {\n        foreach (var attribute in element.Attributes())\n        {\n            string value = attribute.Value.ToLower();\n            if (value.StartsWith("http://") && (value.EndsWith(".jpg") || value.EndsWith(".png") || value.EndsWith(".gif") ))\n            {\n                   rssItem.ImageLinks.Add(value); // Add here the image link to some array\n             }\n        }                                \n    }                            \n}	0
20529863	20529799	get a returned value and a set of record in C# when calling a stored procedure	SqlDataReader reader = cmd.ExecuteReader();\n  ...... do you record reading\n reader.Close();\n\n // Now the output parameters are available\n int result = (int)cmd.Parameters["OutputParameter1"].Value;	0
9871768	9871726	Simpliest way to transform a Dictionary<int, Dictionary<int, Foo> > to IEnumerable<IEnumerable<Foo> > in Linq?	return dictionary.Values.Select(nested => nested.Values);	0
3614198	3612908	Cannot Serialize a List<> of DynamicProxy2-generated objects with DataContractJsonSerializer	var serializer = new DataContractJsonSerializer(\n    typeof(List<SimpleViewModel>),\n    new[] { proxyModel.GetType() });	0
14206178	14205737	Unable to find User after specifying a container for PrincipalContext	const string Domain = "SLO1.Foo.Bar.biz:389";\nconst string Container = @"DC=Foo,DC=Bar,DC=biz";\nconst string Username = @"sanderso";\nPrincipalContext principalContext = new PrincipalContext(ContextType.Domain, Domain, Container);\nUserPrincipal userPrincipal = UserPrincipal.FindByIdentity(principalContext,  username);	0
7971087	7970926	How to store a list of values so that it can be accessed in other pages in ASP.NET?	/// <summary>\n    /// Singleton that retrieves and stores the common list of permissions.\n    /// </summary>\n    public static class Permissions\n    {\n        private static List<String> instance = null;\n\n        /// <summary>\n        /// Gets the permissions.\n        /// </summary>\n        /// <returns></returns>\n        static public List<String> GetPermissions()\n        {\n            if (instance == null)\n                instance = DatabaseHelper.GetPermissionsFromDatabase();\n\n            return instance;\n        }\n    }	0
13274154	13272144	How can i format a string as currency in a data bound DataGrid in WPF C#?	row["FlatMinAmount"] = DBNull.Value;	0
2441007	2336466	how to group by over anonymous type with vb.net linq to object	Dim items As Object() = { _\n               New With {.a="a",.b="a",.c=1}, _\n               New With {.a="a",.b="a",.c=2}, _\n               New With {.a="a",.b="b",.c=1} _\n            }\n    Dim myQuery = From i In items _\n             Group By i.a, i.b into g  = Group _\n             let p = New With { .k = g, .v = g.Sum(Function(i) i.c)} _\n          where p.v > 1 _\n          select p\nmyQuery.Dump	0
22218574	22218404	How to retrieve dual batteries status?	ObjectQuery query = new ObjectQuery("Select * FROM Win32_Battery");\n\nforeach (ManagementObject o in new ManagementObjectSearcher(query).Get())\n{\n    uint level = (uint)o.Properties["EstimatedChargeRemaining"].Value;\n}	0
20862109	20861544	Moq with Autofac Func<Owned<IClass>>	Func<Owned<ISynchProcessor>> syncProcessor;\n    Mock<ISynchProcessor> proc = new Mock<ISynchProcessor>();\n\n    [TestInitialize]\n    public void TestInitialize()\n    {        \n        syncProcessor = () => new Owned<ISynchProcessor>(proc.Object, new Mock<IDisposable>().Object);         \n    }	0
26504521	26502834	Mnemonics of my WiX Burn custom bootstrapper UI not wokring	namespace MyBA_UI\n{\n    public class MyBA : BootstrapperApplication\n    {\n        protected override void Run()\n        {\n            Application.EnableVisualStyles();\n            Application.SetCompatibleTextRenderingDefault(false);\n            Application.Run(new Mainform(this));\n        }\n    }\n}	0
11030813	11030711	Listview Cannot select last row	ListView1.SelectedIndex = e.NewSelectedIndex;\nstring id=ListView1.SelectedDataKey.Value.ToString();\n//Then pass the id's value\nListView1.DataBind();	0
24081773	24079139	Unavailable resources in Nunit, ignore result	Assert.Ignore()	0
11812512	11812494	How can I compare multiple variables to a single condition?	string[] stopsWords = new string[] { "stop", "break", .... };\n     for (int i = 0; i < stopWords.Length; i++) if (textBox.Text.ToLower() == stopWords[i])\n     {\n          // do what ever\n     }	0
29230622	29230559	Regex Select [A-Z ] except two consecutive spaces	^[A-Z ]+\b	0
20287931	20287851	Creating log with millisecond portion in time	"MM/dd/yyyy hh:mm:ss fff"	0
13040188	13040164	how do you set a defaultparametervalue of null for optional parameters?	public List<DynamicBusinessObject> GetSearchResultList(Search search, List<CategoryAttribute> listCatAttrib, string sortBy, int startRow, int pageSize, string state = null, string condition = null, string manufacturer = null)	0
13487816	13487682	Import XmlNode into another XmlNode NOT XmlDocument	XmlNode impertedNode = UnitedXml.ImportNode(x, true);\n newParent.AppendChild(impertedNode);	0
10356235	10330539	How to get and set a vb6 property with parameter from c#?	obj.Prop[enumValue] = 1.2m;	0
13586264	13584085	How to access overall AutoFac container to register a dependency in Orchard?	public class MyModule : Module {\n   protected override void Load(ContainerBuilder builder){\n      builder.RegisterType<MyDependency>().As<IMyDependency>().InstancePerDependency();\n   }\n}	0
12014602	12014601	Serialized Dataset looses custom data types in columns	using System;\nusing System.Text;\nusing System.Xml;\nusing System.Xml.Schema;\nusing System.Xml.Serialization;\n\n  [Serializable]\n  public class AlphaNumericSort : IComparable, IXmlSerializable\n  {\n...\n    // Xml Serialization Infrastructure \n    public void WriteXml (XmlWriter writer)\n    {\n        writer.WriteString(_Value);\n    }\n\n    public void ReadXml (XmlReader reader)\n    {\n        _Value = reader.ReadString();\n    }\n\n    public XmlSchema GetSchema()\n    {\n        return(null);\n    }	0
7953315	7952958	How to get all folder AND items from a sharepoint list?	qry.ViewAttributes = "Scope='RecursiveAll'";	0
10098879	6461262	Get "ascent" LineHeight from Font	FontFamily fontFamily = new FontFamily("Arial");\nFont font = new Font(fontFamily, 16, FontStyle.Regular, GraphicsUnit.Pixel);\nascent = fontFamily.GetCellAscent(FontStyle.Regular);\nascentPixel = font.Size * ascent / fontFamily.GetEmHeight(FontStyle.Regular);	0
31734237	31733843	ASP.NET API serialize entities with circular dependencies	public JObject GetTests()\n{\n\n    NewtonSoft.Json.Linq.JObject jsonResult = NewtonSoft.Json.Linq.JObject.FromObject(new \n    {\n        Tests = from test in db.tests\n                select new \n                {\n                    Id = test.Id,\n                    Title = test.Title,\n                    Users = from user in test.Users\n                            select new\n                            {\n                                Id = user.Id\n                            }\n                }\n    });\n\n    return jsonResult;\n}	0
10988265	10988197	Capture keystroke without focus in console	public static void Main()\n{\n    var doWork = Task.Run(() =>\n        {\n            for (int i = 0; i < 20; i++)\n            {\n                Console.WriteLine(i);\n                Thread.Sleep(1000);\n            }\n            Application.Exit(); // Quick exit for demonstration only.  \n        });\n\n    _hookID = SetHook(_proc);\n\n    Application.Run();\n\n    UnhookWindowsHookEx(_hookID);\n}	0
25096207	25096136	Order list by Date with split between future as past dates	DateTime startOfDay = DateTime.UtcNow.Date;\nvar results = context.Orders\n                     .OrderBy(x => x.Schedule < startOfDay)\n                     .ThenBy(x => x.Schedule);	0
7472206	7471641	Visibility of ajaxToolkit:TabContainer using css	TabContainer1.Tabs[0].Enabled = false;	0
29116483	29116192	How to alter table from C# code	Use [DatabaseName]\nGo\nif Not exists( Select * from sys.columns As clm\n                where clm.object_id = OBJECT_ID(N'[TableName]')\n                And clm.name = N'[ColumnName]'\n              )\nBegin\n\n    Alter Table TableName\n    Add ColumnName DataTypeName\n\nEnd	0
19634265	19634196	Renaming a File	File.Move(path + oldname, path + newName);	0
31471857	31471821	assign default value to object if value is null in c#	public class TempleListDetails\n{\n    private string strTempleImage;\n    public String TempleImage\n    {\n        get {return strTempleImage;}\n        set\n        {\n            if (value == null)\n            {\n                strTempleImage= "some image path";\n            }\n        }\n    }\n}	0
11730594	11726428	silverlight 4 image preview from tooltip on datagrid	String docname = ((FrameworkElement)sender).DataContext.ToString()	0
15664270	15664252	Best way to add a delay in C#	Thread.Sleep(TimeSpan.FromSeconds(1))	0
12975079	12974967	Sorting array of string arrays	string[][] data = { new string[] { "xyz", "pound", "4545" }, \n                    new string[] { "abc", "in", "346" }, \n                    new string[] { "def", "off", "42424" } };\ndata = data.OrderBy(entry => entry[0]).ToArray();  // sorts by first field	0
28814177	28813970	Webclient download - illegal characters in path	string downloadString = client.downloadString(/* ... */);\nlines = downloadString.Split(new char[] { '\n', '\r' }, StringSplitOptions.RemoveEmptyEntities)	0
26797741	26797364	ASP.NET Method local access only	if (!HttpContext.Current.Request.IsLocal)\n{ \n    Response.Status = "403 Forbidden";\n    Response.End();\n}	0
14835125	14835095	Completely Modal WPF Window?	Window.ShowDialog()	0
11224652	10192356	return two values from webservice	return jsonSerialize.Serialize(new { list1 = datalist1, list = datalist });	0
18829905	18829760	Getting Data From Sql Server 2008 with C#	private void button1_Click(object sender, EventArgs e)\n{\n    var builder = new SqlConnectionStringBuilder();\n    builder.DataSource = "servername";\n    builder.InitialCatalog = "databasename";\n    builder.UserID = "username";\n    builder.Password = "yourpassword";\n\n    using(var conn = new SqlConnection(builder.ToString()))\n    {\n        using(var cmd = new SqlCommand())\n        {\n            cmd.Connection = conn;\n            cmd.CommandText = "select u_password from [user] where u_name = @u_name";\n            cmd.Parameters.AddWithValue("@u_name", textBox1.Text);\n            conn.Open();\n\n            using(var reader = cmd.ExecuteReader())\n            {\n                 while (reader.Read())\n                 {\n                     var tmp = reader["u_password"];\n                     if(tmp != DBNull.Value)\n                     {\n                         sifre = reader["u_password"].ToString();\n                     }\n                 }\n            }\n        }\n    }\n}	0
2228841	2228833	define a region in google maps jquery plug in	// Bounds for North America\nvar allowedBounds = new GLatLngBounds(new GLatLng(48.19, -127.52), \n                                      new GLatLng(28.72, -68.81));\n\nfunction checkBounds() { \n    if (allowedBounds.contains(map.getCenter())) {\n        return;\n    }\n\n    var c = map.getCenter();\n    var x = c.lng();\n    var y = c.lat();\n    var maxX = allowedBounds.getNorthEast().lng();\n    var maxY = allowedBounds.getNorthEast().lat();\n    var minX = allowedBounds.getSouthWest().lng();\n    var minY = allowedBounds.getSouthWest().lat();\n\n    if (x < minX) { x = minX; }\n    if (x > maxX) { x = maxX; }\n    if (y < minY) { y = minY; }\n    if (y > maxY) { y = maxY; }\n\n    map.setCenter(new GLatLng(y, x));\n}\n\nGEvent.addListener(map, "move", function() { checkBounds(); });	0
17253555	17253425	How to populate a RadioButton List with 4 answer choices in random order for a Quiz?	// start with an array of the question key strings\nnew[] { "CorrectAnswer", "IncorrectAnswer1", "IncorrectAnswer2", "IncorrectAnswer3" }\n   // for each key string s, select the relevant answer string\n   .Select(s => thisItem[s].ToString())\n   // sort by a random number (i. e. shuffle)\n   .OrderBy(s => rand.Next())\n   // convert to a List<T> (for the ForEach method)\n   .ToList()\n   // for each answer string s in the list, add s to thisAnswers.Items\n   .ForEach(s => thisAnswers.Items.Add(s));	0
8338354	8338305	WPF Dispatcher Thread- Using lambda expression and throw to dispatch exception to UI thread	e => throw new WhateverException("your message", ex);	0
24658806	24658685	How can I get this function's variable?	(?<=\"aContent\": \")(.*?)(?=\",)	0
19809729	19808929	Find items not in datatable that are present in List<customclass>	Dim listaRows = ds.Tables(0).AsEnumerable(). _\n                Cast(Of DataRow).ToList()\n\nDim valores = New HashSet(Of String) _\n                          (listaRows.Select(Function(r) r.Field(Of String)("FICHERO")))\n\nDim query = _\n                listaFichero.Where(Function(l) _\n                                       Not valores.Contains(l.FicheroParsed)).ToList	0
7817425	7817332	Turn a aspx page to a link?	Response.Redirect("http://www.google.com/intl/en_com/images/srpr/logo3w.png");	0
2073343	2073318	How to lock/unlock a field at runtime in C#?	public class X\n{\n    private bool locked = false;\n\n    private int lockedVar;\n    public int LockedVar\n    {\n        get { return lockedVar; }\n        set { if (!locked) lockedVar = value; }\n    }\n\n    public void LockObject() { locked = true; }\n    public void UnlockObject() { locked = false; }\n}	0
475918	475637	Do I need to have a View Page for every Action in ASP.NET MVC?	public class CustomerController : Controller\n\n...\n\npublic ActionResult Search(int id)\n{\n ViewData["SearchResult"] = MySearchBLL.GetSearchResults(id);\n\n return View("Index");\n}\n\n...	0
1427536	1427348	How do you get the name of the first page of an excel workbook?	Microsoft.Office.Interop.Excel.Application app = new Microsoft.Office.Interop.Excel.Application();\nMicrosoft.Office.Interop.Excel.Workbook workbook =  app.Workbooks.Open(fileName,otherarguments);\nMicrosoft.Office.Interop.Excel.Worksheet worksheet =  workbook.Worksheets[1] as Microsoft.Office.Interop.Excel.Worksheet;	0
687451	687359	How would you get an array of Unicode code points from a .NET String?	static int[] ExtractScalars(string s)\n{\n  if (!s.IsNormalized())\n  {\n    s = s.Normalize();\n  }\n\n  List<int> chars = new List<int>((s.Length * 3) / 2);\n\n  var ee = StringInfo.GetTextElementEnumerator(s);\n\n  while (ee.MoveNext())\n  {\n    string e = ee.GetTextElement();\n    chars.Add(char.ConvertToUtf32(e, 0));\n  }\n\n  return chars.ToArray();\n}	0
21337479	20887735	How to Change MVC Registered Bundle Collection items Dynamically	Bundle bndl = BundleTable.Bundles.GetBundleFor("~/Content/css");\n            if (bndl != null)\n            {\n                BundleTable.Bundles.Remove(bndl);\n            }\n\n            Bundle bndl2 = new Bundle("~/Content/css");\n            bndl2.Include("~/Content/site.css", "~/Content/secondStyles.css", ... );\n            BundleTable.Bundles.Add(bndl2);	0
31060662	31060530	C# Pass method with arguments as a parameter to Lazy<T>	var x = 2;\nvar y = 3;\nDoSomething(() => Add(x, y));	0
1904315	1904296	C# Read rows from a table and store the values in a string[]	while (rdr.Read())\n{\n     Console.WriteLine(rdr[0]);\n}	0
33355387	33355205	Detect Shift + F10 or Context menu button	protected override bool ProcessCmdKey(ref Message msg, Keys keyData) {\n        int KeyAsInt=(int)keyData;\n        this.Text = KeyAsInt.ToString();\n        switch (KeyAsInt) {\n            case 65657:\n                MessageBox.Show("Heureka!");\n                break;\n        }\n        return base.ProcessCmdKey(ref msg, keyData);\n    }	0
26693619	26693518	How to create a non rectangular form?	// DllImportAttribute requires reference to System.Runtime.InteropServices\n\npublic const int WM_NCLBUTTONDOWN = 0xA1;\npublic const int HT_CAPTION = 0x2;\n\n[DllImportAttribute("user32.dll")]\npublic static extern int SendMessage(IntPtr hWnd, int Msg, int wParam, int lParam);\n[DllImportAttribute("user32.dll")]\npublic static extern bool ReleaseCapture();\n\npublic Form1()\n{\n    InitializeComponent();\n}\n\nprivate void Form1_MouseDown_1(object sender, MouseEventArgs e)\n{\n    if (e.Button == MouseButtons.Left)\n    {\n        ReleaseCapture();\n        SendMessage(Handle, WM_NCLBUTTONDOWN, HT_CAPTION, 0);\n    }\n}	0
14727178	14727114	translation of vb code to c#	if (Page.User.Identity != null && Page.User.Identity is FormsIdentity) {\n    FormsIdentity ident = (FormsIdentity)Page.User.Identity;\n    FormsAuthenticationTicket ticket = ident.Ticket;\n    string AdminUserName = ticket.UserData;\n\n    if (!string.IsNullOrEmpty(AdminUserName)) {\n    //An Admin user is logged on as another user... \n    //The variable AdminUserName returns the Admin user's name\n    //To get the currently logged on user's name, use Page.User.Identity.Name\n    } else {\n        //The user logged on directly (the typical scenario)\n    }\n}	0
33328700	33321352	Getting Cookies in c#	foreach (var c in GetAuth_Response.Cookies)\n            {\n                Cookies.Add(new Cookie(c.Name, c.Value, c.Path, c.Domain));\n            }	0
8642817	8642745	HttpRequest giving parameter to AsyncCallback delegate	private void StartWebRequest(string url, string filename)\n{\n    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);\n    request.BeginGetResponse(result => {\n        FinishWebRequest(result, request, filename);\n    }, null); // Don't need the state here any more\n}\n\nprivate void FinishWebRequest(IAsyncResult result,\n                              HttpWebRequest request,\n                              string filename)\n{\n    using (HttpWebResponse response =\n             (HttpWebResponse) request.EndGetResponse(result))\n    {\n        // Use filename here\n    }\n}	0
11160907	11160685	Get Columns of a Table by GetSchema() method	var dtCols = con.GetSchema("Columns", new[] { "DBName", null, "TableName" });	0
8813285	8813246	Passing list members into a function	class Program\n    {\n\n        public static void SayHelloXTimes(string helloString, int x)\n        {\n            for (int i = 0; i < x; i++)\n            {\n                Console.WriteLine(helloString);\n            }\n        }\n\n        static void Main(string[] args)\n        {\n            MethodInfo Method = typeof(Program).GetMethod("SayHelloXTimes");\n            Method.Invoke(null, new object[] { "foo", 3 });\n\n            Console.ReadLine();\n        }\n    }	0
30743558	30742271	Trouble with linq left join only including values that are a match	var userQuery = \n        from user in db.Users\n        where (user.FirstName.StartsWith(searchValue)\n               || user.LastName.StartsWith(searchValue)\n               || user.Name.StartsWith(searchValue)\n               || user.School.StartsWith(searchValue)\n               || user.SchoolClass.StartsWith(searchValue))\n               && user.UserId != userId\n        select new {\n            User = user,\n\n            // I'm using single because I'm guessing there's only one match\n            Status = db.Friendship\n                .Where(f => f.FriendUserId == user.UserId && f.UserId == userId)\n                .SingleOrDefault(),\n        };	0
32912178	32911590	Get all possible values from a string array that contains two strings c#	string[] filtered = file.ToList().Where(s => s.Contains("propose ID")).ToArray();\nstring[] superfiltered = filtered.ToList().Where(r => r.Contains("sw")).ToArray();	0
8486675	8486561	Can't find my textbox inside a repeater	foreach(RepeaterItem item in ChildRepeater.Items){\n  if(item.ItemType == ListItemType.Item || item.ItemType == ListItemType.AlternatingItem){\n    var txt = (TextBox)item.FindControl("TextBox1");\n  }\n}	0
22932271	22932270	Delete checked node in a Tree view c#	ArrayList checkedNodes = new ArrayList();\n\n    if (elementsHierTree.CheckedNodes.Count != 0)\n    {\n        foreach (TreeNode nodee in elementsHierTree.CheckedNodes)\n        {\n            if (nodee.Parent != null)\n            {\n                checkedNodes.Add(nodee);\n            }\n        }\n    }\n\n    foreach (TreeNode chNode in checkedNodes)\n    {\n        chNode.Parent.ChildNodes.Remove(chNode);\n    }	0
5625950	5625844	How to pass a value from one frame and receive in another frame in asp.net C#?	public class MyEventArgs : EventArgs\n{\n// add fields and constructor here\n// initialize the fields in the constructor\n}	0
2745475	40535	Asp.Net MVC: How to determine if you're currently on a specific view	public static bool IsCurrentAction(this HtmlHelper helper, string actionName, string controllerName)\n    {\n        string currentControllerName = (string)helper.ViewContext.RouteData.Values["controller"];\n        string currentActionName = (string)helper.ViewContext.RouteData.Values["action"];\n\n        if (currentControllerName.Equals(controllerName, StringComparison.CurrentCultureIgnoreCase) && currentActionName.Equals(actionName, StringComparison.CurrentCultureIgnoreCase))\n            return true;\n\n        return false;\n    }	0
12157538	12157312	DataTable edit per Row through foreach statement	if (specific condition in Datatable "tests" is met)\n{\n      row1[10] = Convert.ToInt64(row2[0]); //try this only.\n}\nelse if (another specific condition in Datatable "tests" is met)\n{\n     //Different fields will be filled\n}	0
21526851	21526706	Foreach loop multiple actions	for (int b = 1; b <= list.count;b++ )\n{\n   if (b <= list.count) method1();\n   b++;\n   if (b <= list.count) method2();\n   b++;\n   if (b <= list.count) method3();\n   b++;\n   if (b <= list.count) method4();\n}	0
1466001	1465434	Edit Metadata of PDF File with C#	using System;\nusing PdfSharp.Pdf;\nusing PdfSharp.Pdf.IO;\n\nnamespace ConsoleApplication1\n{\n  class Program\n  {\n    static void Main (string[] args)\n    {\n      Program p = new Program();\n      p.Test();\n\n    }\n\n    public void Test ()\n    {\n      PdfDocument document = PdfReader.Open ("Test.pdf");\n\n      document.Info.Author = "ME";\n\n      document.Save ("Result");\n    }\n  }	0
901969	901968	C# Reading Decimal Value From Registry	Object obj = APRegistry.GetValue("apTime");\nString str = obj != null ? obj.ToString() : "0";\nDecimal value = Decimal.Parse(str);\nthis.apTime.Value = value;	0
11941143	11939972	How to create folders in website running in IIS 7 at runtime with all permissions?	string path = MapPath("~/bin");	0
379582	379560	How do I write ints out to a text file with the low bits on the right side (Bigendian)	int i = 6;\n        byte[] raw = new byte[4] {\n            (byte)(i >> 24), (byte)(i >> 16),\n            (byte)(i >> 8), (byte)(i)};	0
6990651	6990427	Encrypt AES in PHP, decrypt in C#	ICryptoTransform decryptor = rijndaeld.CreateDecryptor(md5val, null);	0
7019439	7019401	YouTube API - Get All Videos From User limits?	max-results	0
12401285	12401055	c# string replace for keyword	content =  Regex.Replace(content, @"\s\w+\.(abc|ABC)_", " john.$1_");	0
858871	858848	Regular expression to find and replace a string in a xml	("MyString")|(>MyString<)|(;MyString&)	0
17441384	17441322	Is it possible to use Yield keyword to return values without a loop?	// yield-example.cs\nusing System;\nusing System.Collections;\npublic class List\n{\n   IEnumerable <int> MyMethod()\n    {\n\n            yield return result1 ; \n            yield return result2 ; \n            yield return result5 ; \n            yield return result6; \n\n    }\n}	0
6581313	6576192	windows phone 7, help with the back button and pages, saving variables	// Code to execute when the application is launching (eg, from Start)\n    // This code will not execute when the application is reactivated\n    private void Application_Launching(object sender, LaunchingEventArgs e)\n    {\n    }\n\n    // Code to execute when the application is activated (brought to foreground)\n    // This code will not execute when the application is first launched\n    private void Application_Activated(object sender, ActivatedEventArgs e)\n    {\n    }\n\n    // Code to execute when the application is deactivated (sent to background)\n    // This code will not execute when the application is closing\n    private void Application_Deactivated(object sender, DeactivatedEventArgs e)\n    {\n    }\n\n    // Code to execute when the application is closing (eg, user hit Back)\n    // This code will not execute when the application is deactivated\n    private void Application_Closing(object sender, ClosingEventArgs e)\n    {\n    }	0
27330811	27330672	Override Button, make backcolor fill from left to right like progress bar	var bmp = new Bitmap(button1.Width, button1.Height);\nvar g = Graphics.FromImage(bmp);\n\nvar rect = new Rectangle(0, 0, bmp.Width, bmp.Height);\nusing (var lgb = new LinearGradientBrush(rect, Color.Black, Color.LimeGreen, 0f))\n    g.FillRectangle(lgb, rect);\n\nbutton1.BackgroundImage = bmp;	0
2146767	2146711	How to tell if a html string will show as empty in the browser? (C# / regex?)	HtmlDocument docEmpty = new HtmlDocument();\ndocEmpty.LoadHtml("<p><br /></p>");\n\nHtmlDocument doc = new HtmlDocument();\ndoc.LoadHtml("<p>I am not empty...<br /></p>");\n\nbool shouldBeEmpty = string.IsNullOrEmpty(docEmpty.DocumentNode.InnerText);\nbool shouldNotByEmpty = string.IsNullOrEmpty(doc.DocumentNode.InnerText);	0
17896707	17896544	check how many times a function returns a value consecutively	int trueCount = 0;\nbool wasTrue = false;\nfor(int i=0; i<100000; i++)\n{\n    wasTrue = F(i);\n    if (wasTrue)\n        trueCount++;\n    else\n        trueCount = 0;\n    if(trueCount == 10)\n        ;//Do Something\n    else\n        ;// Do something else\n}	0
10336048	10335953	How to use PreviousPage?	Page.PreviousPage	0
24306566	24283858	Reading an X509 Certificate in Python	import json\nimport requests\nfrom OpenSSL import crypto\n\nP12_CERT_FILE = 'C:/Users/mryan/Documents/Code/SampleApps/bundle.p12'\np12_cert = crypto.load_pkcs12(open(P12_CERT_FILE).read(), 'passphrase')\npem_cert = crypto.dump_certificate(crypto.FILETYPE_PEM, p12_cert.get_certificate())\n\n# remove PEM header, footer, and new lines to produce raw cert data\nraw_data = ''.join(pem_cert.split('\n')[1:-2])\ncert_data = json.dumps({'RawData': raw_data})\nresult = requests.post(apiRoot + "/Accounts/" + accId + "/certs", data=cert_data)	0
10648800	10648117	How to reopen a file immediately after it closes via my C# application	private void Form1_Load(object sender, EventArgs e)\n    {\n        Process p = Process.GetProcessesByName("Notepad")[0];\n        p.EnableRaisingEvents = true;\n        p.Exited += new EventHandler(p_Exited);\n    }\n\n    void p_Exited(object sender, EventArgs e)\n    {\n        MessageBox.Show("Exit");\n    }	0
10037597	10032613	Unable to deserialize an xml file	[XmlRoot("info")]\npublic class Response\n{\n    [XmlElement("result")]\n    public Result Result { get; set; }\n\n    [XmlElement("songlist")]\n    public SongList SongList { get; set; }\n}\n\npublic class Result\n{\n    [XmlAttribute("resultCode")]\n    public int ResultCode { get; set; }\n\n    [XmlText]\n    public string Value { get; set; }\n}\n\npublic class SongList\n{\n    [XmlElement("song")]\n    public Song[] Songs { get; set; }\n}\n\npublic class Song\n{\n    [XmlElement("id")]\n    public string Id { get; set; }\n}	0
7865107	7864994	Bind SQL XML field to gridview	string connectionString = /* connection string to your database */\nusing (var connection = new SqlConnection(connectionString))\n{\n    connection.Open();\n    var command = new SqlCommand("SELECT xmlColumn FROM xmlTable", connection);\n    using (var reader = command.ExecuteReader())\n    {\n        string xml = reader.GetString(0);\n        DataSet dataSet = new DataSet();\n        dataSet.ReadXml(new StringReader(xml));\n        this.GridView1.DataMember = "fruit";\n        this.GridView1.DataSource = dataSet;\n        this.GridView1.DataBind();\n    }\n}	0
32590292	32590228	Starting C# project from Java application	Process process = new ProcessBuilder(CSharpApplicationPath,"param1","param2").start()	0
13060400	13058110	How to programmatically determine if anonymous access is enabled for a SharePoint 2010 Web Application?	web.Site.WebApplication.IisSettings[Microsoft.SharePoint.Administration.SPUrlZone.Internet].AllowAnonymous	0
12269692	12269579	Read Json using C#	string json = @"{data: { ""1000"": { ""country-id"": 1000, ""name1"": { ""name"": ""Afghanistan"", }, }, ""4000"": { ""country-id"": 4000, ""name1"": { ""name"": ""Albania"", } }";\n\n    var countries = ((JObject)JsonConvert.DeserializeObject(json))["data"]\n        .Children()\n        .Select(x => new\n        {\n            Id = (int)x.First()["country-id"],\n            Name = (string)x.First()["name1"]["name"],\n        })\n        .ToList();	0
7718351	7718180	Set colors in asp.net pie chart by name	foreach (Series charts in fbchart.Series)\n{\n    foreach (DataPoint point in charts.Points)\n    {\n       switch (point.AxisLabel)\n        {\n           case "Neutral": point.Color = Color.Red; break;\n           case "Happy": point.Color = Color.Green; break;\n           case "Sad": point.Color = Color.Orange; break;\n         }\n         point.Label = string.Format("{0:0} - {1}", point.YValues[0], point.AxisLabel);\n\n    }\n }	0
6777961	6777715	How to display values in list view	bool isNullVersion=(Data.AgentVersion ?? "0.0.0.0") == "0.0.0.0";\nstring policy= isNullVersion ? \n                           ResourcePolicyAvailSystemsLVI.m_nullString :\n                           ResourcePolicyAvailSystemsLVI.unknown;\nif (Data.ResourcePolicy !=null) policy=Data.ResourcePolicy.Name;\nSubItems.Add(policy);\nSubItems.Add(isNullVersion ? \n                            ResourcePolicySystemsControl.m_nullVersion :\n                            Data.AgentVersion\n            );\nSubItems.Add(Data.AgentState.ToString());	0
806478	806420	C# How to show a text bubble on a user control?	System.Windows.Forms.ToolTip myToolTip = new System.Windows.Forms.ToolTip();\nmyToolTip.IsBalloon = true;\nmyToolTip.Show("Some text", this.WhereToShow);	0
384656	384633	Select the maximal item from collection, by some criterion	decimal de = d.Max(p => p.Name.Length);\n    Model a = d.First(p => p.Name.Length == de);	0
13388787	13388603	Assign value member from database to combobox	comboBox1.SelectedValue	0
9578592	9574220	Resource lookup for enums	public static class WeightGoalStatusExtensions\n{\n    public static string ToLocalizedString(this WeightGoalStatus status)\n    {\n        switch (status)\n        {\n           case WeightGoalStatus.InProgress\n              return Resources.WeightGoalStatus.InProgress_ToLocalizedString;\n           // others\n        }\n    }\n}	0
6126440	6126423	find control by name with linq	bool found = testRibbon.CommandTabs.Cast<RibbonTab>().Any(t => t.name == tab.Name);	0
8085763	8082559	C# Windows Phone 7 ListBox Scrolling Up / Down event?	var sView = e.ManipulationContainer as ScrollViewer;\n\n        double lBox = 25 - sView.ScrollableHeight;\n\n        double nBox = 25 - sView.VerticalOffset;\n\n        if (lBox < nBox)\n            //Listbox Scrolled Up\n        else\n            //Listbox at Bottom	0
8164950	8162974	How to make the table non breaking using iTextSharp	tblSummary.KeepTogether = true;	0
5069906	5069825	Change BackColor of a custom user control to transparent	SetStyle(ControlStyles.SupportsTransparentBackColor)	0
14292248	14281982	Error with xml serialization in c# - paramaterless constructor	tempFingerPrint = Fmd.SerializeXml(resultConversion.Data);	0
16297581	16297528	Find child objects in list of parent objects using LINQ	Child childWithId17 = parents.SelectMany(parent => parent.Children)\n                             .FirstOrDefault(child => child.ID == 17);	0
2857067	2854658	LuaInterface - how to register overloaded methods?	function MyMethod(foo, bar)\n    if bar then\n        MyMethod1(foo, bar)\n    else\n        MyMethod2(foo)\n    end\nend	0
34434981	34434727	Static variable initialized more than once using Prism and MEF	public class Test<T>\n{\n    public static object obj = new object();\n}\n\nConsole.WriteLine(object.ReferenceEquals(Test<string>.obj, Test<object>.obj)); // false	0
27527973	27527919	Extract List<int> with positions from indexOf from string	Regex.Matches(input,@"\bsome\b")\n     .Cast<Match>()\n     .Select(x=>x.Index);	0
22990946	22988611	WPF Console app doesnt return to prompt once finished	[STAThread()]\n    internal static void Main()\n    {\n        // [Your startup code here]\n\n        Application app = new Application();\n        app.DispatcherUnhandledException += DispatcherUnhandledException;\n        app.MainWindow = new MainWindow();\n        app.MainWindow.ShowDialog();\n\n        Console.WriteLine("Terminating...");\n        Startup.FreeConsole();\n\n        // http://msdn.microsoft.com/en-us/library/ms597014(v=vs.110).aspx\n        app.Shutdown(0);      // <-- or Application.Current.Shutdown(0);\n\n        // http://msdn.microsoft.com/en-us/library/system.environment.exit.aspx\n        Environment.Exit(0);  // <-- a bit redundant however\n    }	0
6808847	6808739	How to convert color code into media.brush?	var converter = new System.Windows.Media.BrushConverter();\nvar brush = (Brush)converter.ConvertFromString("#FFFFFF90");\nFill = brush;	0
7074571	7074545	How to create a common event for Multiple Controls	private void createControl () {\n  CheckBox dynamicCheckbox = new CheckBox();\n  /* properties */\n  dynamicCheckbox.CheckedChanged += new EventHandler( Common_CheckedChanged );\n  /* add to control tree, etc. */\n}	0
10829607	10829456	ASP.NET C# DateTime Models/Controller/View Format	[DisplayFormat(ApplyFormatInEditMode=true, DataFormatString = "{0:d}")]	0
4265487	4127453	Join multiple times to the same table using LLBLGen	// C#\nIRelationPredicateBucket bucket = new RelationPredicateBucket();\nbucket.Relations.Add(CustomerEntity.Relations.AddressEntityUsingVisitingAddressID, "VisitingAddress");\nbucket.Relations.Add(CustomerEntity.Relations.AddressEntityUsingBillingAddressID, "BillingAddress");\nbucket.PredicateExpression.Add((AddressFields.City.SetObjectAlias("VisitingAddress")=="Amsterdam") &\n     (AddressFields.City.SetObjectAlias("BillingAddress")=="Rotterdam"));\nEntityCollection customers = new EntityCollection(new CustomerEntityFactory());\nDataAccessAdapter adapter = new DataAccessAdapter();\nadapter.FetchEntityCollection(customers, bucket);	0
11848061	11847965	Foreach loop XmlNodeList	XmlDocument xDoc = new XmlDocument();\n            xDoc.Load("http://api.twitter.com/1/statuses/user_timeline.xml?screen_name=twitter");\n\n            XmlNodeList tweets = xDoc.GetElementsByTagName("text");\n            for (int i = 0; i < tweets.Count; i++)\n            {\n                if (tweets[i].InnerText.Length > 0)\n                {\n                    MessageBox.Show(tweets[i].InnerText);\n                }\n            }	0
10348632	10348528	Sort a List by the column of a different list	var expensesSummary_Member =\n    from global in expensesSummary_Global.Select(x => x.TagId).ToList()\n    join tmp in expensesSummary_MemberTmp\n    on global equals tmp.TagId\n    select tmp;	0
27808277	27807942	winforms combobox, how to stop it from dropping down when getting focus	const int WM_LBUTTONDOWN = 0x0201;\nconst int WM_LBUTTONDBLCLK = 0x0203;\n\nprotected override void WndProc(ref Message m)\n    {\n        // only open dropdownlist when the user clicks on the arrow on the right, not anywhere else...\n        if (m.Msg == WM_LBUTTONDOWN || m.Msg == WM_LBUTTONDBLCLK)\n        {\n            int x = m.LParam.ToInt32() & 0xFFFF;\n            if (x >= Width - SystemInformation.VerticalScrollBarWidth)\n                base.WndProc(ref m);\n            else\n            {\n                Focus();\n                Invalidate();\n            }\n        }\n        else\n            base.WndProc(ref m);\n    }	0
30034218	30031721	Security Exception with Microsoft AddIn Framework (MAF) Callback using two AppDomains	PermissionSet permSet = new PermissionSet(PermissionState.Unrestricted);\n\npermSet.Assert();\n\n//Do the problematic Stuff\n\nPermissionSet.RevertAssert();	0
10859774	10858678	Capturing a picture as a perfect square using the camera?	WriteableBitmap SquareImage(WriteableBitmap srcBitmap)\n     {\n         int[] srcData = srcBitmap.Pixels;\n         int[] destData = new int[srcBitmap.PixelHeight * srcBitmap.PixelHeight];\n\n         for (int row = 0; row < srcBitmap.PixelHeight; ++row)\n        {\n            for (int col = 0; col < srcBitmap.PixelHeight; ++col)\n            {\n                destData[(row * srcBitmap.PixelHeight) + col] = srcData[(row * srcBitmap.PixelWidth) + col];\n            }\n        }\n\n         WriteableBitmap squareBitmap = new WriteableBitmap(srcBitmap.PixelHeight, srcBitmap.PixelHeight);\n         destData.CopyTo(squareBitmap.Pixels, 0);\n\n         return squareBitmap;\n    }	0
4787047	4786884	How to write output from a unit test?	[TestClass]\n    public class UnitTest1\n    {\n        private TestContext testContextInstance;\n        /// <summary>\n        ///Gets or sets the test context which provides\n        ///information about and functionality for the current test run.\n        ///</summary>\n        public TestContext TestContext\n        {\n            get\n            {\n                return testContextInstance;\n            }\n            set\n            {\n                testContextInstance = value;\n            }\n        }\n\n        [TestMethod]\n        public void TestMethod1()\n        {\n            TestContext.WriteLine("Message...");\n        }\n    }	0
3943529	3940039	Boundfield as part of Hyperlinkfield in a code generated gridview	string[] id = new string[] { "Emp_ID" }; \n\nHyperLinkField hyperlinkedColumn = new HyperLinkField();\nhyperlinkedColumn.DataTextField = "IDNumber";\nhyperlinkedColumn.HeaderText = "ID No.";\nhyperlinkedColumn.DataNavigateUrlFields = id;\nhyperlinkedColumn.DataNavigateUrlFormatString = "../Pages/Home.aspx?Emp_ID={0}";\nhyperlinkedColumn.Visible = true;	0
18177960	18175541	How to store the username of the LoginName Control from the LoginView into a textbox control	createdBy.Text = User.Identity.Name;	0
7915130	7915080	Convert value from string to generic type that is either Guid or int	id = (T)TypeDescriptor.GetConverter(typeof(T)).ConvertFromInvariantString(text);	0
25862036	25861067	Fibonacci Series Extension	class Program\n    {\n        static void Main(string[] args)\n        {\n            string test = "abcdef";\n            int sum = 0;  \n            foreach (char c in test)\n            {\n                int letterNumber = char.ToUpper(c) - 64;  \n                sum += rtnDegint(letterNumber);\n            }  \n            Console.WriteLine(sum);\n        }\n\n        int rtnDegint(int n)\n        {\n            int first = 0, second = 1, next = 0, c;  \n            for (c = 0; c < n; c++)\n            {\n                if (c <= 1)\n                    next = c;\n                else\n                {\n                    next = first + second;\n                    first = second;\n                    second = next;\n                }\n            }\n            return next;\n        }\n    }	0
12746128	12730294	Dataview.RowFilter - how to get specific result set	dv.RowFilter = "AttributeID in (" + String.Join(",", attributes) + ")";\n\nList<int> Resources =  (from a in dv.ToTable().AsEnumerable()\n         group a by (int)a["ResourceID"] into grp\n         where grp.Count() == attributes.Length\n         select grp.Key).ToList<int>();	0
4394127	4393741	Getting selecteditem from a customized WPF combobox	var item = cbo1.SelectedItem as ComboBoxItem;\nvar stackpanel = item.Content as StackPanel;\nvar selectedContent = (stackpanel.Children[0] as ContentPresenter).Content;	0
19794303	19794180	Drawing aligned strings by formatting double values	String.Format	0
655271	609052	Changing ListBox selection is not moving changes from BindingSource to DataSet	private void MyListBox_Click(object sender, EventArgs e)\n    {\n        this.myBindingSource.EndEdit();\n        if (myDataSet.HasChanges())\n        {\n            if (MessageBox.Show("Save changes?", "Before moving on", MessageBoxButtons.YesNo) == DialogResult.Yes)\n            {\n                myTableAdapter.Update(myDataSet.myDataTable);\n            }\n            else\n            {\n                myDataSet.RejectChanges();\n            }\n        }\n    }	0
13310930	13310674	Given this lambda, how can I write it manually with expression trees?	private static Expression<Func<string[], Poco>> CreateExpr()\n{\n    ParameterExpression paramExpr = Expression.Parameter(typeof(string[]), "a");\n    var newExpr = Expression.New(typeof(Poco));\n\n    var memberExprs = Enumerable.Range(0, 3)\n        .Select(i =>\n        {\n            string propertyName = "MyProperty" + (i + 1);\n            var property = typeof(Poco).GetProperty(propertyName);\n            Expression.Bind(property, Expression.ArrayIndex(paramExpr, Expression.Constant(i)));\n        });\n\n    var expr = Expression.MemberInit(newExpr, memberExprs);\n    return Expression.Lambda<Func<string[], Poco>>(expr, paramExpr);\n}	0
9535380	9534979	How to create delegate to the button click in code behind	((Button)e.Item.FindControl("btn_up")).Click += new EventHandler(delegate(object s, EventArgs args) {});	0
27609156	27608981	How to find string between two numbers and store it in a array?	string str1 =  "47: echo <http://php.net/echo> echo \"<div id=\" . $var . \">content</div>\"; " + Environment.NewLine\n            + "o 46: $var = htmlspecialchars($v, ENT_QUOTES);" + Environment.NewLine\n            + "+ 45: $v = $_SESSION['UserData']; ";\n\nvar matches = System.Text.RegularExpressions.Regex.Matches(str1, @"([\d]+)?:(.*)?\r\n?", System.Text.RegularExpressions.RegexOptions.Multiline);\nforeach(Match m in matches)\n{\n    Console.WriteLine(m.Groups[1].Value);\n    Console.WriteLine(m.Groups[2].Value);\n}	0
18885402	18885340	Remove Substring in String C#	var url = new Uri("http://www.testproject.com/tokyo/4");\nvar lastSegment = url.Segments.Last();	0
15275394	15275269	Sort a list from another list IDs	docs = docs.OrderBy(d => docsIds.IndexOf(d.Id)).ToList();	0
11862563	11862214	How to split pipe-separated (|) values of a single column of data table into multiple columns	var dtCompleteRecords = new DataTable("CompleteRecords");\n dtCompleteRecords.Columns.Add(new DataColumn("a", typeof(string)));\n dtCompleteRecords.Columns.Add(new DataColumn("b", typeof(string)));\n dtCompleteRecords.Columns.Add(new DataColumn("c", typeof(string)));\n\n\ndtRecords.AsEnumerable()\n    .Select(row => row["Token"].ToString().Split('|'))\n    .ToList()\n    .ForEach(array => dtCompleteRecords.Rows.Add(array));	0
3164200	3150751	Bring Windows Taskbar to front when a fullscreen application is running	SendKeys.Send("{ESC}");	0
7903257	7902781	How to make RIA ignore a property when generating entities?	public class Book\n{\n    [Key]\n    public int ID { get; set; }\n    public String Name { get; set; }\n    public DateTime DatePublished { get; set; }\n\n    // I don't need this one in SL4\n    [Exclude]\n    public BookInfo Info { get; set; }\n}	0
4255967	4255924	Locking file for writing from Windows Service	using (fs = new FileStream("somefile.txt", FileMode.Open, FileAccess.Read, FileShare.None))\n  { }	0
30123088	30122901	Save dictionary in application settings and load it on start	string strDictionaryAsString = JsonConvert.SerializeObject(dtnDictionary);\n\nvar dtnDictionary = JsonConvert.DeserializeObject<Dictionary<string, double>>(strDictionaryAsString );	0
28730277	28730241	How do I calculate LINEST in C# with a zero intercept?	public static LineSpec LinestConst(IList<double> yValues, IList<double> xValues)\n    {\n        var yAvg = yValues.Sum() / yValues.Count;\n        var xAvg = xValues.Sum() / xValues.Count;\n\n        double upperSum = 0;\n        double lowerSum = 0;\n        for (var i = 0; i < yValues.Count; i++)\n        {\n            upperSum += (xValues[i] * yValues[i] );\n            lowerSum += (xValues[i] * xValues[i] );\n        }\n\n        var m = upperSum / lowerSum;\n        var b = 0;\n        return new LineSpec() { Slope = m, Intercept = b };\n    }	0
1591720	1591710	c#: How do I determine if the ScrollBar for a Scrollable control is currently displayed?	// Checks horizontal scrollbar visibity.\nyourScrollableControl.HorizontalScroll.Visible;\n\n// Checks horizontal scrollbar visibity.\nyourScrollableControl.VerticalScroll.Visible;	0
21107114	21089855	Fluent NHibernate mapping of Dictionary<Entity, int>	HasMany(x => x.AccessPointPosition)\n   // these are most likely by convention\n   // .Table("tbl_AccessPointPosition") \n   // .KeyColumn("Transport_id")\n   // ...\n   .AsEntityMap("Endpoint_id")\n   .Element("integer_col", part => part.Type<int>());	0
9282845	9282755	how to make a timer restart?	private void checkBox1_CheckedChanged(object sender, EventArgs e)\n    {\n        if (checkBox1.Checked == true)\n        {\n            start = 0;\n            label1.Text = string.Empty;\n            timer1.Enabled = true;\n            timer1.Start();\n        }\n        else\n        {\n            timer1.Enabled = false;\n        }\n    }	0
31407013	31388171	C# - Catch WebException While Posting XML Async	void UploadStringCallback2(object sender, UploadStringCompletedEventArgs e)\n    {\n        if (e.Error != null)\n        {\n            object objException = e.Error.GetBaseException();\n\n            Type _type = typeof(WebException);\n            if (_type != null)\n            {\n                WebException objErr = (WebException)e.Error.GetBaseException();\n                WebResponse rsp = objErr.Response;\n                using (Stream respStream = rsp.GetResponseStream())\n                {\n                    StreamReader reader = new StreamReader(respStream);\n                    string text = reader.ReadToEnd();\n                }\n                throw objErr;\n            }\n            else\n            {\n                Exception objErr = (Exception)e.Error.GetBaseException();\n                throw objErr;\n            }\n        }\n\n     }	0
6661367	6661280	Best way to alter a string to move "A", "An", "The" to end of the string in c#	string title = "The Chronicles of Narnia";\nstring newTitle = Regex.Replace(title, "^(the|a|an) (.*)$", "$2, $1", RegexOptions.IgnoreCase);\n\nConsole.WriteLine(newTitle);	0
16520511	16518939	how can i read a DataTable from javascript	public object[][] SendOnlineContacts()\n{\n    //...\n    for (int i = 0; i < FriendsDt.Rows.Count; i++)\n    {\n        int FriendID = Convert.ToInt16(FriendsDt.Rows[i][0]);\n        DataRow[] FriendisOnlineRow = ConnectedClientDt.Select("ClientID=" + FriendID);\n\n        if (FriendisOnlineRow.Length > 0)  // friend is online \n        {\n            //  new SQLHelper(SQLHelper.ConnectionStrings.WebSiteConnectionString).Update("Update clients set USER_STATUS='O' where CLIENT_ID=" + FriendsDt.Rows[i][0]);\n            FriendsInfo.Rows.Add(FriendsDt.Rows[i][0] + "," + FriendsDt.Rows[i][1] + "," + FriendsDt.Rows[i][2] + "," + "O");\n        }\n    }\n\n    var rows = FriendsInfo.Rows\n        .OfType<DataRow>()\n        .Select(row => row.ItemArray)\n        .ToArray();\n    return rows;\n}	0
3626606	3626322	Passing data from the model into custom validation class	[AttributeUsage(AttributeTargets.Class)]\npublic class StartLessThanEndAttribute : ValidationAttribute\n{\n    public override bool IsValid(object value)\n    {\n        var model = (MyModel)value;\n        return model.StartDate < model.EndDate;\n    }\n}\n\n[StartLessThanEnd(ErrorMessage = "Start Date must be before the end Date")]\npublic class MyModel\n{\n    public DateTime StartDate { get; set; }\n    public DateTime EndDate { get; set; }\n}	0
19717619	19717512	Run some code asynchronously with timeout	var cts = new CancellationTokenSource(3000); // Set timeout\n\nvar task = Task.Run(() =>\n{\n    while (!cts.Token.IsCancellationRequested)\n    {\n        // Working...\n    }\n\n}, cts.Token);	0
11046880	11045577	Getting twitter Profile data in C#	using (var wc = new WebClient())\n{\n    string searchText = "kool_aid_wino";\n    string json = wc.DownloadString("http://search.twitter.com/search.json?rpp=100&q="+searchText);\n    dynamic dynJson = JsonConvert.DeserializeObject(json);\n    foreach (var result in dynJson.results)\n    {\n        Console.WriteLine("{0} --> {1} : {2}\n", result.from_user, result.to_user, result.text);\n    }\n}	0
13583468	13583193	Deserialize json formatted string on server side	public class MyType\n{\n    public IList<string[]> List { get; set; }\n}	0
11616367	11616319	DataGridView variable formatting	DataSet.Datatable.Rows.Count	0
12056856	12055883	Selecting an item from AutoComplete suggestion list raises KeyDown-event with ENTER key	private void textBox1_KeyDown(object sender, KeyEventArgs e) {\n        if (e.KeyData == Keys.Enter && GetKeyState(Keys.Enter) < 0) {\n            Console.WriteLine("Really down");\n        }\n    }\n\n    [System.Runtime.InteropServices.DllImport("user32.dll")]\n    private static extern short GetKeyState(Keys key);	0
20467794	20467245	set textblock of isolated storage	[DataContract]\npublic class MyTextBox : TextBox\n{\n     // your implementations here\n     [DataMember]\n     public string Name { get; set;}\n}	0
29536104	29535893	Property Injection fails with Autofac	builder.RegisterControllers(typeof(MvcApplication).Assembly)\n       .PropertiesAutowired();	0
22151788	22151721	Dynamically create a database connection for SQL Server	string username = Console.ReadLine();\n\nSqlConnection conn = new SqlConnection("User ID=" + username);	0
13419743	13419669	Get XML Innertext	var ytlinks = node.SelectSingleNode("YTLINKS");\n\nforeach (XmlNode node2 in ytlinks.SelectNodes("YTLINK"))\n{           \n    YT_LINKS.Add(node2.InnerText);\n}	0
32836922	32836742	Please help in simple pattern program in c#	int spacelimit = 13, num = 1, n = 5;\n        for (int i = 1; i <= n; i++)\n        {\n            for (int space = spacelimit; space >= i - 3; space--) // HERE, I MADE i-3\n            {\n                Console.Write(" ");\n            }\n            for (int k = 1; k <= i; k++)\n            {\n                Console.Write("{0,3:D} ", num++);\n            }\n            spacelimit = spacelimit - 3;\n            Console.WriteLine();\n        }\n        Console.ReadKey();	0
16550663	16550573	Setting DefaultValue to first and last date of current month	DateTime today = DateTime.Today;\nint daysInMonth = DateTime.DaysInMonth(today.Year, today.Month);\n\nDateTime startOfMonth = new DateTime(today.Year, today.Month, 1);    \nDateTime endOfMonth = new DateTime(today.Year, today.Month, daysInMonth);	0
27000876	26998164	Fill a rectangle with an image using Mono Cairo Library	Cairo.Rectangle imageRectangle = new Cairo.Rectangle(50, 100, width, height);\n\n    ctx.NewPath();\n    Cairo.ImageSurface imgSurface = new Cairo.ImageSurface("C:/Temp/Image.png");\n\n\n    float xScale = (float)imageRectangle.Width / (float)imgSurface.Width;\n    float yScale = (float)imageRectangle.Height / (float)imgSurface.Height;\n\n    //Reposition the image to the rectangle origin\n    ctx.Translate(imageRectangle.X, imageRectangle.Y);\n    ctx.Scale(xScale, yScale);\n\n    ctx.SetSource(imgSurface); \n    ctx.Paint();	0
14348937	14336842	Dictionary Lookup - Specific String	public static byte[] DmxDataMessage(Tuple<byte, byte> redTuple, Tuple<byte, byte> greenTuple, Tuple<byte, byte> blueTuple, EnttecDmxController _enttecDmxControllerInterface)\n{\n\n    foreach (KeyValuePair<string, Tuple<byte, byte>> entry in _enttecDmxControllerInterface.DmxChannelsDictionary)\n    {\n        if (entry.Key.Contains("Red"))\n        {\n            dmxBuffer[entry.Value.Item1] = redTuple.Item2;\n        }\n    }\n     .......\n}	0
24632579	24632466	Rounding up a time to the nearest hour	string inputdate = "2:56:30 8/7/2014";\n\nDateTime dt;\nSystem.Globalization.CultureInfo enUS = new System.Globalization.CultureInfo("en-US");\n\nif (DateTime.TryParseExact(inputdate, "H:m:s d/M/yyyy", // hours:minutes:seconds day/month/year\n    enUS, System.Globalization.DateTimeStyles.None, out dt))\n{\n  // 'dt' contains the parsed date: "8-7-2014 02:56:30"\n  DateTime rounded = new DateTime(dt.Year, dt.Month, dt.Day, dt.Hour, 0, 0);\n  if (dt.Minute > 0 || dt.Second > 0) // or just check dt.Minute >= 30 for regular rounding\n    rounded = rounded.AddHours(1);\n\n  // 'rounded' now contains the date rounded up: "8-7-2014 03:00:00"\n}\nelse\n{\n  // not a correct date\n}	0
10625223	10625147	ImageBrush for Grid programmatically	var ib = new ImageBrush {\n  ImageSource =\n    new BitmapImage(\n      new Uri(@"Images\bg1.jpg", UriKind.Relative)\n    )\n};\n\nRootGrid.Background = ib;	0
3223037	3223020	How do I create a string from a block of text that contains the " character	var html = @"<html>\n<body>\n    <span id=""name""> somethnig more</span>\n</body>\n</html>";	0
24114499	24114441	How to find user control kept inside another usercontrol from parent aspx page in asp.net?	yourUserControl.FindControl("ControlName you searching for");	0
22602577	22602459	how to code behind a html button?	function Button1_onclick() \n  {\n  window.location.assign("Search.aspx")\n  }	0
8307757	8307722	how can i get current phone timezone in windowsphone	TimeZoneInfo localZone = TimeZoneInfo.Local;\nstring text = String.Format("{0}{1}:{2:00} ({3})",(localZone.BaseUtcOffset >= TimeSpan.Zero) ? "" : "-", Math.Abs(localZone.BaseUtcOffset.Hours),\n                          Math.Abs(localZone.BaseUtcOffset.Minutes),TimeZoneInfo.Local.DisplayName);	0
23057788	23057419	<double> RegEx catching IP addresses	AddRule<double>("!!float", @"^[0-9]*(?:\.[0-9]*)?$",\n            m => Convert.ToDouble(m.Value.Replace("_", "")), null);	0
13052215	13051893	Insert users into levels based on sales/age	Employees.ForEach(e => Console.WriteLine("{0} - {1} Sale/s",e.Name, e.Sales.Count().ToString()));\n\n    int[] levels = new int[1];\n    levels[0] = 50;\n\n    for (int i = 0; i < levels.Length; i++)\n        {\n        var emps = Employees.Where(e => e.Sales.Count() <= levels[i]);\n\n        emps.ForEach(Console.WriteLine("{0} salesmen have reachead level {1}: under {2} sales", emps.Count(), i.ToString(), levels[i]);\n        // Remove employees from the list that already achived the level (so they won't be counted again).\n        Employess.RemoveAll(e=> e.Sales.Count() <= levels[i]);\n        }	0
10346511	10346459	C# show a form to user if some parameters are not set	btnSend_Click(...)\n{\n   EmailSendingClass sender = new EmailSendingClass();\n   //  Initialize sender with from, to, etc.\n   if (!sender.IsComplete)\n   {\n       FrmGetMissingFields frm = new FrmGetMissingFields(sender);\n   }\n   sender.SendEmail();\n}	0
29222660	29222539	How to show or hide a tooltip under specific conditions? IWin32window win?	((ToolTip)sender).Hide(someControlWithTooltipBeingShown);	0
23354017	23324096	How to get the option set from a field in an entity in CRM 2011 using crm sdk and C#	public static void GetOptionSet(string entityName, string fieldName, IOrganizationService service)\n    {\n\n        var attReq = new RetrieveAttributeRequest();\n        attReq.EntityLogicalName = entityName;\n        attReq.LogicalName = fieldName;\n        attReq.RetrieveAsIfPublished = true;\n\n        var attResponse = (RetrieveAttributeResponse)service.Execute(attReq);\n        var attMetadata = (EnumAttributeMetadata)attResponse.AttributeMetadata;\n\n        var optionList = (from o in attMetadata.OptionSet.Options\n            select new {Value = o.Value, Text = o.Label.UserLocalizedLabel.Label}).ToList();\n\n\n    }	0
21581680	21581434	Reverse Single String value	string Reverse(string s)\n{\n    char[] c = new char[s.Length];\n    for (int i = s.Length-1, j = 0; i >=0 ; i--, j++)\n    {\n        c[j] = s[i];\n    }\n    return new string(c);\n}	0
8091326	8091130	Which was the best way to store the data that was coming from excel	main (\nid int,\ndescription varchar(255)\n)\n\nperiod\n(\nmain_id int (fk main(id))\nperiod int,\nperiod_length int, --in months or years, whatever is more appropriate\nperiod_value float\n)	0
29430380	29430169	ASP.NET listbox selected item change textbox text	private void ListBox1_SelectedIndexChanged(object sender, System.EventArgs e)\n{\n   // Get the currently selected item in the ListBox. \n   string curItem = listBox1.SelectedItem.ToString();\n\n   switch(curItem)\n   {\n       case "Person1":\n           TextBoxPersons.Text = "Andersson";\n       break;\n       case "Person2":\n           TextBoxPersons.Text = "Smith";\n       break;\n       //Add more cases and perhaps a default...\n   }\n}	0
11581180	11579956	Can't find text in PdfTable	// t is a PdfPTable\n        foreach(var row in t.Rows)\n        {\n            foreach(var cell in row.GetCells())\n            {\n                if(cell.Phrase != null)\n                {\n                    cell.Phrase.Font = fontNormal;\n                }\n            }\n        }	0
29322886	29322828	How do I make the objects appear again after they disappeared	if(x > terrainXEndpoint){\n   x = 0;\n}\nif(x < 0){\n   x=terrainXEndpoint;\n}\n\nif(y > terrainYEndpoint){\n   y = 0;\n} \nif(y<0){\n   y=terrainYEndpoint;\n}	0
26398192	26398130	How to bind a command to Window Loaded event using WPF and MVVM	var vm = this.DataContext as YourViewModel;\nvm.SearchCommand.Execute(null);	0
10343402	10343304	Parsing Expressions as a parameter	// Create an expression tree.\nExpression<Func<int, bool>> exprTree = num => num < 5;\n\n// Decompose the expression tree.\nParameterExpression param = (ParameterExpression)exprTree.Parameters[0];\nBinaryExpression operation = (BinaryExpression)exprTree.Body;\nParameterExpression left = (ParameterExpression)operation.Left;\nConstantExpression right = (ConstantExpression)operation.Right;\n\nConsole.WriteLine("Decomposed expression: {0} => {1} {2} {3}",\n              param.Name, left.Name, operation.NodeType, right.Value);\n\n// This code produces the following output:\n// Decomposed expression: num => num LessThan 5	0
3630840	3630821	What was the name of the set accessor that only lets the value to be set in the constructor?	public class MyClass\n{\n    private readonly string _name;\n    public MyClass(string name)\n    {\n        _name = name;\n    }\n\n    public string Name \n    {\n        get { return _name; }\n    }\n}	0
2762704	2762686	c# - pull records from database without timeout	YourCommandObject.CommandTimeout = 0;	0
18901359	18900985	Read File, Search for Term and replace all line of this term	Regex r = new Regex(@"\s");\nString[] tokens = r.Split(tempLineValue);\nstring settings = string.Empty;\nfor (int i = 0; i < tokens.Length; i++)\n{\n   if (tokens[i].Contains(searchTerm))\n   {\n       settings = tokens[i];\n       break;\n   }\n}\nif (settings != string.Empty)\n    outputWriter.WriteLine((tempLineValue.Replace(settings, replaceTerm));\nelse\n    outputWriter.WriteLine(tempLineValue);	0
21642685	21642480	how to close an application on clicking the OK button of windows phone 7 application	if (result == MessageBoxResult.OK)\n{\n    while (NavigationService.CanGoBack)\n    {\n        NavigationService.RemoveBackEntry();\n    }\n    NavigationService.GoBack();\n}	0
28536936	28534974	Change Excel Comment Font in C# VSTO	var selection = Globals.ThisAddIn.Application.Selection as Range;\nvar textFrame = selection.Comment.Shape.TextFrame;\ntextFrame.Characters().Font.ColorIndex = 3;\ntextFrame.Characters().Font.Size = 30;	0
1541167	1541155	C#, Search string, ASP	string searchTerm = "hello world";\nbool foundIt = txtReadDocs.Text.IndexOf(searchTerm, StringComparison.OrdinalIgnoreCase) >= 0;	0
7721529	7721406	Running the C# compiler from a C# program	static void CompileCSharp(string code) {\n    CodeDomProvider provider = CodeDomProvider.CreateProvider("C#");\n    ICodeCompiler compiler = provider.CreateCompiler();\n    CompilerParameters parameters = new CompilerParameters();\n    parameters.OutputAssembly = @"D:\foo.exe";\n    parameters.GenerateExecutable = true;\n    CompilerResults results = compiler.CompileAssemblyFromSource(parameters, code);\n    if (results.Output.Count == 0)\n    {\n        Console.WriteLine("success!");\n    }\n    else\n    {\n        CompilerErrorCollection CErros = results.Errors;\n        foreach (CompilerError err in CErros)\n        {\n            string msg = string.Format("Erro:{0} on line{1} file name:{2}", err.Line, err.ErrorText, err.FileName);\n            Console.WriteLine(msg);\n        }\n    }\n}	0
18418344	18418300	How to change path location of image from a folder to another	// Simple synchronous file move operations with no user interface. \npublic class SimpleFileMove\n{\n    static void Main()\n    {\n        string sourceFile = @"C:\Users\Public\public\test.txt";\n        string destinationFile = @"C:\Users\Public\private\test.txt";\n\n        // To move a file or folder to a new location:\n        System.IO.File.Move(sourceFile, destinationFile);\n\n        // To move an entire directory. To programmatically modify or combine \n        // path strings, use the System.IO.Path class.\n        System.IO.Directory.Move(@"C:\Users\Public\public\test\", @"C:\Users\Public\private");\n    }\n}	0
2257042	2257016	Render HtmlGenericControl from a HttpHandler	using (StringWriter stringWriter = new StringWriter())\n{\n    HtmlTextWriter htmlTextWriter = new HtmlTextWriter(stringWriter);\n    holder.RenderControl(htmlTextWriter);\n    HttpContext.Response.Write(stringWriter.ToString());\n    htmlTextWriter.Close();\n    stringWriter.Close();\n}	0
19174120	19173998	Detect whether button was right or left clicked	var btn = new Button();\nbtn.Text = "BUTTON";\nbtn.MouseDown += ((o, e) => {\n    MessageBox.Show(e.Button.ToString());\n});	0
19707502	19683863	Context Attach Method Exception	context.Configuration.AutoDetectChangesEnabled = false;\ncontext.Configuration.ValidateOnSaveEnabled = false;	0
14202433	14201149	Wpf FlowDocumentReader column property	reader.Document.ColumnWidth = 1000;	0
20584535	20584507	Printing items from Class based List	var textBox = new TextBox();\ntextBox.Text = minaVaror[0].artNamn;	0
8902416	8902359	Session instead of viewsate	var key = UserID + "_personList";\nCache.Add(key, personList, null, \n  DateTime.Now.AddSeconds(60), \n  Cache.NoSlidingExpiration,\n  CacheItemPriority.High, \n  null);	0
27639266	26736010	how to retrieve data from database into textbox and save the edited data from the same textbox to database	if (!IsPostBack)\n{\n    string CSs = ConfigurationManager.ConnectionStrings["Koshur"].ConnectionString;\n    using (SqlConnection conn = new SqlConnection(CSs))\n    {\n        string query = "select * from userdetails where Username='" + \n            HttpContext.Current.User.Identity.Name.ToString() + "';";\n        SqlCommand cmd = new SqlCommand(query, conn);\n        SqlDataAdapter da = new SqlDataAdapter(cmd);\n        DataSet ds = new DataSet();\n        da.Fill(ds, "userdetails");\n        firstnametext.Text = ds.Tables["userdetails"].Rows[0]["Firstname"].ToString();\n        lastnametext.Text = ds.Tables["userdetails"].Rows[0]["Lastname"].ToString();\n        dobtext.Text = ds.Tables["userdetails"].Rows[0]["Dateofbirth"].ToString();\n        contacttext.Text = ds.Tables["userdetails"].Rows[0]["ContactNO"].ToString();\n    }\n}	0
23952202	23951981	how to get text value of label in grid view control	Label lbl_Activity_Code = (Label)row.FindControl("lbl_Activity_Code");\nif(lbl_Activity_Code != null)\n     string text = lbl_Activity_Code.Text;	0
33673780	33673370	Parsing multiple XML objects in one file	string data = "\n<?xml version=\"1.0\" encoding=\"UTF-8\"?><element1 value=\"3\"><sub>1</sub></element1>\n<element1><sub><element>2</element></sub></element1>\n \n<element2><sub>3</sub></element2>\n \n<element2><sub>4</sub></element2>";\n\n    //Clear whitespace and parse out the header\n    data = data.Trim();\n    var pos = data.IndexOf("?>") + 2;\n    data = string.Concat("<root>",data.Substring(pos, data.Length - pos), "</root>");\n\n    var xml = XDocument.Parse(data);\n\n    //Nodes will have all the elements1, 2... etc.\n    var nodes = xml.Descendants().Where(d => d.Name.LocalName.Contains("element"));\n\n    //if you need to load to string list.\n    var items = new List<string>();\n    foreach(var node in nodes)\n    {\n        items.Add(node.ToString());\n    }	0
9225824	9225647	log4net - different log-files for assembly	// Setup RollingFileAppender\n  log4net.Appender.RollingFileAppender fileAppender = new log4net.Appender.RollingFileAppender();\n  fileAppender.Layout = new log4net.Layout.PatternLayout("%d [%t]%-5p %c [%x] - %m%n");\n  fileAppender.MaximumFileSize = "100KB";\n  fileAppender.MaxSizeRollBackups = 5;\n  fileAppender.RollingStyle = log4net.Appender.RollingFileAppender.RollingMode.Size;\n  fileAppender.AppendToFile = true;\n  fileAppender.File = fileName;\n  fileAppender.Name = "XXXRollingFileAppender";\n  log4net.Config.BasicConfigurator.Configure(fileAppender);	0
4171145	4171130	Split String with spaces and minus sign	string[] titledata = title.Split(new[] { " - " }, StringSplitOptions.None)	0
28053785	28053278	Coloring rows before columns in DataGridView	void OnGridCellPainting(object sender, System.Windows.Forms.DataGridViewCellPaintingEventArgs e)\n{\n    if (e.RowIndex >= 0 && e.ColumnIndex == mLastSortColumnIndex)\n        e.CellStyle.BackColor = Color.LightGray;\n}	0
12268906	12267553	Mouse over highlighting of dates in ASP.NET calender	Color col = new Color();\ncol = (e.IsSelected) ? Calendar1.SelectedDayStyle.BackColor.ToString() : Calendar1.DayStyle.BackColor.ToString();\n\ne.Cell.Attributes["onmouseover"] = "this.style.backgroundColor='pink';";\ne.Cell.Attributes["onmouseout"] = "this.style.backgroundColor='" + col + "';";	0
17765533	17765521	Trim comboBox with non fixed number	textBox1.Text = comboBox1.Text.Split('-').First().Trim();	0
33014729	33014409	How to change the volume by using mouse wheel?	void Form1_MouseWheel(object sender, MouseEventArgs e)\n    {\n        if(e.Delta > 0)\n            wmpPlayer.settings.volume = activeMusic.settings.volume + 1;\n        else\n            wmpPlayer.settings.volume = activeMusic.settings.volume - 1;\n\n        //to check the volume no.\n        MessageBox.Show(Convert.ToString(wmpPlayer.settings.volume));\n    }	0
31047547	10202584	Using Dapper to map more than 5 types	connection.Query<TypeOfYourResult>\n(\n   queryString,\n   new[]\n   {\n      typeof(TypeOfArgument1),\n      typeof(TypeOfArgument2),\n      ...,\n      typeof(TypeOfArgumentN)\n   },\n   objects =>\n   {\n      TypeOfArgument1 arg1 = objects[0] as TypeOfArgument1;\n      TypeOfArgument2 arg2 = objects[1] as TypeOfArgument2;\n      ...\n      TypeOfArgumentN argN = objects[N] as TypeOfArgumentN;\n\n     // do your processing here, e.g. arg1.SomeField = arg2, etc.\n     // also initialize your result\n\n     var result = new TypeOfYourResult(...)\n\n     return result;\n   },\n   parameters,\n   splitOn: "arg1_ID,arg2_ID, ... ,argN_ID"\n);	0
32719558	32719368	How to select unique list out of collection of lists?	var filteredList = Modifiers\n  .GroupBy(modifier => modifier.Id)\n  .Select(chunk => chunk.First());	0
22151416	22151376	Will this linq display object with latest date?	Context.Objects.Where(p => p.ObjectId == ObjectId)\n       .OrderByDescending(p => p.DateOrdered)\n       .First();	0
12320379	12317509	Unable to use MongoDB from my C# console application	> db.version()\n2.2.0\n> db.runCommand("ping")\n{ "ok" : 1 }\n>	0
665740	665721	How can I programmatically check in a C# installer class if IIS supports Application Pools?	Key: \HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\InetStp\nValue Name: MajorVersion	0
32955972	32955927	Converting a file into stream	foreach (var file in Directory.GetFiles(networkpath))\n{\n    using (FileStream fs = File.Open(file, FileMode.Open))\n    {\n\n    }\n}	0
30045808	30045468	Ho do I get the cell value from a datagridview using row index and column index in c#?	myvalue =dgvList.Rows[rowindex].Cells[columnindex].Value.ToString();	0
16181755	16181685	How to change Repeater DataSourceID?	rpProducts.DataSource = null;\nrpProducts.DataSourceID = ItemDataSource.ID;\nrpProducts.DataBind();	0
3068195	3068168	How to read a key pressed by the user and display it on the console?	Console.WriteLine("Enter any Key: ");\nConsoleKeyInfo name = Console.ReadKey();\nConsole.WriteLine("You pressed {0}", name.KeyChar);	0
15754982	15754973	c# Sorting a Custom List	MyAddressList = MyAddressList.OrderBy( x => x.Suburb ).ThenBy(x => x.Street).ToList();	0
9073090	9073018	On Postback, the DataTable data source for a Repeater is empty?	public void addNewItem(object sender, EventArgs e) {\n  DataTable theItems = this.items;\n  DataRow r = theItems.NewRow()\n  theItems.Rows.Add(r);\n  this.items = theItems\n  myRepeater.DataBind(); //I'm not sure if this belongs here because of the reasons said before\n}	0
15152010	15151529	How to Sort list	private void btnSort_Click(object sender, RoutedEventArgs e)\n{\n    List<string> list = lstbxResults.Cast<string>().OrderBy(p=>p).ToList();\n\n    lstbxResults.Clear();\n    foreach(var item in list)\n        lstbxResults.Items.Add(item);\n}	0
26469891	26410146	How to return Wrapper obj of TableOjb1 and TableObj2 using linq	public IEnumerable<MergeObj> QueryJoin()\n    {\n        List<TableObj1> t1 = conn.Table<TableObj1>().ToList();\n        List<TableObj2> t2 = conn.Table<TableObj2>().ToList();\n\n        return t1.Join(t2, outer => outer.Id, \n                           inner => inner.Id, \n                           (outer, inner) => new MergeObj { Obj1 = outer, Obj2 = inner });\n    }	0
27397591	27397289	How to open a file using a text path	System.Diagnostics.Process.Start(textBox1.Text)	0
10591966	10586437	convert Facebook.JsonObject into my model	dynamic myInfo = _fb.Get("/me/friends?fields=id,name,picture");\n\nentity.Friends = (\n     from dynamic friend \n       in (IList<object>) myInfo["data"] \n  orderby friend.name ascending  \n   select new UserFriend()  {\n               Id = (long)friend.id, \n               Name = (string)friend.name,\n               Picture = (string)friend.picture }\n).ToList();	0
23794627	23794479	How to handle SlideShowBegin Event in C#	private void ThisAddIn_Startup(object sender, System.EventArgs e)\n{\n    Application.SlideShowBegin += Application_SlideShowBegin;   \n}\n\n\n\nprivate void Application_SlideShowBegin(PowerPoint.SlideShowWindow Wn)\n{\n    // your implementation\n}	0
31088945	31088824	c# getting xml node that doesn't have close tag explicity	XmlDocument doc = new XmlDocument();\n    doc.LoadXml(responseMessage);\n    var node  = doc.DocumentElement.SelectSingleNode("//Error");\n\n    if (null != node && string.IsNullOrEmpty( node.InnerText ))\n    {\n\n    }	0
20318552	20318424	XMLDocument Selection	XmlDocument doc = new XmlDocument();\n    doc.Load("http://api.wunderground.com/api/74e1025b64f874f6/forecast/conditions/q/zmw:00000.1.95784.xml");\n    XmlNode node = doc.DocumentElement.SelectSingleNode("/response/forecast/txt_forecast/forecastdays/forecastday[period=0]/fcttext");\n\n    String Forecast = node.InnerText;	0
8473721	8473527	C# DataAccess Update, Insert, Delete	new DAL().Execute("INSERT INTO TABLE TABLENAME VALUES (...)");	0
7077949	6936537	How to append Values to Excel Range	Application.Union(Range1,Range2)	0
13698809	13669733	Export DataTable to excel with EPPlus	using (ExcelPackage pck = new ExcelPackage(newFile))\n{\n  ExcelWorksheet ws = pck.Workbook.Worksheets.Add("Accounts");\n  ws.Cells["A1"].LoadFromDataTable(dataTable, true);\n  pck.Save();\n}	0
23675282	23675211	how to retrieve file data(.txt) to respective text box?	myAmazingTextBox.Text = File.ReadAllText(openFileDialog1.FileName);	0
16896414	16896284	Opening a URL in a new tab	Response.Write(String.Format("window.open('{0}','_blank')", ResolveUrl(pageurl)));	0
19147653	19121972	How to use Binder.GetIndex	var binder = Binder.GetIndex(CSharpBinderFlags.None, typeof (SampleDynamicObject), new[]\n{\n    CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.None, null),\n    CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.UseCompileTimeType, null) // this argument is required!\n});\nvar callsite = CallSite<Func<CallSite, object, object, object>>.Create(binder);\nvar obj = callsite.Target(callsite, sampleObject, 0); // 0 is an index	0
13253805	13250200	Running application at startup in Windows CE 5.0	HKLM\Init	0
27222760	27222484	Iterating over a custom collection of objects and deleting duplicates	var keepers =\n    objTestReports\n        .Cast<TestReport>()\n        .GroupBy(x => new { x.LocalReportID, x.ScoreTypeID })\n        .SelectMany(x => x.Take(1))\n        .ToArray();\n\nobjTestReports.Clear();\n\nforeach (var objTestReport in keepers)\n{\n    objTestReports.Add(objTestReport);\n}	0
20038718	20038506	get most frecuent k-length kmers in string	var term = "01xTTx10TxT1x10Tx0Tx10Tx0x0x1T";\nvar dict = new Dictionary<string, int>();\nfor (var i = 0; i < term.Length - 4; i++)\n{\n    var kmer = term.Substring(i, 4);\n    if (!dict.ContainsKey(kmer))\n        dict[kmer] = Regex.Matches(term, kmer).Count;\n\n}\n\nvar maxOccurring = dict.Max(m => m.Value);\nvar maxOccurringTerm = dict.Where(l => l.Value == maxOccurring);	0
34406981	34193127	Send email to particular segment and framework	if(email=='')\n{\n  if (segment='')\n {  }\n}	0
22374428	22374281	Replace Old FIle with the New upload File	File.Delete(Server.MapPath(Path.Combine("~/Data/", MyFile)));	0
14404610	14397392	Overwriting root element in syndicationfeed, Adding namespaces to root element	var feed = new SyndicationFeed("foo", "bar", new Uri("http://www.example.com"));\nvar rssFeedFormatter = new Rss20FeedFormatter(feed);\n\n// Create a new  XmlDocument in order to modify the root element\nvar xmlDoc = new XmlDocument();\n\n// Write the RSS formatted feed directly into the xml doc\nusing(var xw = xmlDoc.CreateNavigator().AppendChild() )\n{\n    rssFeedFormatter.WriteTo(xw);\n}\n\n// modify the document as you want\nxmlDoc.DocumentElement.SetAttribute("xmlns:example", "www.example.com");\n\n// now create your writer and output to it:\nvar sb = new StringBuilder();\nusing (XmlWriter writer = XmlWriter.Create(sb))\n{\n    xmlDoc.WriteTo(writer);\n}\n\nConsole.WriteLine(sb.ToString());	0
3516708	2962071	keep focus in a WPF combo box in an addin	protected override CreateParams CreateParams\n    {\n        get\n        {\n            CreateParams p = base.CreateParams;\n            if (!DesignMode)\n            {\n                unchecked\n                {\n                    p.Style = (int)(WindowStyles.WS_VISIBLE |\n                                    WindowStyles.WS_POPUP |\n                                    WindowStyles.WS_CLIPSIBLINGS |\n                                    WindowStyles.WS_CLIPCHILDREN);\n                }\n            }\n            return p;\n        }\n    }	0
19193427	19191687	asp control from ascx codebehind	protected global::System.Web.UI.WebControls.Literal test1;	0
4613979	4612990	How to call a stored proc from LINQ to SQL if working "code-first"	ISingleResult<MySPResult> spResult = DataContext.MySP( params )	0
26285820	26264563	ASP.NET user control property in a repeater is null after postback	if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)\n        {\n            TransactionPage transaction = (TransactionPage)e.Item.DataItem;\n            TransactionPagePartial visual = (TransactionPagePartial)Page.LoadControl("~/Views/Pages/Partials/TransactionPagePartial.ascx");\n            visual.transaction = transaction;\n            rptTransactionVisual.Controls.Add(tombstone);\n        }	0
5628177	5627730	How would the following c(++)-struct be converted to C# for p/invoke usage	[StructLayout(LayoutKind.Sequential)]\npublic struct MyStruct\n{\n    public string point_name;\n    public string param_name;\n    public Int32 param_offset;\n    public VariantWrapper param_value;\n    public Int32 param_type;\n    public Int32 status;\n};	0
16043787	16043475	Play part of MP3 using ASP.NET	bigfile_1.mp3; bigfile_2.mp3	0
4846496	4846493	how to always round up to the next integer	Math.Ceiling((double)list.Count() / 10);	0
123340	123336	How can you strip non-ASCII characters from a string? (in C#)	string s = "s??me string";\ns = Regex.Replace(s, @"[^\u0000-\u007F]", string.Empty);	0
12106702	12106590	How To: Best way to run a threaded loop with a UI update at the end of each?	delegate void updStatusbar(int i);\npublic UpdateStatusBar(int i)\n{\n  if (Statusbar1.InvokeRequred)\n  {\n    updStatusbar c = UpdateStatusBar;\n    this.Invoke(c,new object[] {i});\n  }\n  else\n    Statusbar1.value=i;\n  }\n}	0
15662415	15662374	How to write a cookie inside a static method	public static void WriteCookie(HttpContext context, Guid token)\n{ \n    HttpCookie cookie = new HttpCookie("LoginControl");\n\n    cookie.Value = token.ToString();\n    cookie.Expires = DateTime.Now.AddHours(0.5);\n\n    context.Response.Cookies.Add(cookie);\n}	0
34189061	34189010	How to enable/disable a textbox with a button	textbox11.IsEnabled = true;	0
30575107	30570872	ViewPager/PagerAdapter shows all views on first page	public override bool IsViewFromObject(View view, Java.Lang.Object @object)\n{\n    return (object)view == @object;\n}	0
27004303	26998122	Multiple colored Activity Label element on Xamarin.Android	var textView = FindViewById<TextView>(Resource.Id.my_label);\n    var span = new SpannableString("My Label");\n\n    span.SetSpan(new ForegroundColorSpan(Color.Red), 0, 2, 0);  // "My" is red\n    span.SetSpan(new ForegroundColorSpan(Color.Blue), 3, 8, 0); // "Label" is blue\n    textView.SetText(span, TextView.BufferType.Spannable);	0
16781199	16778325	TextBox with maxvalue	int box_int = 0; Int32.TryParse(textBox1.Text, out box_int);\nif (box_int > 1050 && textBox1.Text != "") { textBox1.Text = "1050"; }	0
18176626	17968742	Unable to dynamically update display report in Report Viewer Control	private void ReinitializeViewer(string tsReport)\n{\n       ReportDataSource ReportDataSourceX = new ReportDataSource();\n        this.PurchaseReprotViewer.Reset();\n\n        if (tsReport.Contains("Rpt_PurchaseInvoice.rdlc"))\n        {\n            ReportDataSourceX.Name = "PurchaseInvoiceDataSet";\n            ReportDataSourceX.Value = this.purchaseBindingSource;\n            this.PurchaseReprotViewer.LocalReport.DataSources.Add(ReportDataSourceX);\n            this.PurchaseReprotViewer.LocalReport.ReportEmbeddedResource = tsReport;\n            this.PurchaseReprotViewer.RefreshReport();\n        }\n\n    }	0
3411359	3411339	SQL INSERT from SELECT	insert into myDestTable (userid, name, value, othercolumns)\nselect us.userid, us.name,'myvaluefromcode', othercolumns\nfrom users us \nwhere us.name = 'mynamefromcode'	0
17826426	17825677	Extracting frames of a .avi file	// create instance of video reader\n VideoFileReader reader = new VideoFileReader( );\n// open video file\nreader.Open( "test.avi" );\n// read 100 video frames out of it\nfor ( int i = 0; i < 100; i++ )\n{\n    Bitmap videoFrame = reader.ReadVideoFrame( );\n\n    videoFrame.Save(i + ".bmp")\n\n    // dispose the frame when it is no longer required\n    videoFrame.Dispose( );\n}\nreader.Close( );	0
23520391	23503628	Wpf xamlreader load xaml with custom elements	public class TextBox_Element{\n\n    public TextBox_Element(double x, double y){\n        // code\n    }\n    public TextBox_Element(){\n        // emptyness\n    }\n}	0
287567	287540	How to test a remoting connection (check state)	public void Ping() {}	0
5986738	5986662	get data from variable table and return as datatable c#	var query = String.Fromat("Select * from [{0}]", type.Name);\n        var sqlComm = new SqlCommand(query, sqlConn);\n        /*sqlComm.Parameters.AddWithValue("@table", type.Name);*/	0
5624845	5624830	Return filename without extension from full path in C#	return Path.GetFileNameWithoutExtension (fullpath);	0
20002505	20002387	c# idiom to check / assign variable	string strVariableName = (row["VariableName"] ?? "default value").ToString();	0
18711859	16218371	displaying a crystal report using c#	ReportDocument cryRpt = new ReportDocument();\n    cryRpt.Load(@"CRYSTAL REPORT PATH HERE\CrystalReport1.rpt");\n    crystalReportViewer1.ReportSource = cryRpt;\n    crystalReportViewer1.Refresh();	0
25940406	25936515	retrieve image to picture box from database in c# winforms	using (SqlConnection con = new SqlConnection(strConnection))\nusing (SqlCommand cmd = new SqlCommand("select companyLogo from companyDetailsTbl where companyId = 1", con))\n{\n    con.Open();\n    using (SqlDataReader reader = cmd.ExecuteReader())\n    {\n        if (reader.HasRows)\n        {\n            reader.Read();\n            pictureBox1.Image = ByteArrayToImage((byte[])(reader.GetValue(0)));\n        }\n    } \n}\n\npublic static Image ByteArrayToImage(byte[] byteArrayIn)\n{\n    using (MemoryStream ms = new MemoryStream(byteArrayIn))\n    { \n        Image returnImage = Image.FromStream(ms);\n        return returnImage;\n    }\n}	0
837477	837423	Render a section of an image to a Bitmap C# Winforms	private void DrawImageRectRect(PaintEventArgs e)\n{\n\n    // Create image.\n    Image newImage = Image.FromFile("SampImag.jpg");\n\n    // Create rectangle for displaying image.\n    Rectangle destRect = new Rectangle(100, 100, 450, 150);\n\n    // Create rectangle for source image.\n    Rectangle srcRect = new Rectangle(50, 50, 150, 150);\n    GraphicsUnit units = GraphicsUnit.Pixel;\n\n    // Draw image to screen.\n    e.Graphics.DrawImage(newImage, destRect, srcRect, units);\n}	0
15258029	15256994	Set value of root XElement without affecting child elements	private void ReplaceRegex(XElement xElement)\n{\n    if(xElement.HasElements)\n    {\n        foreach (XElement subElement in xElement.Elements())\n            this.ReplaceRegex(subElement);\n    }\n    foreach(var node in xElement.Nodes().OfType<XText>())\n    {\n        string value = node.Value;\n        if(this.ReplaceRegex(ref value))\n            node.Value = value;\n    }\n}	0
33031213	32993045	WPF custom effect animation programmatically	DoubleAnimation da = \nnew DoubleAnimation(0.0, 1.0, new Duration(new TimeSpan(0,0,1)); // adjust as needed\n\n(image1.Effect as WpfEffect).BeginAnimation(WpfEffect.para01Property, da);\n(image2.Effect as WpfEffect).BeginAnimation(WpfEffect.para01Property, da);\n(image3.Effect as WpfEffect).BeginAnimation(WpfEffect.para01Property, da);\n(image4.Effect as WpfEffect).BeginAnimation(WpfEffect.para01Property, da);	0
8436067	8435947	same random values	class YourClass\n{\n    private static Random randomGenerator = new Random();\n\n    public YourClass(int entriesCount)\n    {\n       int weight = 0;\n       for (int i = 0; i < entriesCount; i++)\n       {\n           weight = randomGenerator.Next(10);\n           this.weights[i] = weight;\n       }\n    }\n    // .. rest of your class	0
7105759	7105553	How to get cs files for xml schemas (xsd)	xsd /c A.xsd B.xsd Common.xsd	0
13226170	13224836	Datepicker - no reaction	DatePickerReady.js	0
26982074	26981792	Double.parse() in C# for data downloaded from webpage	var numberFormatInfo = new NumberFormatInfo();\n    numberFormatInfo.NumberDecimalSeparator = ".";\n    numberFormatInfo.NumberGroupSeparator = ",";\n    double result;\n    if (double.TryParse("10,000.00", NumberStyles.Any, numberFormatInfo, out result))\n    {\n        Console.WriteLine(result);\n    }	0
7876653	7876553	using a variable outside of a function C#	TextStyle txtstyle = new TextStyle(new SolidBrush(Properties.Settings.Default["Color"]), null, FontStyle.Regular); // the variable	0
8654279	8635155	ASP ListView Multiple Style	protected void ListInbox_ItemDataBound(object sender, ListViewItemEventArgs e)\n    {\n        Panel PanelMsg;\n        PanelMsg = (Panel)e.Item.FindControl("PanelMsg");\n\n        ListViewDataItem dataItem = (ListViewDataItem)e.Item;\n        string status = (string)DataBinder.Eval(dataItem.DataItem, "Status");\n        if (status == "unread")\n        {\n            PanelMsg.BackColor = System.Drawing.Color.Purple;\n        }\n    }	0
8093325	8093240	sorting with gridview inside a update panel in asp.net	if (direction.Equals("ASC")) \n      direction = "DESC";\nelse  \n      direction = "ASC";	0
19617929	19617844	WPF Change color of Rectangle placed inside Button	var rect = btnInitial.Template.FindName("rectInitial") as Rectangle;\nrect.Fill = Brushes.Aquamarine;	0
27227009	27226494	Active Directory - How to Escape Comma in CN	"LDAP://domain/CN=Smith\\, John, OU=Distribution..."	0
1391265	1391243	How do I build a search with the number of results for each category?	_categoryRepository\n  .Where(category=>category.Matches(query))\n  .Select(category.Items.Count())	0
26582669	26581670	Summing values across nested lists at each index	var list = new List<List<string>>\n{\n    new List<string> {"tom", "abc", "$525.34", "$123"},\n    new List<string> {"dick", "xyz", "$100", "$234"},\n    new List<string> {"harry", "", "$250.01", "$40"},\n    new List<string> {"bob", "", "$250.01", ""}\n};\n\ndecimal num;\nvar itemsPerLine = list[0].Count; // 4\nvar res = list.SelectMany(line => line);\n              .Select((s, i) => new { Text = s, Index = i })\n              .GroupBy(i => i.Index % itemsPerLine) // transformed matrix here\n              .Select(g => g.Sum(i => \n                   decimal.TryParse(i.Text, NumberStyles.AllowCurrencySymbol | \n                                            NumberStyles.AllowDecimalPoint, \n                                            new CultureInfo("en-US"), out num) \n                                            ? num : 0));	0
10671696	10666332	How to assign a class to an instance using saved model in weka	Classifier nbTree = (Classifier)SerializationHelper.read(Model) as NBTree;\nInstances testDataSet = new Instances(new BufferedReader(new FileReader(arff)));\ntestDataSet.setClassIndex(10);\nEvaluation evaluation = new Evaluation(testDataSet);\n\nfor (int i = 0; i < testDataSet.numInstances(); i++)\n{\n    Instance instance = testDataSet.instance(i);\n    evaluation.evaluateModelOnceAndRecordPrediction(nbTree, instance);\n}\n\nforeach (object o in evaluation.predictions().toArray())\n{\n    NominalPrediction prediction = o as NominalPrediction;\n    if (prediction != null)\n    {\n        double[] distribution = prediction.distribution();\n        double predicted = prediction.predicted();\n    }\n}	0
25760317	25760241	Itinerating Strings to Dictionary	Dictionary<string, Dictionary<string,string>> newDictionary = new Dictionary<string, Dictionary<string,string>>();\n\nforeach (SectionData section  in data.Sections)\n{\n    var keyDictionary = new Dictionary<string,string>();\n    foreach (KeyData key in section.Keys)\n        keyDictionary.Add(key.KeyName.ToString(),key.KeyValue.ToString());\n\n    newDictionary.Add(section.SectionName.ToString(), keyDictionary);\n}	0
8894879	8894834	how to find percentage	let percentage=100*(a-b)/a	0
9982047	9981802	Connecting / Copying from network drive C#	string updir = @"\\NetworkDrive\updates\somefile";\n\nAppDomain.CurrentDomain.SetPrincipalPolicy(PrincipalPolicy.WindowsPrincipal);\nWindowsIdentity identity = new WindowsIdentity(username, password);\nWindowsImpersonationContext context = identity.Impersonate();\n\nFile.Copy(updir, @"C:\somefile", true);	0
34195102	34140131	Display pdf from byte array to c# winforms	PDFViewer PDFViewer1;\nbyte[] baPDF; // load the decrypted PDF to this byte array\n...\nPDFViewer1.LoadDocument(baPDF);	0
1479523	1479499	How do I localize password validation in C#?	[\p{L}\p{N}_-]+	0
19953311	19953197	Multiple Regex matches in C#	Regex re = new Regex(@"<a href=""(.*?)"">.+name=""(.*?)""");\n\nMatchCollection matches = re.Matches(input);\n\nforeach (Match match in matches)\n{\n    Console.WriteLine("URL={0}, Name={1}", match.Groups[1].Value, match.Groups[2].Value);\n}	0
22915948	22915528	how to merge codes in c# with passing parameters?	var newlist = _repository.ReportRepository.GetTracks(jtStartIndex, jtPageSize, jtSorting).OrderBy(i => i.Date).ToList().GetRange(jtStartIndex, jtPageSize);	0
3530197	3530148	Selecting "custom distinct" items from a List using LINQ	var maxPolicies = policyList\n    .GroupBy(p => p.PolicyNumber)\n    .Select(grp => grp.OrderByDescending(p => p.PolicySequence).First());	0
10327664	10327513	WCF call a function without waiting for it to finish its job?	[OperationContract(IsOneWay = true)]	0
21674733	21674640	Search string using Pattern within long string in C#	foreach (Match m in Regex.Matches(big, "([A-Za-z]{3}[0-9]{5})"))\n{\n    if (m.Success)\n    {\n        m.Groups[1].Value // -- here is your match\n    }\n}	0
25420649	25420585	cross-thread opertion in combobox in c#	this.Invoke((MethodInvoker)delegate()\n    {\n        //// your code \n    });	0
16826149	16825030	How to initially hide the main GUI window with C#	protected override void SetVisibleCore(bool value) {\n    if (!this.IsHandleCreated) {\n        value = false;\n        this.CreateHandle();\n    }\n    base.SetVisibleCore(value);\n}	0
29447483	29446129	.Net MongoDB, Finding documents of custom class	public class Student\n          {\n            public int Id { get; set; }\n            public string name { get; set; }\n            public Scores[] scores { get; set; }\n          }	0
2889648	2889622	Remove anchor from URL in C#	srcstring.Substring(0,srcstring.LastIndexOf("#"));	0
5000739	5000489	how to edit and update row values in grid view?	protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)\n{ \nTextBox txtProdID = (TextBox)gvProducts.Rows[e.RowIndex].FindControl("txtProdID");\nTextBox txtProdName = (TextBox)gvProducts.Rows[e.RowIndex].FindControl("txtProdName");\n\n\n//Call update method\nProduct.Update(txtProdId,txtProdName);\n\ngvProducts.EditIndex = -1;\n//Refresh the gridviwe\nBindGrid(); \n}	0
4187806	4186932	Best way to remember DataGridView settings when rebinding DataSource	// pseudo code\nprivate void RefreshDGV()\n{\n    SaveUserSettings();\n    myDGV.SuspendLayout();\n    myDGV.DataSource = myDataSource;\n    ApplyUserSettings();\n    myDGV.ResumeLayout();\n}	0
33631000	33630801	Asp.net How do i delete objects with One To Many using entity framework	GridDataItem item = e.Item as GridDataItem;\n            Guid strId = new Guid(item.GetDataKeyValue("id").ToString());\n            team _team = _dal.SoccerEntities.teams.FirstOrDefault(p => p.id == strId);\n            if (_team != null)\n            {\n\n                 if( _team.players!= null &&  _team.players.Count>0)\n                 { var _palayers = _team.players.ToList();\n                    foreach (player _player in _palayers )\n                    {\n                        _dal.SoccerEntities.players.DeleteObject(_player);\n                    }\n                 }\n                _dal.SoccerEntities.teams.DeleteObject(_team);\n            }\n            _dal.SoccerEntities.SaveChanges();	0
21797159	21796319	Inherit from MasterPage	protected void Page_Load(object sender, EventArgs e)\n{\n    if (!IsPostBack)\n    {\n        string role;\n\n        var sessionValue = Session["Roles"];\n        if (sessionValue != null)\n           role = sessionValue.ToString();\n\n        else\n        {\n          string MyPage = System.IO.Path.GetFileName(Request.Path);\n          SqlDataReader RolePageDr = BLL.Users.RolesPage(MyPage);\n          while (RolePageDr.Read())\n          {\n            role = RolePageDr["Roles"].ToString();\n            Session["Roles"] = role;\n          }\n        }\n\n        if (Page.User.IsInRole(Rolepage) != true)\n        {\n                Response.Redirect("~/MsgPage.aspx");\n        }\n        else\n                Response.Redirect(MyPage);\n    }\n}	0
7589282	7586807	Passing clicked hyperlink text in query string	{?URLParameter} + {Table.Field}	0
722265	722240	Instantly detect client disconnection from server socket	static class SocketExtensions\n{\n  public static bool IsConnected(this Socket socket)\n  {\n    try\n    {\n      return !(socket.Poll(1, SelectMode.SelectRead) && socket.Available == 0);\n    }\n    catch (SocketException) { return false; }\n  }\n}	0
12124420	12123970	Unable to edit tables in SQL Server 2008 database using C#	CREATE TABLE YourTable\n(\n   Id INT IDENTITY(1,1) PRIMARY KEY,\n   .......\n);	0
18443949	18443735	Using a pre-existing PHP script to upload images to a server	using(var wc = new WebClient())\n{\n    wc.UploadData("http://scriptlocation.html", "POST", data);\n}	0
23047428	23046309	Cant get geo location from address	foreach (Restaurant restaurant in allRestaurant)\n{\n     GeoCoordinate help;\n     GeocodeQuery query = new GeocodeQuery()\n     {\n         GeoCoordinate = new GeoCoordinate(),\n         SearchTerm = restaurant.address\n     };\n     TaskCompletionSource<Restaurant> task = new TaskCompletionSource<Restaurant>();\n     query.QueryCompleted += (s, ev) =>\n     {\n         foreach (var item in ev.Result)\n         {\n             help = item.GeoCoordinate;\n             task.TrySetResult(restaurant);\n         }\n         task.TrySetResult(null);\n     };\n     query.QueryAsync();\n     var rest = (await task.Task);\n     if (rest != null) \n         restaurants.Add(rest);\n }	0
6912024	6911155	How to regenerate grid data on various button click event of a page while we are using telerik grid with LinqDataSource	RadGrid.rebind();	0
19505352	19504830	Null value when retrieving value from combobox C#	public class Example\n{\n   public string Title {get; set;}\n   public int Value {get; set;}\n}	0
29405816	29405386	Foreach selected item in Listbox?	ArrayList controllersSelected = new ArrayList();\n\nforeach (var item in view.ListBox1.SelectedItems)\n    GetSelectedItem(item.Value, out controllersSelected);\n\n//Your logic to display selected forms simultaneously\nDisplaySimultaneousForms(controllersSelected);\n\nprivate void GetSelectedItem(formName, out ArrayList list)\n{\n  if (view.FormType == "Form1")\n    list.Add(new Form1_Controller());\n  else if (view.FormType == "Form2")\n    list.Add(new Form2_Controller());\n  else if (view.FormType == "Form3")\n    list.Add(new Form3_Controller());\n}	0
9202623	9198197	How To Insert Into DBF File (foxpro)	string CreateTableK = \n   "Create Table DSKKAR00 (DSK_ID c(10),DSK_KIND N(1),MON_PYM C(3))";     \n\nOleDbCommand cmdCreateTable = new OleDbCommand(CreateTableK, dbConnW);\ncmdCreateTable.ExecuteNonQuery();     \n\nstring MyInsert = \n   "insert into DSKKAR00 ( dsk_id, dsk_kind, mon_pym ) values ( ?, ?, ? )";\nOleDbCommand cmd3 = new OleDbCommand( MyInsert, dbConnW);\ncmd3.Parameters.AddWithValue( "parmSlot1", WorkRoomNo );\ncmd3.Parameters.AddWithValue( "parmSlot2", 1);\ncmd3.Parameters.AddWithValue( "parmSlot3", 'tst' ); // or whatever variable to put\ncmd3.ExecuteNonQuery();	0
12285570	12268147	Change Textboxcell to a Comboboxcell at run time	// Here I do this in the form constructor - there are other places you can do it\npublic Form1()\n{\n    InitializeComponent();\n\n    DataGridViewComboBoxColumn col = new DataGridViewComboBoxColumn();\n\n    // You need to set some properties on the column to make it work\n\n    // Datasource is the source (usually a list) of objects to show in the combobox\n    col.DataSource = dataSource;\n\n    col.DataPropertyName = "ColumnInGridDataSource";\n    col.DisplayMember = "DisplayProperty";\n    col.ValueMember = "ValueProperty";\n\n    dataGridView1.Columns.Add(col);\n\n    // This hides the textboxcolumn\n    dataGridView1.Columns["YourTextBoxColumnName"].Visible = false;\n}	0
26126857	26126408	Fill inputs and click login button with webrequest in C#	var request = new WebRequest(@"http:\\localhost\somePage.aspx");\nrequest.Credentials= CredentialCache.DefaultCredentials;\nrequest.Method = "Post";\nvar postString = "SomeTextBox=Foo&SomeOtherTextBox=Bar";\nvar byteData = Encoding.UTF8.GetBytes(postString);\nStream requestStream = request.GetRequestStream();\nrequestStream.Write(byteData, 0, byteData.Length);\nrequestStream.Close();	0
11125810	11120439	Updating multi level embedded mongo array	var query = new QueryDocument { { "Children._id", new ObjectId("4f979621682dbc1a8cefecaf") } };\nvar petDocuments = BsonDocumentWrapper.CreateMultiple(pets);\nvar petArray = new BsonArray(petDocuments);\nvar update = Update.Set("Children.$.Pets", petArray);\nparents.Update(query, update);	0
25184788	25184760	Cannot implicitly convert string[][] to string[] in C#	public static string[] SplitStrings(string inboundString, char splitChar)\n     {\n        if(inboundString.Contains(splitChar))\n        {\n            return inboundString.Split(splitChar);\n        }\n        else \n        {\n          return new string[] {};\n        }\n    }	0
21276961	21276637	i want to pass value from another datatable	DataRow tblvdrRow = tblvdr.NewRow();\n tblvdrRow["item_Vendorname"]= dttemp.Rows[0]["item_Vendorname"];\n tblvdr.Rows.Add(tblvdrRow);	0
2849501	2849455	Post "Hello World" to twitter from .NET application	var twitter = FluentTwitter.CreateRequest()   \n    .AuthenticateAs("USERNAME", "PASSWORD")   \n    .Statuses().Update("Hello World!")   \n    .AsJson();   \n\n    var response = twitter.Request();	0
13500711	13500334	Special queue with defined size	public class MyQueue<T>\n{\n    private Queue<T> queue;\n\n    public MyQueue(int capacity)\n    {\n        Capacity = capacity;\n        queue = new Queue<T>(capacity);\n    }\n\n    public int Capacity { get; private set; }\n\n    public int Count { get { return queue.Count; } }\n\n    public T Enqueue(T item)\n    {\n        queue.Enqueue(item);\n        if (queue.Count > Capacity)\n        {\n            return queue.Dequeue();\n        }\n        else\n        {\n            //if you want this to do something else, such as return the `peek` value\n            //modify as desired.\n            return default(T);\n        }\n    }\n\n    public T Peek()\n    {\n        return queue.Peek();\n    }\n}	0
15366923	15366804	How to persist session data, available to a business layer	Session["ActiveDepartment"] = 1	0
21365185	21365151	Prevent code replication with lambda functions when using out parameters	private delegate bool GenericTryParse<T>(TextBox txtBox, out T result);	0
6158227	6103765	Mapping data in a table to enumerated XSD or CLR object	get{ return context.Where(myVar => myVar.myKey == (int) myEnumVal);	0
13619514	13619291	Comparing enumeration flags (bit combinations) with linq	View | Edit | Create ( = 7)\nView | Edit          ( = 6)\nView | Create        ( = 5)\nView                 ( = 4)\nEdit | Create        ( = 3)\nEdit                 ( = 2)\nCreate               ( = 1)\nNone                 ( = 0)	0
4818853	4818824	C# events, how to raise them?	public void onHit()\n{\n   if(BallInPlay != null)\n     BallInPlay(this, new EventArgs());\n}	0
1284102	1275225	How to get VS10 Intellisense to complete suggested member on enter?	Console.WriteLine("....");	0
3857216	3857159	Enforcing implementation of events in derived abstract classes	protected void OnMyEvent(EventArgs e)\n{\n    // Note the copy to a local variable, so that we don't risk a\n    // NullReferenceException if another thread unsubscribes between the test and\n    // the invocation.\n    EventHandler handler = MyEvent;\n    if (handler != null)\n    {\n        handler(this, e);\n    }\n}	0
14893148	14893081	Instantiating a type-constrained generic class without subclassing it	var e = new Entity<Deriver>();	0
7936777	7936758	C++ architecture : how is it similar to machine architecture	operator=()	0
1982185	1982125	Is copying performed when capturing a value-type into a lambda?	private static void Foo()\n{\n    DisplayClass locals = new DisplayClass();\n    locals.someStruct = new SomeStruct { Num = 5 };\n    action = new Action(locals.b__1);\n}\nprivate sealed class DisplayClass\n{\n    // Fields\n    public SomeStruct someStruct;\n\n    // Methods\n    public void b__1()\n    {\n        Console.WriteLine(this.someStruct.Num);\n    }\n}	0
4511159	4510850	WCF UserNamePasswordValidator - Access credentials after validation	var userName = OperationContext.Current.ServiceSecurityContext.PrimaryIdentity.Name;	0
14507980	14507910	using Dictionary Key (as a string) to set variables in a constructor	public class Project\n{\n    public DateTime LastModified;\n    public string LoanName;\n    public string LoanNumber;\n    public int LoanProgram;\n    public string ProjectAddress;\n    ...\n\n    // Project class constructor\n    public Project(Dictionary<string, object> Dict)\n    {\n        foreach (KeyValuePair<string, object> entry in Dict)\n        {\n           this.GetType().GetProperty(entry.Key).SetValue(this, entr.Value, null);\n        }\n    }\n}	0
8644097	8639702	Constructing a fluent API method that accepts a method group	config.Transition().From(v1def, "ExitMethod").To(v2def, "EntryMethod");	0
6433097	6432960	Sending 2 controls values to a converter	private TimeSpan _time;\npublic TimeSpan Time \n{\n  get { return _time; }\n  set \n  { \n    _time = value; \n    RaisePropertyChanged("Time");\n  }\n}\n\nprivate int _minutes\npublic int Minutes\n{ \n  get { return _minutes; }\n  set \n  {\n    _minutes = value;\n    CalculateTimeSpan();\n    RaisePropertyChanged("Minutes");\n  }\n}\n\nprivate int _seconds\npublic int Seconds\n{ \n  get { return _seconds; }\n  set \n  {\n    _seconds= value;\n    CalculateTimeSpan();\n    RaisePropertyChanged("Seconds");\n  }\n}	0
17046297	17046254	If statement targetting string	_Menu1.SelectedIndex == 1	0
18080785	18080363	Is it possible to add Menu Items to a context menu during implementation?	TreeViewItem GreetingItem = new TreeViewItem()\n        {\n            Header = "Greetings",\n            ContextMenu = new ContextMenu //CONTEXT MENU\n            {\n                Background = Brushes.White,\n                BorderBrush = Brushes.Black,\n                BorderThickness = new Thickness(1),\n            }\n        };\n\n        MenuItem sayGoodMorningMenu = new MenuItem() { Header = "Say Good Morning" };\n        sayGoodMorningMenu.Click += (o, a) =>\n        {\n            MessageBox.Show("Good Morning");\n        };\n        MenuItem sayHelloMenu = new MenuItem() { Header = "Say Hello" };\n        sayHelloMenu.Click += (o, a) =>\n            {\n                MessageBox.Show("Hello");\n            };\n        GreetingItem.ContextMenu.Items.Add(sayHelloMenu);\n        GreetingItem.ContextMenu.Items.Add(sayGoodMorningMenu);\n        this.treeView.Items.Add(GreetingItem);	0
12416340	12416272	Why are variables that are declared in one case statement in scope for other cases?	public static void Main()\n{\n    var x = 2;\n    switch (x)\n    {\n        case 1: {  // notice these braces I added\n            var foo = "one";\n            Console.Out.WriteLine(foo);\n            break;\n        }\n        case 2:\n            foo = "two"; // hooray! foo is no longer in scope here\n            Console.Out.WriteLine(foo);\n            break;\n    }\n}	0
12062412	12062311	double number formatting	string value = ini.Read( "Form", "value" );\nthis.textcontrol.Text = String.Format("{0:0.00000}",  double.Parse(value));	0
24355749	24235004	How can I force send response stream?	return new Response\n{\n    StatusCode = HttpStatusCode.PartialContent,\n    ContentType = "audio/mp3",\n    Headers =\n    {\n        new KeyValuePair<string, string>("Accept-Ranges", "bytes"),\n        new KeyValuePair<string, string>("Content-Range", string.Format("bytes {0}-{1}/{2}", startPosition, endPosition , totalLength)),\n        new KeyValuePair<string, string>("Content-Length", outputBytes.Length.ToString(CultureInfo.InvariantCulture))\n    },\n    Contents = s =>\n    {\n        // I can write here multiple times thus sending multiple chunks\n        s.Write(outputBytes, 0, takeHowMuch);\n        s.Write(otherOutputBytes, 0, takeHowMuch);\n    }\n};	0
4605875	4593763	using return values from a c# .net made component build as com+	public object[] Read()    {      var retVal = new object[] {1,2,3};      return retVal;    }	0
15134994	15134864	Split String into jagged array looplessly	String s = "1:2,a;1:3,b;1:4";\n\nString[][][] f = s.Split(';').Select(t => t.Split(':').Select( e => e.Split(',') ).ToArray()).ToArray();	0
27975410	27974947	Animation based on a float value	using UnityEngine;\n using System.Collections;\n\n public class example : MonoBehaviour {\n     void Example() {\n         animation["Walk"].speed = 2;\n     }\n }	0
1836571	1836338	Saving Panel as an Image 	int width = plotPrinter.Size.Width;\n        int height = plotPrinter.Size.Height;\n\n        Bitmap bm = new Bitmap(width, height);\n        plotPrinter.DrawToBitmap(bm, new Rectangle(0, 0, width, height));\n\n        bm.Save(@"C:\TestDrawToBitmap.bmp", ImageFormat.Bmp);	0
6840846	6840808	How to sort a user Created List<UserClass> Collection in C#	list.Sort((a, b) => {\n                       if (a==null) return (b==null) ? 0 : -1;\n                       if (b==null) return 1;\n                       if (a.Property==null) return (b.Property==null) ? 0 : -1;\n                       return a.Property.CompareTo(b.Property);\n                     });	0
4276925	4276826	Special characters in Password are converting URL into a String	webbrowser.navigate("http://username:pww%40word@www.something.com")	0
5628877	5628858	Convert date c#	DateTime.ParseExact("20/01/2011 7:15:28 PM",\n                    "dd/MM/yyyy h:mm:ss tt",\n                    CultureInfo.InvariantCulture)\n        .ToString("yyyy-MM-dd HH:mm:ss")	0
21393955	21393914	Optional DateTime Web API	public class FooController : ApiController\n    {\n        [System.Web.Http.Route("live/topperformers/{dateTime:DateTime?}")]\n        [System.Web.Http.AcceptVerbs("GET", "POST")]\n        [System.Web.Http.HttpGet]\n        public List<string> GetTopPerformers(DateTime? dateTime = null)\n        {\n            return new List<string>();\n        }\n}	0
1497335	1497156	Passing a generic type (child of abstract class) to a func	(HtmlImage img) => img.Alt.Length == 0	0
4087106	4087036	How to only use Converter when input is valid	public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)\n{\n    string entry = (string)value;\n    Regex regex = new Regex(@"[0-9a-fA-F]{6}");\n    if (!regex.IsMatch(entry)) {\n        return Binding.DoNothing;\n\n    return entry.Substring(3); \n}	0
19979309	19979184	Late Binding to dll based on CPU architecture	System.Reflection.Assembly.LoadFile	0
15739083	15739022	how to create multi selection	DrawToBitmap()	0
26980590	26980562	Replace Quote with Unicode Symbol in Text	xml = xml.Replace(@"&quot;", @"\u0022");	0
29391886	29391817	Call method with assembly loaded from GAC	System.Drawing.Image	0
3291979	3291913	LINQ Select certain cell in DataGridView depending on other cell in row	IEnumerable<string> values = multiContactLookup.Rows.Cast<DataGridViewRow>()\n    .Where(row => (bool)row.Cells[0].Value)\n    .Select(row => (string)row.Cells[3].Value);	0
715227	715206	Show a message box from a class in c#?	using System.Windows.Forms;\n...\nMessageBox.Show("Hello World!");	0
13875608	13875432	dependency property to observable	// WhenAny now works on any object, will detect DependencyObject automatically\nobj.WhenAny(x => x.ActiveEditor, x => x.Value)\n   .Subscribe(/* ... */)	0
11104222	11103823	How can I return a ReadOnly object class with mutable properties while allowing write access	public interface IReadSecureSite\n{\n  IEnumerable<String> AccessHistory { get; }\n}\n\nclass Write_SecureSite : IReadSecureSite\n{\n    public IList<String> AccessHistoryList { get; private set; }\n\n    public Write_SecureSite()\n    {\n        AccessHistoryList = new List<string>();\n    }\n\n    public IEnumerable<String> AccessHistory {\n        get {\n            return AccessHistoryList;\n        }\n    }\n }\n\n public class Controller\n {\n    private Write_SecureSite sec= new Write_SecureSite();\n\n    public IReadSecureSite Login(string user)\n    {\n       return sec;\n     }\n\n }\n\n ...\n Controller ctrl = new Controller();\n IReadSecureSite read = ctrl.Login("me");\n foreach(string user in read.AccessHistory)\n {\n }	0
3167804	3167752	Is there a way to convert an observable collection to a List?	List<Person> personList= MySelectedPeople.ToList();	0
31600487	31593106	Launching a FilePicker or FolderPicker from a UICommand / MessageDialog	protected async override void OnNavigatedTo(NavigationEventArgs e)\n{\n    base.OnNavigatedTo(e);\n\n    var messageDialog = new MessageDialog("Please pick a folder where you'd like to store your documents", "Choose storage");\n    messageDialog.Commands.Clear();\n    UICommand okCommand = new UICommand("Ok");\n    messageDialog.Commands.Add(okCommand);\n    var cmd = await messageDialog.ShowAsync();\n    if (cmd == okCommand)\n    {\n        await PickFolder();\n    }\n}	0
22481258	22481230	pass C# string to C++ dll fails in Release build	[DllImport("pers.dll", CallingConvention = CallingConvention.Cdecl, CharSet = CharSet::Ansi)]\npublic static extern void AddSetting(string key, string value);	0
11811161	11807646	Get rows of a Telerik RadGrid	protected void btnLoad_Click(object sender, EventArgs e)\n{\n  rgCustomers.DataSource = odsCustomers;\n  rgCustomers.DataBind();\n  foreach (GridDataItem row in rgCustomers.Items)\n  {\n  }\n}	0
29604720	29601017	Programmicaly add route	var route = new MIB_IPFORWARDROW\n                {\n                    dwForwardDest = BitConverter.ToUInt32(IPAddress.Parse("XX.XX.XX.XX").GetAddressBytes(), 0),\n                    dwForwardMask = BitConverter.ToUInt32(IPAddress.Parse("255.255.255.255").GetAddressBytes(), 0),\n                    dwForwardNextHop = BitConverter.ToUInt32(IPAddress.Parse("XXX.XXX.XXX.XXX").GetAddressBytes(), 0),\n                    dwForwardMetric1 = 99,\n                    dwForwardType =  ForwardType.Indirect,\n                    dwForwardProto =  ForwardProtocol.NetMGMT,\n                    dwForwardAge = 0,\n                    dwForwardIfIndex = interfaceIndex\n                };\n    var ipForwardEntry = RouteInterop.CreateIpForwardEntry(ref route);	0
1012646	1012519	How do I InvokeMember in inherited class that is only implemented in base	BindingFlags.InvokeMethod | BindingFlags.Public\n | BindingFlags.Static | BindingFlags.FlatternHierarchy	0
25128184	25127955	How do I find a random color in C#	private static Random rand = new Random();\n\ncolor= Color.FromArgb(this.rand.Next(256), this.rand.Next(256), this.rand.Next(256));	0
22526238	22525668	Delete all in folder except the filename in list	public void DeleteFilesExcept(string directory,List<string> excludes)\n    {\n        var files = System.IO.Directory.GetFiles(directory).Where(x=>!excludes.Contains(System.IO.Path.GetFileName(x)));\n        foreach (var file in files)\n        {\n            System.IO.File.Delete(file);\n        }\n    }	0
4263720	4263471	Linq Query ToList not putting data into a list, but rather a one element list	var results = (from paymenttype in offer.Elements("paymentTypes").Elements()\n                       select paymenttype.Value).ToList();	0
33975320	33975256	Add listview items to a list of object in Entity Framework database	foreach (Dish item in lstViewOrder.Items)\n    {\n       or.Dishes.Add(item);   \n    }	0
11891875	11888941	Unable to send JSON to ASMX as anything other than Dictionary<>	500 Internal Server Error	0
17071760	17047278	Generating report from rdlc xml string	private void Page_Load(object sender, System.EventArgs e)\n{\n    NMBS.ViewModels.ViewModelReport Report = (Session["CurrentReport"] as NMBS.ViewModels.ViewModelReport);\nReportViewer.ProcessingMode = ProcessingMode.Local;\nReportViewer.PageCountMode = PageCountMode.Actual;\n\n// Set report specifics.\nReportViewer.LocalReport.DisplayName = Report.Name;\nReportViewer.LocalReport.LoadReportDefinition(new System.IO.StringReader(Report.Definition));\nforeach (ReportParameter Param in Report.Parameters)\n{\n    ReportViewer.LocalReport.SetParameters(Param);\n}\nforeach (ReportDataSource Rds in Report.Data)\n{\n    //Load Report Data.\n    ReportViewer.LocalReport.DataSources.Add(Rds);\n}\nReportViewer.CurrentPage = Report.CurrentPage;\nReportViewer.Width = Report.Width;\n\n// Refresh the reports.\nReportViewer.LocalReport.Refresh();\n}	0
31294078	31293960	C# reading an xml file, node value returns as blank	countryname = countryNode.InnerText;	0
8472771	8472740	Calling a Stored Procedure every n seconds	Timer myTimer = new Timer(500);\ntimer1.Interval = 5000;\ntimer1.Enabled = true;\ntimer1.Tick += new System.EventHandler (OnTimerEvent);\n\nWrite the event handler\n\nThis event will be executed after every 5 secs.\n\npublic static void OnTimerEvent(object source, EventArgs e)\n{\nm_streamWriter.WriteLine("{0} {1}", DateTime.Now.ToLongTimeString(),DateTime.Now.ToLongDateString());\nm_streamWriter.Flush();\n}	0
1356013	1355978	How can i add embedded resources to dll during build process	al.exe MyLib.module /out:MyLib.dll /embed:MyRes.txt	0
13230905	13230439	Efficient data structure for associating data with filesystem paths?	(letter, child node)	0
20002315	20001863	WPF MVVM with EF CodeFirst	using ( var ctx = new JanathaPosDbContext() )\n{\n    // access the data \n    var roles = ctx.UserRoles.ToList();         \n\n    // or force the initialization\n    ctx.Database.Initialize( true );\n}	0
7773475	7757881	C# Download Text to Speech from Google Translate comes with problems	using System.Net;\nusing System.Text;\nusing System.Web;\n\nclass Program\n{\n    static void Main()\n    {\n        var text = "Teste de cria??o no ficheiro";\n        var url = "http://translate.google.com/translate_tts?tl=pt&q=";\n        url += HttpUtility.UrlEncode(text, Encoding.GetEncoding("utf-8"));\n        using (var client = new WebClient())\n        {\n            client.Headers[HttpRequestHeader.UserAgent] = "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:7.0.1) Gecko/20100101 Firefox/7.0.1";\n            client.DownloadFile(url, "mp3CriationTest.mp3");\n        }\n    }\n}	0
19809235	19808948	how to fill C# Fill rectangle From bottom to top?	System.Drawing.Drawing2D.LinearGradientBrush linGrBrush = \n         new System.Drawing.Drawing2D.LinearGradientBrush(\n               new Point(0, 1),\n               new Point(0,0),\n               Color.FromArgb(0, 0, 0, 0),\n               Color.FromArgb(255, 190, 0, 0));	0
5145700	5145682	Is there a construct similar to a lock in C# that skips over a block of code rather than blocking?	Monitor.TryEnter	0
25838100	25837725	Converting Nhibernate Object to JSON	using (var session = NHibernateHelper.OpenSession())\n{\n  Feed feed = new Feed();\n\n  Tag tag = Tag.READ.ById(8);\n  feed.Tag.Add(tag);\n  feed.Language = ENLanguage.EN;\n  feed.Name = "Foo";\n\n  feed.Save();\n\n  string x = JsonConvert.SerializeObject(feed);\n}	0
7906182	7905990	How to infer a type in a base class dependant on the inheriting class at runtime without if statements?	abstract class MyAbstractClass{\n\n    MyHelperClassBase myHelper;\n\n    protected void foo() {\n        myHelper = createHelper();\n    }\n\n    protected abstract MyHelperClassBase createHelper();\n}\n\nclass MySubClass : MyAbstractClass{\n    protected override MyHelperClassBase createHelper(){\n        return new MyHelperSubClass();\n    }\n}\n\nclass MyOtherSubClass : MyAbstractClass{\n    protected override MyHelperClassBase createHelper(){\n        return new MyOtherHelperSubClass();\n    }\n}	0
21007359	21007327	Access objects in a list, perform a foreach using their properties with F#	mylist |> Seq.iter (fun x -> g.FillRectangle(Brushes.Black,x.x,x.y,...))	0
11732958	11722721	Copy and Paste from excel to windows form	Range("A1").Select\nActiveCell.FormulaR1C1 = "abc"\nRange("A2").Select\nActiveCell.FormulaR1C1 = "def"\nRange("A3").Select\nActiveCell.FormulaR1C1 = "hij"\nRange("A4").Select\nActiveCell.FormulaR1C1 = "klm"\nRange("A4,A1").Select    'It actually concatenates the cells you've selected, that info isn't ion the clipboard, if I selected three cells in the column it would be Range("A4,A1,A2").Select\nRange("A1").Activate\nSelection.Copy  \n\n'Range("B1").Select\n'ActiveSheet.Paste   'when I paste onto new cells only two rows are taken up	0
3547911	3547857	how to embed an xml file to a resource file	string resourceName = "Namespace.Prefix.FileName.xml";\nAssembly someAssembly = LoadYourAssemblyContainingTheResource();\nXmlDocument xml = new XmlDocument();\nusing (Stream resourceStream = someAssembly.GetManifestResourceStream(resourceName))\n{\n    xml.Load(resourceStream);\n}\n// The embedded XML resource is now available in: xml	0
23482728	23482681	Combine 2 textbox contents with delimiter	string left = string.Format("Win{0}Lose{0}Hello{0}Goodbye", Environment.NewLine);\nstring right = string.Format("One{0}Two{0}Three{0}Four", Environment.NewLine);\nstring[] leftSplit = left.Split(new[] { Environment.NewLine }, StringSplitOptions.None);\nstring[] rightSplit = right.Split(new[] { Environment.NewLine }, StringSplitOptions.None);\n\nstring output = "";\nif (leftSplit.Length == rightSplit.Length)\n{\n    for (int i = 0; i < leftSplit.Length; i++)\n    {\n        output += leftSplit[i] + ":" + rightSplit[i] + Environment.NewLine;\n    }\n}	0
21145512	21144525	In Mef, can a part of a dependent assembly be null?	[ImportingConstructor]\npublic ExportContainer([Import(AllowDefault=true)]IService service)\n{\n     this.service= service;\n}	0
23419908	23208974	How to use DotNetOpenAuth.AspNet to provide social login while i'm using MVC3	if (provider == Provider.Yahoo)\n        {\n            DotNetOpenAuth.AspNet.AuthenticationResult result;\n            var YahooClient = new YahooClient(clientId: clients[provider].AppID, clientSecret: clients[provider].AppSecret);\n            var context = HttpContext.Current;\n\n            //the second time\n            if (!String.IsNullOrEmpty(context.Request.QueryString.ToString()) && (context.Request.QueryString.ToString().Contains("code")))\n            {\n                result = YahooClient.VerifyAuthentication(new HttpContextWrapper(context), new Uri(returnUrl));\n                if (result.IsSuccessful)\n                {\n                    //Success;\n                }\n            }\n            //the first time\n            else\n            {\n                OAuthWebSecurity.RegisterClient(YahooClient, "yahoo");\n                OAuthWebSecurity.RequestAuthentication("yahoo");\n            }\n        }	0
24079000	24078657	c# code to get Selected query result in a array	if (connection.State == ConnectionState.Closed)\n{\n     connection.Open();\n}	0
30510426	30503393	Troubles setting SentOn Outlook MailItem property with PropertyAccessor.SetProperty method	set Session = CreateObject("Redemption.RDOSession")\n  Session.MAPIOBJECT = Application.Session.MAPIOBJECT\n  set Msg = Session.GetDefaultFolder(olFolderInbox).Items.Add\n  Msg.Sent = true\n  Msg.Import "C:\temp\test.eml", 1024\n  Msg.Save	0
13526102	13526015	Outlook add-in reloading	Connect = false	0
13732524	13731139	C# accessing static members of T	class Program\n{\n    static void Main(string[] args)\n    {\n        PlaceRoom<Room>();\n        Console.ReadKey(true);\n    }\n\n    public static void PlaceRoom<T>()\n        where T : Room\n    {\n        string name = ((NameAttribute)typeof(T).GetCustomAttributes(false).First(x => x is NameAttribute)).Name;\n\n        Console.WriteLine(name);\n    }\n}\n\n[Name("Room")]\npublic class Room\n{\n}\n\n[Name("Bedroom")]\npublic class Bedroom : Room\n{\n}\n\n[AttributeUsage(AttributeTargets.Class, Inherited = false)]\npublic class NameAttribute : Attribute\n{\n    public string Name { get; set; }\n\n    public NameAttribute(string name)\n    {\n        Name = name;\n    }\n}	0
2304703	2294411	How do I get PNG with transparency into GDI32 (in c#) to use it with alphaBlend?	using (Bitmap tBMP = new Bitmap(@"myBitmap.png"))\n        {\n            BMPObject = tBMP.GetHbitmap(Color.Black);\n            sz = tBMP.Size;\n        }	0
17363762	17363278	How do I trigger a jQuery function with a c# Calendar SelectedDateChange?	ScriptManager.RegisterStartupScript(this, this.GetType(), this.ClientID, "JavaScriptmethod()", true);	0
6277927	6277822	send multiple mail with image attachements	StreamReader strm_rdr = new StreamReader(theme);\nstring theme_text = strm_rdr.ReadToEnd();\nstrm_rdr.Close();	0
21580625	21579719	How to send elements of array as separate lines in email message in asp.net with C#	string[] arr = { "one", "two", "three" };\nstring messageBody = string.Join("<br/>", arr);	0
30041487	30040281	Send the user to my other apps, Windows Phone button	MarketplaceSearchTask marketplaceSearchTask = new MarketplaceSearchTask(); \nmarketplaceSearchTask.SearchTerms = "developer-username"; \nmarketplaceSearchTask.Show();	0
731728	730860	How do I loop through all layers of Treeview nodes?	protected void ColorNodes(TreeNode root, Color firstColor, Color secondColor)\n{\n   Color nextColor;\n   foreach (TreeNode childNode in root.Nodes)\n   {     \n      nextColor = childNode.ForeColor = childNode.Index % 2 == 0 ? firstColor : secondColor;\n\n      if (childNode.Nodes.Count > 0)\n      {\n         // alternate colors for the next node\n         if (nextColor == firstColor)\n              ColorNodes(childNode, secondColor, firstColor);\n         else\n              ColorNodes(childNode, firstColor, secondColor);\n      }\n   }\n}\n\n  private void frmCaseNotes_Load(object sender, System.EventArgs e)\n    {\n       foreach (TreeNode rootNode in treeView1.Nodes)\n       {\n          ColorNodes(rootNode, Color.Goldenrod, Color.DodgerBlue);\n       }\n    }	0
24388632	24388288	Parse JSON Array using Newtonsoft	RootObject ro = JsonConvert.DeserializeObject<RootObject>(strResult);\n\nforeach(var item in ro.showAttendanceResult)\n{\n    string _name= item.lec_no;\n}	0
25041763	25041703	Write a method for a generic type that is required to implement an interface	public void SomeMethod<T>(ref T para1)\n    where T : ITest\n{\n    // ...\n}	0
22429517	22429456	How to close a Data Reader	foreach (var store in db.Stores.ToList())\n    {\n        var productsInStore = store.Products.ToList();\n    }	0
876539	876534	Setting Date format yyyyMMdd through specify Culture Name	string s = DateTime.Today.ToString("yyyyMMdd");	0
27491794	27491762	Creating a plan repository, but using keyword in constructor body	planInfo = db.Plans.Where(d => d.PatientId == _patientId).ToList();	0
3182389	3182145	How can i validate this attribute(annonation)?	class Program\n{\n    static void Main(string[] args)\n    { \n        var invalidPerson = new Person { Name = "Very long name" };\n        var validPerson = new Person { Name = "1" };\n\n        var validator = new Validator<Person>();\n\n        Console.WriteLine(validator.Validate(validPerson).Count);\n        Console.WriteLine(validator.Validate(invalidPerson).Count);\n\n        Console.ReadLine();\n    }\n}\n\npublic class Person\n{\n    [StringLength(8, ErrorMessage = "Please less then 8 character")]\n    public string Name { get; set; }\n}\n\npublic class Validator<T> \n{\n    public IList<ValidationResult> Validate(T entity)\n    {\n        var validationResults = new List<ValidationResult>();\n        var validationContext = new ValidationContext(entity, null, null);\n        Validator.TryValidateObject(entity, validationContext, validationResults, true);\n        return validationResults;\n    }\n}	0
141816	138449	How to convert a Unicode character to its ASCII equivalent	byte[] bytes = Encoding.GetEncoding(437).GetBytes("?");	0
25737150	25736982	how to set combobox text to bet trimmed while retrieving from database in c#	dt.Load(dtr);\nforeach (DataRow row in dt.Rows)\n{\n    var name = (string)row["employee_name"];\n    row["employee_name"] = name.Trim();\n}\ncomboBox1.DisplayMember = "employee_id";\ncomboBox1.DisplayMember = "employee_name";\ncomboBox1.DataSource = dt;	0
1792156	1792129	Multithreaded access to the WPF GUI in C#	if(textbox.Dispatcher.CheckAccess())\n{\n   // The calling thread owns the dispatcher, and hence the UI element\n   textbox.AppendText(...);\n}\nelse\n{\n   // Invokation required\n   textbox.Dispatcher.Invoke(DispatcherPriority.Normal, [delegate goes here]);\n}	0
11629548	11629473	how to show only the last four digit of a credit card number	var card_number = "1234384234034";\nvar reason = "some reason";\nvar s = "Received returned card ending in {0} due to {1} will dispose off after 45 days";\nvar text = String.Format(s, card_number.Substring(card_number.Length-4), reason);	0
29368412	29360693	How to map Entities when [One to Two] Relationship is required?	class Address { \n  // Properties \n}\nclass Account\n{\n  //Other Properties\n  Public int PermanentAddressId {get;set;}\n  Public int CurrentAddressId {get;set;}\n  Public Address Permanent { get; set; }\n  Public Address Current { get; set; }\n}\nclass Other\n{\n  //Other Properties\n  Public int OtherAddressId {get;set;}\n  Public Address OtherAddress { get; set; }\n}\n\nclass AccountMapping : EntityTypeConfiguration<Account>\n{\n  Public AccountMapping()\n  {\n    ToTable("Account");\n    //Others like HasKey\n    HasRequired(a=>a.ParmanentAddress).WithMany().HasForeignKey(p=>p.PermanentAddressId);\n    HasRequired(a=>a.CurrentAddress).WithMany().HasForeignKey(p=>p.CurrentAddressId);\n  }\n}\nclass OtherMapping : EntityTypeConfiguration<Other>\n{\n   public OtherMapping()\n   {\n     HasRequired(a=>a.OtherAddress).WithMany().HasForeignKey(p=>p.OtherAddressId);\n   }\n}	0
20244809	20244544	How to correctly format 'data' for HighChart	var str = "[1,2,3,4,5,6,7]";\n\nvar trim = str.replace(/[\[\]]/g, "");\n\nvar data = trim.split(",");\n\ndata = data.map(function (d) {\n    return +d;\n});\n\nconsole.log(data);	0
18320695	18320394	Send just specified properties from a model to the view	public class UserViewModel\n{\n    public int Id { get; set; }\n\n    [Required]\n    public string Email { get; set; }\n\n    [Required]\n    public string Password { get; set; }\n}	0
24761370	24722751	Custom Attribute client side Validation inside Collection	//dirty way\nvar rule = new ModelClientValidationRule\n{\n    ValidationType = "dynamicrange",\n    ErrorMessage = this.ErrorMessage,\n};\nstring Prefix = ((System.Web.Mvc.ViewContext)(context)).ViewData.TemplateInfo.HtmlFieldPrefix;\nPrefix = Prefix.Replace(metadata.PropertyName, "");\nSystem.Text.RegularExpressions.Regex Regex = new System.Text.RegularExpressions.Regex("[^a-zA-Z0-9 -]");\nPrefix = Regex.Replace(Prefix, "_");\nrule.ValidationParameters["minvalueproperty"] = Prefix + _minPropertyName;\nrule.ValidationParameters["maxvalueproperty"] = Prefix + _maxPropertyName;\nyield return rule;	0
18628383	18599851	MySQLBulkLoader not inserting any row in mysql db	string sql = @"load data infile 'E:/a1.csv' ignore into table tblspmaster fields terminated by '' enclosed by '' lines terminated by '\n' IGNORE 1 LINES (sp)";\n MySqlCommand cmd = new MySqlCommand(sql, mycon); \ncmd.CommandTimeout = 5000000; \ncmd.ExecuteNonQuery();	0
11136455	11135743	How do I detect when the content of a WebBrowser control has changed (in design mode)?	string lastSaved;\n\nprivate void Form_Load(object sender, System.EventArgs e)\n{\n   // Load the form then save WebBrowser text\n   this.lastSaved = this.webBrowser1.DocumentText;\n}\n\nprivate void webBrowser1_KeyDown(object sender, System.Windows.Forms.KeyEventArgs e)\n{\n    // Check if it changed\n    if (this.lastSaved != this.webBrowser1.DocumentText)\n    {\n        // TODO: changed, enable save button\n        this.lastSaved = this.webBrowser1.DocumentText;\n    }\n}\n\nprivate void webBrowser1_Navigating(object sender, WebBrowserNavigatingEventArgs e)\n{\n    // Check if it changed\n    if (this.lastSaved != this.webBrowser1.DocumentText)\n    {\n        // TODO: ask user if he wants to save\n        // You can set e.Cancel = true to cancel loading the next page\n    }\n}	0
7024982	7024945	How can I check if a string contains another string in C#	a.IndexOf('*') >= 0 && a.IndexOf('*') < 20	0
4464415	4464088	Changing the underlying model that ModelState is validating against	var isOriginalModelValid = this.TryValidateModel(updated);	0
26944399	26940802	Copy file from app installation folder to Local storage	private async void TransferToStorage()\n    {\n        // Has the file been copied already?\n        try\n        {\n            await ApplicationData.Current.LocalFolder.GetFileAsync("localfile.xml");\n            // No exception means it exists\n            return;\n        }\n        catch (System.IO.FileNotFoundException)\n        {\n            // The file obviously doesn't exist\n\n        }\n        // Cant await inside catch, but this works anyway\n        StorageFile stopfile = await StorageFile.GetFileFromApplicationUriAsync(new Uri("ms-appx:///installfile.xml"));\n        await stopfile.CopyAsync(ApplicationData.Current.LocalFolder);\n    }	0
24604748	24526638	Button click works randomly asp.net	void Application_BeginRequest(object sender, EventArgs e)\n{\n    var app = (HttpApplication)sender;\n    if (app.Context.Request.Url.LocalPath.EndsWith("/"))\n    {\n    app.Context.RewritePath(\n             string.Concat(app.Context.Request.Url.LocalPath, "default.aspx"));\n    }\n}	0
27875379	27874353	How to show a gif frame?	frames[0] = new Bitmap(GG);\npictureBox1.Image = frame[0];	0
18388442	18388362	Xamarin - Collapse text	Preferences > Text Editor > General > Enable code folding	0
4207492	4207455	Get values from LINQ query	public SomeClass GetData()\n{\n       var table = GetDataTable();\n       var view = table.DefaultView;\n       //..... more code\n       var query = from row in view.ToTable().AsEnumerable()\n                    group row by row.Field<string>("ShortName") into grouping\n                    select new SomeClass\n                        {\n                            ShortName = grouping.Key,\n                            SCount = grouping.Sum( count => count.Field<int>("ProfCount")),\n                            DisplayText = string.Empty\n                        };\n        return query;\n}\n\n// this code doesn't work\npublic void DoIt()\n{\n  var result = GetData();\n  string shortName = result.ShortName;\n}\n\npublic class SomeClass\n{\n    public string ShortName { get; set; }\n    public int SCount { get; set; }\n    public string DisplayText { get; set; }\n}	0
4365103	4364893	how to specify xml element having a xml attribute	[XmlRoot]\npublic class Header\n{\n    [XmlElement]\n    public Version Version { get; set; }\n}\n\npublic class Version\n{\n    [XmlAttribute("environment")]\n    public String Environment { get; set; }\n\n    [XmlText]\n    public String Value { get; set; }\n}	0
10191698	10191364	How to delete a node if it has no parent node	if (node.InnerHtml == String.Empty) {\n    HtmlNode parent = node.ParentNode;\n    if (parent == null) {\n        parent = doc.DocumentNode;\n    }\n    parent.RemoveChild(node);\n}	0
20879880	20841710	How to remove a dynamically created button in gridview	for (int i = dgvBG.Columns.Count - 1; i >= 0; i--)\n{\n    var col = dgvBG.Columns[i];\n\n    if (col.HeaderText == "Edit" || col.HeaderText == "Delete" )\n    {\n        dgvBG.Columns.Remove(col);\n        // col.Visible = false;\n    }\n}	0
4582943	4582912	Get _id of an inserted document in MongoDB?	[BsonId]\npublic ObjectId ID{get;set;}	0
24051105	24024327	Google Drive API invalid_grant after removing access	DeleteAsync()	0
284462	277817	Compile a version agnostic DLL in .NET	using System.Reflection;\n\nstatic Program()\n{\n    AppDomain.CurrentDomain.AssemblyResolve += delegate(object sender, ResolveEventArgs e)\n    {\n        AssemblyName requestedName = new AssemblyName(e.Name);\n\n        if (requestedName.Name == "Office11Wrapper")\n        {\n            // Put code here to load whatever version of the assembly you actually have\n\n            return Assembly.LoadFile("Office11Wrapper.DLL");\n        }\n        else\n        {\n            return null;\n        }\n    }\n}	0
32719252	32719110	C# Extract Words Beginning with %! and Ending With !%	var reg = new Regex(@"%!(?<word>\w+)!%");\nvar inStr = @"You don't want no %!beef!%, boy\nKnow I run the streets, boy\nBetter follow me towards\nDowntown\nWhat you see is what you get %!girl!%\nDon't ever forget girl\nAin't seen nothing yet until you're\n%!Downtown!%";\nvar results = reg.Matches(inStr).Cast<Match>().Select(m => m.Groups["word"].Value);	0
14476861	14476744	Get All node name in xml in silverlight	foreach (XElement child in doc.Root.DescendantsAndSelf())\n{\n    Console.WriteLine(child.Name.LocalName);\n}	0
12420823	12420790	How I can set the AutoCompleteList of ten elements?	filteredList.Take(10).ToArray(typeof(string));	0
14061192	14061130	Changing ToString value for checkedListBox	public string Description(){\n    return this.ToString();\n}\n\nprotected override ToString(){\n    /// and here goes the code you need.\n}	0
11490076	11489829	Fetching data from SQL Server 2005 using c#	private void button1_Click(object sender, EventArgs e)\n    {\n        using (SqlConnection con = new SqlConnection("Data source=.;initial catalog=loki;integrated security=true"))\n        {\n            string query = "select  price from metro where source= @Source and destination = @Destination";\n\n            using (SqlCommand cmd = new SqlCommand(query, con))\n            {\n                cmd.Parameters.AddWithValue("@Source", textBox1.Text);\n                cmd.Parameters.AddWithValue("@Destination", textBox2.Text);\n\n                con.Open();\n                object o  = cmd.ExecuteScalar();\n                if(o != null && o != DBNull.Value)\n                {\n                   string price = (string) o; //please cast the return type as required\n                   textBox3.Text = price;\n                }\n                con.Close();\n            }\n        }\n    }	0
22639837	22639653	How do a serialize a member of a .net Object	public class Job{\n     [XmlIgnore]\n     System.Diagnostics.Process process;\n\n     public ProcessFileName\n     {\n         get {return process.StartInfo.FileName;}\n         set { process = Process.Start(value); }\n     }\n }	0
5210128	5210069	Sort big quantity of strings with same lengths	open input file (r)\nfor i in ['aa', 'ab', 'ac', ..., 'zz']:\n    open output file[i] (w)\nfor record in input file:\n    write record to output file[record[0:2]]\nclose all files\nopen main output file (w)\nfor i in ['aa', 'ab', 'ac', ..., 'zz']:\n    open input file[i] (r)\n    slurp whole file into memory\n    close input file\n    sort data\n    append whole sorted file to main output file	0
6170528	6170427	How to use Control.Dispatcher.BeginInvoke to modify GUI	msg = string.Format("Processing {0} on thread {1}", filename,\n            Thread.CurrentThread.ManagedThreadId);\n this.BeginInvoke( (Action) delegate ()\n    {\n        this.Text = msg;\n    });	0
17675333	17675253	Trim whitespace from all DataSet fields	foreach (DataTable dt in ds.Tables)\n            {\n                foreach (DataRow dr in dt.Rows)\n                {\n                    foreach (DataColumn col in dt.Columns)\n                    {\n                        if (col.ColumnName == "colName"))\n                        {\n                            dr[col] = dr[col].ToString().Replace(" ", "");\n                        }\n                        else if (col.DataType == typeof(System.String))\n                        {\n                            dr[col] = dr[col].ToString().Trim();\n                        }\n                    }\n                }\n            }	0
12699591	12699273	Formatting TimeSpan in different cultures	using System;\nusing System.Globalization;\n\nclass Program {\n    static void Main(string[] args) {\n        var ci = CultureInfo.GetCultureInfo("ml-IN");\n        System.Threading.Thread.CurrentThread.CurrentCulture = ci;\n        var ts = new TimeSpan(0, 2, 9);\n        var dt = new DateTime(Math.Abs(ts.Ticks));\n        Console.WriteLine(dt.ToString("HH:mm:ss"));\n        Console.ReadLine();\n    }\n}	0
32707013	32705494	Need help extracting information out of a string	// Input string\n    string input = "{2,(IDT High Definition Audio CODEC,IDT),(High Definition Audio Device,Microsoft)}";\n\n    // Remove the last }\n    input = input.Remove(input.Length - 1);\n\n    // Remove from the begining to the first (\n    input = input.Substring(input.IndexOf('('));\n\n    // Remove the first and the last characters\n    input = input.Remove(0, 1);\n    input = input.Remove(input.Length - 1);\n\n    // At this point, the input value is\n    // "IDT High Definition Audio CODEC,IDT),(High Definition Audio Device,Microsoft"\n\n    // Split it, using "),(" as separators\n    string[] data = input.Split(new[] { "),(" }, StringSplitOptions.RemoveEmptyEntries);\n\n    // Now, what you want is in data\n    foreach (var s in data)\n    {\n        Console.WriteLine(s);\n    }	0
3236406	3236279	Calculate to sum of 2^1000 without using BigInt	digits = [1]\nfor n in range(1000):\n    newdigits = []\n    carry = 0\n    for digit in digits:\n        s = 2*digit+carry\n        carry = s/10\n        s = s%10\n        newdigits.append(s)\n    if carry:\n        newdigits.append(carry)\n    digits = newdigits\nprint "".join(map(str,reversed(digits)))	0
3485056	3484650	What API function do I need to use to know if a window is being shown in the taskbar?	if style & WS_VISIBLE \n{\n  if ( ( exstyle & WS_EX_APPWINDOW ) \n  or ( !HasOwnerWindow() and !(exstyle & WS_EX_TOOLWINDOW) ) \n  {\n        ShowWindowInYourTaskBar()\n  }\n}	0
466915	466909	Is there a way to convert an IEnumerable into a collection of XElements?	XElement Configuration = new XElement("Collection",\n      collection.Select(c=>new XElement("Element", c)));	0
22353100	22346153	Create overload for generic extension method	public static QueryMapper<TSource> Map<TSource>(this IOrderedQueryable<TSource> source) \n{\n   return new QueryMapper<TSource>(source); \n}	0
23354155	23353407	How do I calculate a value from a string in C# when taking data out of a list box?	var subTotal = ReceiptBox.Items.Cast<Hardware>().Sum(item => item.Price);	0
13565854	13565676	RegEx C# get substring of 12 characters which contains at least one digit AND letter	String testString = "Some text F4LE8AWMF87E and again some text";\nMatch myMatch = Regex.Match(testString, @"\b(?=[a-zA-Z]*[0-9])(?=[0-9]*[a-zA-Z])[0-9a-zA-Z]{12,}\b");\nmyLabel.Text = myMatch.Value;	0
11664890	11662480	Handling background based per pixel collision with different screen resolutions and image stretching	Xc= Wbk * (Xs-Xvp)/Wvp;\n   Yc= Hbk * (Ys-Yvp)/Hvp;	0
22769250	22596646	FlowDocument alternative in wp8 or Hyperlinks and Run on same line	Paragraph p = new Paragraph();\np.Inlines.Add("Plase visit ");\nvar link = new Hyperlink();\nlink.Inlines.Add("google.com ");\np.Inlines.Add(link);\np.Inlines.Add("to continue");\nrtb.Blocks.Add(p);	0
9608970	9608836	How to format c# object to display category and subcategory in json body?	public class Widget{\n    public string Address{get; set;}\n    public string City{get; set;}\n    //other properties\n    public Category Category {get; set;}\n}\n\npublic class Subcategory{\n   public int Id{get; set;}\n   public string Name {get; set;}\n}\npublic class Category{\n    public int Id{get; set;}\n    public string Name {get; set;}\n    public List<Subcategory> Subcategory {get; set;}\n}	0
10667228	10665747	retrieve value of properties in jsonobject which is also prpoerties of jsonobject	var jss = new JavaScriptSerializer();\n        var ob = jss.Deserialize<Dictionary<string, object>>(\n                "{\"id\":\"100001867845514\",\"name\":\"ucef nahs\",\"location\": {\"id\":\"100245266683893\",\"name\":\"settat, Casablanca, Morocco\"}, \"picture\":\"http://profile.ak.fbcdn.net/hprofile-ak-snc4/49453_100001867845514_620239062_q.jpg\"}");\n        var location = ob.FirstOrDefault(friend => friend.Key == "location").Value as IDictionary<string, object>;\n        if (location != null)\n        {\n            var locationName = location.FirstOrDefault(elem => elem.Key == "name").Value;\n            Console.WriteLine(locationName);\n            Console.ReadLine();\n        }	0
29738506	29738201	How to make a object delete itself from a list.	public class MyObject\n{\n    public void RemoveFromList(List<MyObject> list)\n    {\n        if (list == null)\n            return;\n\n        list.Remove(this);\n    }\n}	0
32834677	32834494	How can I force load a proxy object in NHibernate?	var queryOver = session.QueryOver<Parent>()\n               .Select(p => p.Name))\n               .List<string>()	0
2803782	2803767	How to get row by one column faster in C#?	DataRows row = MyDataTable.Select("Value = 7")[0];\nstring name = (string)row["name"];	0
24711657	24711415	Windows Phone - Increment a value	DispatcherTimer tmr;\nint test;\nprotected override void OnNavigatedTo(NavigationEventArgs e)\n{\n    base.OnNavigatedTo(e);\n    string QueryStr = "";\n    NavigationContext.QueryString.TryGetValue("myNumber", out QueryStr);\n    test = (int.Parse(QueryStr));\n    LoadTimer();\n}\n\npublic void LoadTimer()\n{\n    tmr = new DispatcherTimer();\n    Deployment.Current.Dispatcher.BeginInvoke(() =>\n    {\n        tmr.Interval = new TimeSpan(0, 0, 1);\n        tmr.Tick += tmr_Tick;\n        tmr.Start();\n    });\n}\n\nvoid tmr_Tick(object sender, EventArgs e)\n{\n    test++;\n    TextBlock.Text = test.ToString();\n}	0
7660220	7660075	Retrieve XAML from programmatically created UserControl at runtime	XamlWriter.Save()	0
5758322	5757799	Casting from Decimal to Float	decimal FirstYr = decimal.Round((first / second), 5)*100;\n ev.HiComm = (double)FirstYr ;	0
20117323	20117221	How to Take Top 10 Distinct Rows order by Date	DataTable recentTen = recent_index.AsEnumerable()\n    .OrderByDescending(r => r.Field<DateTime>("Date"))\n    .GroupBy(r => r.Field<string>("JID"))\n    .Take(10)\n    .Select(g => g.First())\n    .CopyToDataTable();	0
34094073	34093743	Print from SqlDataReader urls	HyperLink VideoLink = new HyperLink();\nVideoLink.NavigateUrl = video;\nVideoLink.Text = "Click Me!";	0
26088713	26087806	How to correctly set up a 'ContextMenu' in a ListView for Windows Phone 8.1?	private void EditButton_Click(object sender, RoutedEventArgs e)\n{\n    var datacontext = (e.OriginalSource as FrameworkElement).DataContext;\n\n    //this datacontext is probably some object of some type T (whatever is in your Items collections you haven't specified in your question)\n}	0
4984649	4984560	Changing ForeColor of a Textblock in Silverlight4 according to a value	public class BrushColorConverter : IValueConverter\n  {\n\n    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)\n    {\n        return ((int)value >= 0) ? new SolidColorBrush(Colors.White) : new SolidColorBrush(Colors.Red);\n    }\n\n    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)\n    {\n        throw new NotImplementedException();\n    }\n  }	0
19354622	19354551	how to find and extract text from webpage in c#	HtmlDocument doc = new HtmlDocument();\ndoc.Load(yourStream);\nvar nameElement= doc.DocumentNode.SelectSingleNode("//li[@id='hello1']").InnerText;\n//name would contain `about me name: john`\nRegex.Match(nameElement,@"(?<=name:\s*)\w+").Value;//john	0
9845364	9844949	Reorder a master list with multiple sub lists	var A = new List<string> { "Beef", "Ham", "Chicken" };\nvar B = new List<string> { "Cat", "Monkey", "Dog" };\nvar C = new List<string> { "Veal", "Ham", "Beef", "Chicken", "Deer", "Dog", "Cat", "Monkey" };\n\n// To quickly check if C[i] belongs to the corresponding list.\nvar sA = new HashSet<string>(A);\nvar sB = new HashSet<string>(B);\nList<string> currentList = null;\nint pos = 1;\nfor (int i = 0; i < C.Count; i++)\n{\n    string el = C[i];\n    if (currentList != null)\n    {\n        if (pos == currentList.Count)\n        {\n            pos = 1;\n            currentList = null;\n        }\n        else\n        {\n            C[i] = currentList[pos];\n            pos++;\n        }\n    }\n    else if (sA.Contains(el))\n    {\n        currentList = A;\n        C[i] = currentList[0];\n    }\n    else if (sB.Contains(el))\n    {\n        currentList = B;\n        C[i] = currentList[0];\n    }\n}\n\n// Outputs "Veal,Beef,Ham,Chicken,Deer,Cat,Monkey,Dog"\nConsole.WriteLine(string.Join(",", C));	0
10641786	10641644	KeyNotFoundException in dictionary in C#	foreach (var pair in ackData)\n{\n    Console.WriteLine("{0},{1}", pair.Key, pair.Value);\n}	0
9030552	9030499	How to change delimiter in C# datatable	string sCurrentCulture = System.Threading.Thread.CurrentThread.CurrentCulture.Name;\nCultureInfo ci = new CultureInfo(sCurrentCulture);\nci.NumberFormat.NumberDecimalSeparator = ".";\nSystem.Threading.Thread.CurrentThread.CurrentCulture = ci;	0
31355122	31355000	C# connectivity with SQL Server 2008	cmd.Connection = con;	0
32450201	32449511	How can I receipt users?	if (property.PropertyType.Name.ToLower() == "list`1")\n{\n     if (property.PropertyType.Name.ToLower() == "list`1")\n     {\n          var type = property.PropertyType;\n          var it = type.GetGenericArguments()[0];\n\n          var users = Activator.CreateInstance(type); // list of user\n          var user = Activator.CreateInstance(it);    //user\n\n          user.GetType().GetProperty("ID").SetValue(user, 1, null);\n          user.GetType().GetProperty("Name").SetValue(user, "Name1", null);\n\n          var add = type.GetMethod("Add");\n          add.Invoke(users, new[] { user });\n     }\n}	0
15831821	15831196	Binding on key withing a custom class	public class DataGridField\n{\n    public string this[string index]\n    {\n        get { return this.Key; }\n        set\n        {\n            this.Key = index;\n        }\n     }\n }	0
4906651	4906592	Combining 2 IQuerable results	public class EntityA : IEntity\n{}\n\npublic class EntityB : IEntity\n{}\n\nList<IEntity> results = \n(from a in EntityAList select a).Cast<IEntity>()\n.Concat(\n(from b in EntityBList select b).Cast<IEntity>()\n)\n.Fetch(N).ToList();\n\nforeach (IEntity entity in results)\n{\n if (entity is EntityA)\n  // do something with entity A\n\n if (entity is EntityB)\n  // do something with entity B\n}	0
9429820	9429791	Alter each value returned in a LINQ query at same time as query	.Select( s => s.Replace(@"C:\",""));	0
10928376	10927893	C# full hour format	TimeSpan diff = endDate - startDate;\nString.Format("{0:00}hr {1:00}mn {2:00}sec",\n                     Math.Truncate(diff.TotalHours),diff.Minutes,diff.Seconds);	0
3383409	3382816	Need help with a class?Might be simple	public class Person(....)\n{\n    protected string userID;\n\n    public Person(....)\n    {\n      //create userID   //no, print it\n      Console.WriteLine(userID);\n    }\n}\n\npublic class Staff : Person\n{\n    public Staff(...)\n      : base(....)         // now it is printed\n    {\n       this.userID = ...;  // and now it is filled\n    } \n}	0
10583866	10583815	Using QueryOver how do I write a Where statement against an "is in"	.Where(x => ListOfSubsetCodes.Contains (x.Code))	0
15206506	15206226	How can i add a table in my existing database without losing data in Entity-framework Code first 5.0 ?	Database.SetInitializer<dbContext>(new MigrateDatabaseToLatestVersion<dbContext, Configuration>());	0
12870389	12856057	windows phone 7 - xna programming input gesture	TouchCollection touchCollection = TouchPanel.GetState();\n        foreach (TouchLocation tl in touchCollection)\n        {\n            if (tl.State == TouchLocationState.Pressed)\n            {\n                  ...on touch down code\n            }\n\n            if (tl.State == TouchLocationState.Released)\n            {\n                  ...on touch up code\n            }\n\n        }	0
1740963	1726197	Find char width in pixels for various Arial fontsizes	gfx.MeasureString(token, this.font).Width	0
13781444	13781030	Working with subtypes in MySQL	CREATE TABLE Product(\nProd_id INT PRIMARY KEY AUTO_INCREMENT,\nName VARCHAR(40),\nBarcode INT\n);\n\nCREATE TABLE Card(\nProd_id INT,\nPrice DECIMAL(8, 2),\nFOREIGN KEY (Prod_id) REFERENCES Product(Prod_id)\n);\n\nINSERT INTO Product VALUES (NULL, 'phone', 1000);\nINSERT INTO Card VALUES(LAST_INSERT_ID(), 10.5);	0
728037	728018	Parsing a string in C#; is there a cleaner way?	private static string DecipherUserName (string user) {           \n    int start = user.IndexOf( "(" );\n    if (start == -1)\n        return user;\n    return user.Substring (start+1).Replace( ")", string.Empty );\n}	0
21430934	21430754	How to fill in HTML file contents with some data C#	string fileContents = File.ReadAllText(myFileName);\nfileContents = fileContents.Replace("<%username%>", textbox1.Text);\nFile.WriteAllText(fileContents, myFileName);	0
25671707	25671579	Assign textbox's value to another texbox without a botton	function enterAmt(ev) {\n    document.getElementById('amt2').value = ev.value;\n}	0
1827442	1827430	How to unit test the default case of an enum based switch statement	Assert.IsFalse(Enum.IsDefined(typeof(EnumType), Int32.MaxValue);\nCreate((EnumType)Int32.MaxValue);	0
12624227	12592031	Excel Controls - Delete Combo Box Dynamically	myBox.BeginInvoke(new MethodInvoker(delegate { sheetVSTO.Controls.Remove(myBox); }));	0
3755316	3754993	Is there a way to find a file by just its name in C#?	string target = "yourFilenameToMatch";\nstring current = Directory.GetCurrentDirectory();\n\n// 1. check subtree from current directory\nmatches=Directory.GetFiles(current, target, SearchOption.AllDirectories);\nif (matches.Length>0)\n    return matches[0];\n\n// 2. check system path\nstring systemPath = Environment.GetEnvironmentVariable("PATH");\nchar[] split = new char[] {";"};\nforeach (string nextDir in systemPath.Split(split))\n{\n    if (File.Exists(nextDir + '\\' + target)\n    {\n        return nextDir;\n    }\n}\n\nreturn String.Empty;	0
12231271	12231236	How to Test a Proxy with C#?	bool OK = false;\ntry\n{\n    WebClient wc = new WebClient();\n    wc.Proxy = new WebProxy(Host, Port);\n    wc.DownloadString("http://google.com/ncr");\n    OK = true;\n}\ncatch{}	0
5234956	5231827	Post On Facebook Page As Page Not As Admin User Using Facebook C# SDK	var dicParams = new Dictionary<string, object>();\n                        dicParams["message"] = stSmContentTitle;\n                        dicParams["caption"] = string.Empty;\n                        dicParams["description"] = string.Empty;\n                        dicParams["name"] = smContent.CmeUrl;\n                        dicParams["req_perms"] = "publish_stream";\n                        dicParams["scope"] = "publish_stream";\n\n                        // Get the access token of the posting user if we need to\n                        if (destinationID != this.FacebookAccount.UserAccountId)\n                        {\n                            dicParams["access_token"] = this.getPostingUserAuthToken(destinationID);\n                        }\n                        publishResponse = this.FacebookConnection.Post("/" + destinationID + "/feed", dicParams);	0
27782112	27780077	Keeping administrator privileges	// at application start\nvar identity = WindowsIdentity.GetCurrent();\nvar principal = new WindowsPrincipal(identity);\nbool isAdmin = principal.IsInRole(WindowsBuiltInRole.Administrator);\n\n// if not admin - elevate\nif(!isAdmin)\n{\n    var info = new ProcessStartInfo(Application.ExecutablePath) { Verb = "runas" };\n    Process.Start(info);\n    return; // exit\n}\n\n// if we are here - application runs as admin\n...	0
25127608	25127525	getting directory root isn't acting as expected	var appdir = Path.GetDirectoryName(AppDomain.CurrentDomain.BaseDirectory);\nvar ppsdir = Directory.GetParent(appdir).FullName;	0
10981935	10980241	How can a child entity move from one parent to another?	Child child = sourceParent.Children.First();  // or whatever\n\nchild.ParentObject = destinationParent;	0
12461431	12461343	How to get type of the custom UserControl?	Type myType = myCustomUserControl.GetType();	0
21768132	21768063	Having issues extracting part of an XML document	var ns = XNamespace.Get("http://schemas.microsoft.com/voicecommands/1.0");\ntb.Text = xDoc.Root.Element(ns + "CommandSet").Element(ns + "CommandPrefix").Value;	0
9223846	9223772	Prevent radiobutton click	// some function\n        GroupBox g = createGBox();\n        this.Controls.Add(g);\n        g.Controls.Add(radioButton1);\n        g.Controls.Add(radioButton2);\n    }\n\n    public GroupBox createGBox()\n    {\n        GroupBox gBox = new GroupBox();\n        gBox.Location = new System.Drawing.Point(72, 105);\n        gBox.Name = "BOX";\n        gBox.Size = new System.Drawing.Size(200, 100);\n        gBox.Text = "This is a group box";\n        return gBox;\n    }	0
29452197	29433400	Saving many to many relationship in EF 6.1	[HttpPost]\n    [ValidateAntiForgeryToken]\n    public ActionResult Create([Bind(Include = "ReservationId,ArrivalDate,LeaveDate,CampingSpotId,UserId,PersonsAmount,FacilityType,FacilityPrice")] Reservation reservation, int[] SelectedFacilities) \n    {\n        //Instantiate our facilities list!\n        reservation.FacilitiesList = new List<Facility>();\n\n        foreach (int facId in SelectedFacilities)\n        {\n            var facType = _facilityrepository.GetFacilityType(facId);\n            var facPrice = _facilityrepository.GetFacilityPricePerDay(facId);\n            reservation.FacilitiesList.Add(new Facility { FacilityId = facId, FacilityType = facType, FacilityPrice = facPrice} );\n        }\n\n        _reservationrepository.Add(reservation);\n        return View() //code omitted \n    }	0
17015594	17015586	C# List getting same value	EmployeeHeader emp = new EmployeeHeader();	0
7058200	7056048	Removing pushpin from Bing map	private void AddPushpinButton_Click(object sender, RoutedEventArgs e)\n    {\n        GeoCoordinate location = new GeoCoordinate() { Latitude = 51.5, Longitude = 0 };\n        Pushpin pushpin1 = new Pushpin() { Location = location, Tag = "FindMeLater" };\n        map1.Children.Add(pushpin1);\n    }\n\n    private void RemovePushpinButton_Click(object sender, RoutedEventArgs e)\n    {\n        var pushpin = map1.Children.First(p => (p.GetType() == typeof(Pushpin) && ((Pushpin)p).Tag == "FindMeLater"));\n        map1.Children.Remove(pushpin);\n    }	0
5348504	5348363	how to do a Join in Entity Framework	var query = db.Accounts.Join(db.BankTransactions,\n     Account => acc.AccountID,\n     bank=> bank.AccountID,\n     (acc,bank) => new {Account = acc, BankTransaction = bank });	0
10997465	10996396	Telnet connection with SQL Server	GET / HTTP/1.1	0
18203858	18203800	Convert List of object into another List of object	R = V.GroupBy(x => x.id)\n     .Select(g => new Result(){\n        id = g.Key,\n        vachelid = string.Join(",", g.Select(x => x.vachelid).Distinct()),\n        title = string.Join(",", g.Select(x => x.title).Distinct()),\n     }).ToList();	0
33957946	33907192	How to Retain HttpPostedFileBase on View Return	public ActionResult UploadTemporary(HttpPostedFileBase file)\n{\n    Guid reference = Guid.NewGuid();\n    string extension = Path.GetExtension(file.FileName);\n    string fullName= reference.ToString()+extension;\n    var path = Path.Combine(Server.MapPath("~/Content/TempFiles/"), fullName);\n\n    var data = new byte[file.ContentLength];\n    file.InputStream.Read(data, 0, file.ContentLength);\n\n    using (var sw = new FileStream(path, FileMode.Create))\n    {\n        sw.Write(data, 0, data.Length);\n    }\n\n    return Content(reference);\n}	0
17944359	17944144	Is There Any General XMLSchema that can be used to validate our XML string	string Parameetrs = "<root><HostName></HostName></root>";\n  var xmlDoc = new XmlDocument();\n  xmlDoc.LoadXml(Parameetrs);	0
8332709	8332588	Terminate Console ReadLine	IsBackground = true;	0
20690940	20690637	C# Regex to find strings surrounded by curly braces that do not have just a digit inside the braces	\{\D+\}	0
6380094	6379858	Collapse 'button' for splitcontainer control	private void radButton1_Click(object sender, EventArgs e) \n{ \n    splitPanel1.Collapsed = !splitPanel1.Collapsed; \n}	0
11173300	11172932	How to parse, and dechipher data output	static void Main()\n{\n    char[] delimiterChars = { ' ', ',', '.', ':', '\t' };\n\n    string text = "one\ttwo three:four,five six seven";\n    System.Console.WriteLine("Original text: '{0}'", text);\n\n    string[] words = text.Split(delimiterChars);\n    System.Console.WriteLine("{0} words in text:", words.Length);\n\n    foreach (string s in words)\n    {\n        System.Console.WriteLine(s);\n    }\n}	0
4804960	4448468	Compare date value obtained from TextBox in Windows Form, to Date value stored in Excel sheet	String sql = "select * from [Tabelle1$] WHERE blahblah "' AND (StartDate <= @curDate AND EndDate >= @curDate)";\nOleDbCommand olDbCmd = new OleDbCommand(sql, con);\nOleDbParameter curDate = new OleDbParameter("curDate", DateTime.Now);\ncurDate.DbType = DbType.DateTime;\nolDbCmd.Parameters.Add(curDate);\nOleDbDataAdapter cmd = new System.Data.OleDb.OleDbDataAdapter(olDbCmd);	0
25215910	25215217	How to set Localization / culture in iOS Xamarin C#	var path = NSBundle.MainBundle.PathForResource("en", "lproj");\nNSBundle languageBundle = NSBundle.FromPath(path);\nlblEn.Text = languageBundle.LocalizedString("Task Details", "Task Details");\n\nvar path1 = NSBundle.MainBundle.PathForResource("es", "lproj");\nNSBundle languageBundle1 = NSBundle.FromPath(path1);\nlblEs.Text = languageBundle1.LocalizedString("Task Details", "Task Details");	0
25032790	25032523	C# ASP.NET Selecting multiple column from same mysql command and use them in code behind	using(var connection = new MySqlConnection(myConnString))\n{\n   var cmd = connection.CreateCommand();\n   cmd.CommandText = "select nome,cognome from Utenti where CodiceCliente = @codice";\n   cmd.Parameters.AddWithValue("@codice", value);\n   var reader = cmd.ExecuteReader();\n   while(reader.Read())\n   {\n       // here could be problems if database value is null\n       var nome = reader["nome"];\n       var cognome = reader["cognome"];\n   }\n}	0
12392815	12392790	How to set a WPF window's icon to an icon file through C#?	mywindow.Icon = new BitmapImage(new Uri(@"C:\myicon.ico"));	0
12705910	12705883	String Manipulation using C#	test = test.Replace("\"","");	0
673747	673744	How can I add " character to a multi line string declaration in C#?	string s = @"..."".....";	0
20543038	20542857	Creating Multiple Users	var authStore = new AuthenticationStore();\n\nforeach(var user in users)\n{\n    if(UserAuthentication.Verify(user))\n    {\n        authStore.Add(user);\n        // store auth token in session or similar\n    }\n}	0
31341061	31339568	Add code to XSLT before transformation	XNamespace ns = "http://www.w3.org/1999/XSL/Transform";\n\nXElement xslt = XElement.Load(sXslPath);\n\nxslt.AddFirst(new XElement(ns + "include", new XAttribute("href", "FOOT.xslt")));\nxslt.AddFirst(new XElement(ns + "include", new XAttribute("href", "HEAD.xslt")));\n\nXElement body = xslt.Descendants("body").Single();\n\nbody.AddFirst(new XElement(ns + "call-template", new XAttribute("name", "Header")));\nbody.Add(new XElement(ns + "call-template", new XAttribute("name", "Footer")));	0
18874537	18872077	How can I change the shape of a gridview to circular?	.circle {\n    width: 320px;\n    height: 320px;\n    background: LightPink;\n    -moz-border-radius: 160px;\n    -webkit-border-radius: 160px;\n    border-radius: 160x;\n}	0
31099907	31099798	How to change the value of KeyPairValue in dictionary?	// This dictionary can be defined on the class\n// as a private static readonly member.\nvar translations = new Dictionary<string,string> {\n    {"original1", ""translation1}\n,   {"original2", "translation2"}\n};\nforeach(var kvp in wmDictionary) {\n    string translated;\n    if(!translations.TryGetValue(kvp.Value, out translated)){\n        translated=kvp.Value;\n    }\n    Console.WriteLine("Key={0} Translated value={1}", kvp.Key, translated);\n}	0
1138950	1138625	How to terminate all [grand]child processes using C# on WXP (and newer MSWindows)	public bool killProcess(int pid)\n {\n  bool didIkillAnybody = false;\n  try\n  {\n   Process[] procs = Process.GetProcesses();\n   for (int i = 0; i < procs.Length; i++)\n   {\n    didIkillAnybody = GetParentProcess(procsIdea.Id) == pid) &&\n                                   killProcess(procsIdea.Id);\n   }\n   try\n   {\n    Process myProc = Process.GetProcessById(pid);\n    myProc.Kill();\n    return true;\n   }\n   catch { }\n  }\n  catch (Exception ex)\n  {\n   try\n   {\n    new Logger().Write("Exception caught at JobExecution.killProcess()", ex.Message, System.Diagnostics.EventLogEntryType.Warning, false);\n   }\n   catch { }\n  }\n  return didIkillAnybody;\n }\n\n private int GetParentProcess(int Id)\n {\n  int parentPid = 0;\n  using (ManagementObject mo = new ManagementObject("win32_process.handle='" + Id.ToString() + "'"))\n  {\n   mo.Get();\n   parentPid = Convert.ToInt32(mo["ParentProcessId"]);\n  }\n  return parentPid;\n }	0
14685580	14685493	Error encountered inserting into a database in C#	string insert = "INSERT INTO EMP_tracking(emp_login, emp_dom_code, emp_domain,   emp_affectation_date, emp_surname" +\n        ",emp_name, emp_service,emp_telephone_model" +\n        ",emp_entry_date" +\n        ",emp_telephone_number" +\n        ",emp_cellphone_number" +\n        ",emp_email) VALUES (@emp_login, @emp_dom_code, //... etc.";\n\ncmd_Insert.Parameters.AddWithValue("@emp_login", readerReference.GetString(loginIndex));\ncmd_Insert.Parameters.AddWithValue("@emp_dom_code", readerReference.GetInt32(DomCodeLoginIndex));\n//etc...	0
16804307	16803143	Combining LINQ-to-Entities Queries into Single Query	from t in ProviderRankings\n  group t by key = 0\n  into g\n  select new {\n     previousVote  = g.FirstOrDefault(r => r.UserId == CurrUserId),\n     totalVotes = g.Count(),\n     averageVote = g.Average(x => x.Rating)\n  }	0
4344268	4344232	Problem filling a DataGridView	dataGridView1.DataBind();	0
19706365	19704387	How to optimize a LINQ with minimum and additional condition	var result = objects.Aggregate(\n    default(SomeObject),\n    (acc, current) =>\n        !current.IsValid ? acc :\n        acc == null ? current :\n        current.Height < acc.Height ? current :\n        acc);	0
2574132	2574118	Check if any object in a 2d array is null	foreach (var item in cells)\n{\n    //code\n}	0
24157336	24157122	How can I mix the order of words in a textbox in C#?	string text = "today is a beautiful day";\nvar mixedWords = text.Split()                     // split by white-spaces\n    .Select((word, index) => new { word, index }) // select anonymous type\n    .GroupBy(x => x.index % 2)                    // remainder groups to split even and odd indices\n    .OrderBy(xg => xg.Key)                        // order by even and odd, even first\n    .SelectMany(xg => xg                          // SelectMany flattens the groups\n        .OrderByDescending(x => x.index)          // order by index descending\n        .Select(x => x.word));                    // select words from the anonymous type\nstring newText = string.Join(" ", mixedWords);    // "day a today beautiful is"	0
11153597	11131911	How to set default Printer dynamically in wpf	var query = new ManagementObjectSearcher("SELECT * FROM Win32_Printer");\n                var printers = query.Get();                   \n                foreach (ManagementObject printer in printers)\n                {\n                    if (printer["name"].ToString() == combox_pinter.SelectedItem.ToString())\n                    {\n                        printer.InvokeMethod("SetDefaultPrinter", new object[] { combox_pinter.SelectedItem.ToString() });\n                    }\n                }	0
24127753	23541758	How to use (if possible) same source a tap event uses in a ContextMenu button click?	private void Save_Click(object sender, System.Windows.RoutedEventArgs e)\n{\n    var element = (FrameworkElement)sender;\n\n    SoundData data = element.DataContext as SoundData;\n\n    _CustomRingtone.Source = new Uri(data.FilePath, UriKind.RelativeOrAbsolute**);\n    _CustomRingtone.DisplayName = "Ring";\n    _CustomRingtone.Show();\n}	0
3251469	3251367	How to Delete a entire folder and all its contents including readonly files	string[] allFileNames = System.IO.Directory.GetFiles(tempFolder, "*.*", System.IO.SearchOption.AllDirectories);\nforeach (string filename in allFileNames) {\n    FileAttributes attr = File.GetAttributes(filename);\n    File.SetAttributes(filename, attr & ~FileAttributes.ReadOnly);\n}	0
25369449	25369399	How to know threadid for each thread spawn by parallel.foreach	Thread.CurrentThread.ManagedThreadId	0
21753475	21753132	Parsing Parameters of a Powershell Script. How to do this from C#?	var str = @"param([string]$name,[string]$template)";\nvar matches = Regex.Matches(str, "\\[(?<type>\\w+)\\]\\$(?<name>\\w+)").OfType<Match>()\n                   .Select(m => new \n                                {\n                                   name = m.Groups["name"].Value, \n                                   type = m.Groups["type"].Value\n                                });\nforeach (var m in matches)\n{\n    // check m.name and m.type\n}	0
1342946	1342922	Console.WriteLine as hexadecimal	Console.WriteLine ("Hex: {0:X}", nNum);	0
6481414	6481313	Passing a byte* to Stream.Read(byte[], int, int)	class SomeDataProcessor\n{\n    [ThreadStatic]\n    static byte[] _Buffer;\n}	0
15412119	15412000	how to replace label text with text in the column c#	string studentName = string.Empty;\n    while (sr.Read())\n    {\n     studentName = sr["StudentName"].toString();\n\n    }\n\nlblMyLabel.Text = studentName;	0
18167167	18165794	Pausing an Application Procedure	SlideTransition slideTransition = new SlideTransition { Mode = SlideTransitionMode.SlideRightFadeOut };\nITransition transition = slideTransition.GetTransition(textBlockSong);\ntransition.Completed += delegate \n{ \n    transition.Stop(); \n\n    SlideTransition slideTransition2 = new SlideTransition { Mode = SlideTransitionMode.SlideRightFadeIn };\n    ITransition transition2 = slideTransition2.GetTransition(textBlockSong);\n    transition2.Completed += delegate { transition2.Stop(); };\n    transition2.Begin();\n\n};\ntransition.Begin();	0
22500596	22500574	Split the string in asp.net with c#	string year = date.ToString("yy");	0
11125911	11125858	find dynamically created control and hide it	var button = (from b in this.Controls.OfType<Button>()\n              where b.Name == nameOfButton).First();\n\nbutton.Hide();	0
9908507	9896859	Delete Matching Braces in Visual Studio	Sub DeleteMatchingBrace()\n    Dim sel As TextSelection = DTE.ActiveDocument.Selection\n    Dim ap As VirtualPoint = sel.ActivePoint\n\n    If (sel.Text() <> "") Then Exit Sub\n    ' reposition\n    DTE.ExecuteCommand("Edit.GoToBrace") : DTE.ExecuteCommand("Edit.GoToBrace") \n\n    If (ap.DisplayColumn <= ap.LineLength) Then sel.CharRight(True)\n\n    Dim c As String = sel.Text\n    Dim isRight As Boolean = False\n    If (c <> "(" And c <> "[" And c <> "{") Then\n        sel.CharLeft(True, 1 + IIf(c = "", 0, 1))\n        c = sel.Text\n        sel.CharRight()\n        If (c <> ")" And c <> "]" And c <> "}") Then Exit Sub\n        isRight = True\n    End If\n\n    Dim line = ap.Line\n    Dim pos = ap.DisplayColumn\n    DTE.ExecuteCommand("Edit.GoToBrace")\n    If (isRight) Then sel.CharRight(True) Else sel.CharLeft(True)\n\n    sel.Text = ""\n    If (isRight And line = ap.Line) Then pos = pos - 1\n    sel.MoveToDisplayColumn(line, pos)\n    sel.CharLeft(True)\n    sel.Text = ""\nEnd Sub	0
20770999	20770861	How to change x-axis?	chart1.ChartAreas[0].AxisX.Minimum = 0;\nchart1.ChartAreas[0].AxisX.Maximum = 10;	0
8419810	8416407	Setting a dynamic effect to a UIElement.Effect	var shadowExpand = new DoubleAnimation();\nshadowExpand.From = 1;\nshadowExpand.To = 0;\nshadowExpand.Duration = new Duration(TimeSpan.FromMilliseconds(2000));\nshadowExpand.RepeatBehavior = RepeatBehavior.Forever;\nshadowExpand.AutoReverse = true;\nStoryboard.SetTarget(shadowExpand, addFlowShape);\nStoryboard.SetTargetProperty(shadowExpand, new PropertyPath("(UIElement.Effect).(DropShadowEffect.Opacity)"));\nvar stb = new Storyboard();\nstb.Children.Add(shadowExpand);	0
22689786	22689385	How can I log a message so that I can see it in VS2013?	Trace.Write("YOUR MESSGE");	0
26493059	26490270	Using Android Location Services in a XamarinForms App	public class AndroidLocationService : Java.Lang.Object, ILocationService, ILocationListener	0
25865698	25758282	Delete selected file from a folder using checkbox	protected void Button2_Click(object sender, EventArgs e)\n{\n    foreach (GridViewRow di in GridView1.Rows)\n    {\n        CheckBox chkId = (CheckBox)di.FindControl("CheckBox1");\n        if (chkId != null)\n        {\n            if (chkId.Checked)\n            {\n                string fileName = di.Cells[1].Text;\n                File.Delete(Server.MapPath("~/upload/" + TextBox1.Text + "/" + fileName));\n            }\n        }\n    }\n}	0
5261425	5261403	how can understand which control has been focused?	if (panel.ContainsFocus)\n{\n    Control currentlyFocused =\n        panel.Controls.Cast<Control>().FirstOrDefault(control => control.Focused);\n}	0
11183087	11182660	datagrid freezing before bind	public void clickit(Object sender, EventArgs e)\n{\n    //call the function\n    this.bindGrid();\n}\n\n //function to populate the datagrid with the data from the datasource\n   private void bindGrid()\n   {\n    string sql = "SELECT a from table1";\n    SqlConnection connection = new SqlConnection(connectionstring);\n    SqlDataAdapter adap= new SqlDataAdapter(sql, connection);\n    DataTable table = new DataTable();\n    connection.Open();\n    adap.Fill(table); //page reloads here, but hangs\n    mygrid.DataSource = table;\n    //bind the control with the data in the datasource\n    mygrid.DataBind();\n   connection.Close();\n   }	0
14805626	14805559	Assigning new dropdown list item value as NULL in database in C#	int id;\nEmployeeID = int.TryParse(ddlInstructorAllocated.SelectedValue, out id)\n                   ? id \n                   : (int?)null;	0
15141565	15141385	Saving Image from a Panel	using (Bitmap bitmap = new Bitmap(panel1.ClientSize.Width, \n                                  panel1.ClientSize.Height)) {\n  panel1.DrawToBitmap(bitmap, panel1.ClientRectangle);\n  bitmap.Save("C:\\" + pagAtual + ".bmp", ImageFormat.Bmp);\n}	0
360690	360392	Schedule Task with spaces in the path	string args = "/CREATE /RU SYSTEM /SC " + taskSchedule + " /MO " + taskModifier + " /SD " + taskStartDate + " /ST " + taskStartTime + " /TN " + taskName + " /TR \"\\\"" + taskSource + "\""	0
32592596	32592447	How to get the value of autocomplete textbox in asp.net	return {\n                            label: item.split('-')[0],\n                            val: item.split('-')[1],\n                            val: item.split('-')[2]\n                        }	0
4495840	4495827	Print msg to the console from GUI app - C#	Debug.WriteLine	0
4111586	4111568	How do I access the running method's name?	System.Diagnostics.StackTrace st = new System.Diagnostics.StackTrace();\nstring methodName = st.GetFrame(0).GetMethod().Name;	0
29683705	29683642	How to place values from struct to an array?	student[] my_array = new student[] {struct1,struct2,struct3};	0
7813367	7813207	How to remove a subset of items from an Entity Framework Collection	// Perform the deletes\nvar reqsToDelete = order.Requirements.Where(x=>!orderContract.Requirements.Any(y=>y.RequirementId==x.RequirementId)).ToList();\nforeach (var deleteReq in reqsToDelete)\n{\n    order.Requirements.Remove(deleteReq);\n}	0
19978643	19969983	How can I use a Expression tree in an EF Where() clause with join?	private object bindingSourceTbl1_DataSourceBinding(object sender, EventArgs e)\n{\n    using (SampleDbEntities dbo = new SampleDbEntities())\n    {\n\n       return dbo.Tbl1.Join(dbo.Tbl2, x => x.Id, y => y.Tbl1Id, (x, y) => new { Tbl1 = x, Tbl2 = y }).Where(a => a.Tbl2.Tbl6Id == (int)comboBoxTbl6.SelectedValue).Select(a => a.Tbl1).Where(Expr1()).ToList();\n    }\n}	0
16939817	16939627	In ReSharper 7, is it possible to extend syntax highlighting of strings?	[StringFormatMethod("me")]\npublic static string FormatWith(this string me, params object[] args) {\n    return string.Format(me, args);\n}	0
8022619	8022613	How To Prevent Overriding in C#?	sealed class MyBaseClass {\n    ...\n}	0
26215057	26117461	Unable to cast BsonArray to BsonInt32	double Total = 0;    \n\n    foreach (BsonDocument nestedDocument in myDocument["doc"].AsBsonArray)\n                        {\n                            Total += Convert.ToDouble(nestedDocument["amt"]);\n                        }	0
21779392	21778528	How to close a form from another form	//Form 1\nprivate void button1_click(object sender, EventArgs e)\n{\n    frmLeaveRequestConfirmation frmForm2 = new frmLeaveRequestConfirmation();\n    frmForm2.FormClosed += new FormClosedEventHandler(frmForm2_FormClosed);\n    frmForm2.Show();\n\n}\n\nprivate void frmForm2_FormClosed(object sender, FormClosedEventArgs e)\n{\n   this.Close();\n}\n\n\n//Form 2\nprivate void btnConfirm_Click(object sender, EventArgs e)\n{\n    this.Close();\n}	0
1798806	1798752	Linq, Where Extension Method, Lambda Expressions, and Bool's	var results = from a in context.aTable1\n              where !a.Bool2\n              select new\n              {\n                  Column1 = a.Column1\n                  Bool1 = a.Bool1\n                  Bool2 = a.Bool2\n              };\n\nresults = results.Where(l => !l.Bool1);\nresults = results.Where(l => l.Column1.Contains(fooString));	0
19551612	19551406	Calculate bottom 10% and top 10% values from quartile values	Probability   Value\n1/8           2\n4/8           3\n5/8           4\n7/8           5\n8/8          15	0
20111620	20111366	How to update a ComboBox from a window when closing another window?	// When button Adicionar is clicked\nprivate void buttonAdd_Click(object sender, EventArgs e)\n{\n    using(Form formAdd = new Form()) // This is the Gerenciar Fornecedor form\n    {\n        formAdd.ShowDialog(this); // Show the form. The next statement will not be executed until formAdd is closed\n        // Put the your code to update the ComboBox items here\n    }\n}	0
9617849	9617793	How to search for embedded files during runtime C#	var findedResourceNames = assembly.GetManifestResourceNames()\n     .Where(name => name.EndsWith(".xml")).ToArray();	0
16685618	16685543	Converting array of pointers from C++ to C#	int nData = 10;\n  int nwp = 3;\n\n  var varData = new UInt16[ nData, nwp ]; //varData is of type UInt16[,]	0
20733361	20733141	Replace Alphabet with another Alphabet in List	var map = new Dictionary<string, string>() {\n  {"A", "N"},\n  {"B", "Z"},  // ... etc\n};\nvar newList = originalList.Select(x=>map[x]).ToList();	0
25521559	25521243	How can we set the CommandTimeout as a property in our class and when set it will take effect all in DAL	public SqlCommand GetCommandObj()\n{\n        SqlCommand cmd=new SqlCommand();\n        cmd.CommandTimeout=60;\n        cmd.CommandText="your query here";\n        return cmd;\n}	0
11840352	11840319	How to create and populate generic Dictionary?	Dictionary<string, Point> spdic = new Dictionary<string, Point>();\n\nspdic.Add("mystring", new Point(0,0)); \nspdic.Add("mystring1", new Point(23,30));	0
31124593	31052666	Inserting rows of database into XML/XSD class C#	IEnumerable<human> humanList = (new PetaPoco.Database(connectionstring))\n.Fetch<human>("SELECT * FROM dbTable");	0
5659037	5659005	How to fetch integer value from given string? 	var myString = @"Ahmedabad to Gandhinagar Distance:29km(about 31 mins)";\nvar myRegex = @".*:(\d*)km.*";\nvar match = Regex.Match(myString, myRegex);\n\nif (match.Success)\n{\n    // match.Groups contains the match "groups" in the regex (things surrounded by parentheses)\n    // match.Groups[0] is the entire match, and in this case match.Groups[1] is the km value\n    var km = match.Groups[1].Value;\n}	0
18835006	18834816	Printing a document from Windows Form	Bitmap img = new Bitmap(this.ClientRectangle.Width, this.ClientRectangle.Height);\n this.DrawToBitmap(img, this.ClientRectangle);\n Point p = new Point(40, 650);\n e.Graphics.DrawImage(img, p)	0
4276748	4276702	Remove line and column with number N from two-dimensional List	dests.RemoveAt(N); // removes the line (row)\n\nforeach(var list in dests) // removes column by going through each row \n list.RemoveAt(N);	0
7778708	7777505	how to color form Gradually from yellow to green	using System.Drawing;\nusing System.Drawing.Drawing2D;\n\npublic Form1() {\n  InitializeComponent();\n  this.DoubleBuffered = true;\n  this.ResizeRedraw = true;\n}\n\nprotected override void OnPaintBackground(PaintEventArgs e) {\n  using (var lgb = new LinearGradientBrush(this.ClientRectangle, Color.Yellow, Color.Green, LinearGradientMode.Vertical))\n    e.Graphics.FillRectangle(lgb, this.ClientRectangle);\n}	0
11696004	11695824	Two Sets of controllers	System.Web.Mvc.Controller	0
25032358	25032122	Store and Retrieve in Windows Store Apps	Windows.Storage namespace	0
14002798	14002702	Get Rectangle from index in a tilemap	int tileY = tileIndex / numberOfTiles;\nint tileX = (tileIndex % numberOfTiles) - 1;	0
20463967	20463931	search in bit array in c#	for (int i = 0; i < (bits.Length)-1;i++ ) {\n    bool found = true;\n    for (int j = 0; j < 32; j++) {\n        if (bits[i + j] != bits[j]) {\n            found = false;\n            break;\n        }\n    }\n    if (found) Console.WriteLine("Found");\n}	0
2595651	2595629	Write string to fixed-length byte array in C#	static byte[] StringToByteArray(string str, int length) \n{\n    return Encoding.ASCII.GetBytes(str.PadRight(length, ' '));\n}	0
10360171	10359448	Saving PNG image to Isolated Storage for WP7	_bi = new BitmapImage(new Uri("http://blog.webnames.ca/images/Godzilla.png", UriKind.Absolute));\n_bi.ImageOpened += ImageOpened;\n...\n\nprivate void ImageOpened(object sender, RoutedEventArgs e)\n{\n    var isf = IsolatedStorageFile.GetUserStoreForApplication();\n\n    using (var writer = new StreamWriter(new IsolatedStorageFileStream("godzilla.png", FileMode.Create, FileAccess.Write, isf)))\n    {\n        var encoder = new PngEncoder();\n        var wb = new WriteableBitmap(_bi);\n        encoder.Encode(wb.ToImage(), writer.BaseStream);\n    }\n}	0
21463057	21462362	listbox doesn't show displaymember	lstAtt.ItemsSource = dtAtt.Select("Att_Pkg=0").CopyToDataTable().DefaultView;	0
20843795	20843733	How can you take only the last result with Linq	var query = from e in models.ExerciseUserResults\n    where e.ExerciseID == ExerciseId\n    group e by UserID into usersExercises\n    select usersExercises.Last();	0
3865117	3865076	How to escape Japanese characters?	public static string EscapeString(string s)\n{\n    StringBuilder sb = new StringBuilder();\n\n    foreach (char c in s)\n    {\n                int i = (int)c;\n                if (i < 32 || i > 126)\n                {\n                    sb.AppendFormat("&#{0};", i);\n                }\n                else\n                {\n                    sb.Append(c);\n                }\n\n    }\n\n    return sb.ToString();\n}	0
7232999	7232960	How do i use LinqToExcel to get sheet names of an excel file	var excel = new ExcelQueryFactory("excelFileName");\nvar worksheetNames = excel.GetWorksheetNames();	0
1927844	1927653	C# combobox selected index changed fires old value	protected override bool ProcessCmdKey(ref Message msg, Keys keyData)\n    {\n        if (keyData == (Keys.Control | Keys.Left))\n        {\n            DoUpdate();\n            return true;\n        }\n        else\n        {\n            return base.ProcessCmdKey(ref msg, keyData);\n        }\n    }	0
15896175	15878862	Search Combo Box like Google Search	DataTable temp;\n    DataTable bank;\n    private void Form1_Load(object sender, EventArgs e)\n    {\n        comboBox1.AutoCompleteMode = AutoCompleteMode.SuggestAppend;\n        comboBox1.AutoCompleteSource = AutoCompleteSource.ListItems;\n\n        temp = DbRdRw.SqlDbRead("Select * from BankMaster", "BankMaster");\n\n        DataView dtview = new DataView(temp);\n        dtview.Sort = "BankName DESC";\n        bank = dtview.ToTable();\n\n        comboBox1.DataSource = bank;\n        comboBox1.ValueMember = "BankName";\n        comboBox1.DisplayMember = "BankName";\n    }	0
23940147	23939925	dynamically changing picture box	private void pb_Click(object sender, EventArgs e)\n{ \n   var pb = sender as PictureBox;\n   if(pb != null)\n   {\n       pb.Visible = false;\n   }\n}	0
9853105	9852901	How can I bind a property to a TextBox	public class YourControl : Control, INotifyPropertyChanged\n{\n\n    public string VersionNumber {\n        get { return versionNumber; }\n        set {\n            versionNumber = value;\n            NotifyPropertyChanged("VersionNumber");\n        }         \n    }\n    private string versionNumber;\n\n    public event PropertyChangedEventHandler PropertyChanged;\n\n    protected void NotifyPropertyChanged(String info) {\n        if (PropertyChanged != null) {\n            PropertyChanged(this, new PropertyChangedEventArgs(info));\n        }\n    }\n}	0
24570097	24568999	How to generate multiple csv files from dataSet which is having multiple tables	public void GenerateCSVfiles(DataSet dataSets)\n{\n    //create csv file\n    StreamWriter sw = null;\n    StringBuilder sb = new StringBuilder();\n    foreach (DataTable dataTable in dataSets.Tables)\n    {\n        sw = new StreamWriter(string.Format(@"C:\Temp\{0}.csv", dataTable.TableName));\n\n        for (int i = 0; i < dataTable.Rows.Count; i++)\n        {\n            sb.Clear();\n\n            for (int j = 0; j < dataTable.Columns.Count; j++)\n            {\n                sb.Append(dataTable.Rows[i][j]);\n                if (j != (dataTable.Columns.Count - 1)) sb.Append(",");\n            }\n            sw.WriteLine(sb.ToString());\n        }\n        sw.Close();\n    }\n}	0
14043882	14043776	Break Lines and Wrapping in Auto Formating of Visual Studio with Reshaper	Reshaper > Environment > Code Editing > C# > Formating Style > Line Breaks And Wrapping.	0
22797072	22792313	show availability of username on createUserWizard with available image or unavailable image	.innerHTML	0
9345457	9345319	C# Regex and a bulk replace	class Program\n{\n    static void Main()\n    {\n        string data = "<data><ab:tag_x contents=\"some text1\" src_id=\"some id\"><br/><ab:tag_x contents=\"some text2\" src_id=\"some id\"></data>";\n        string pattern = "<ab:tag_x.*?contents=\"(.*?)\".*?>";\n        string replacement = "$1";\n        string result = Regex.Replace(data, pattern, replacement);\n\n        Console.WriteLine(result);\n    }\n}	0
291550	291522	WPF: How can you add a new menuitem to a menu at runtime?	//Add to main menu\nMenuItem newMenuItem1 = new MenuItem();\nnewMenuItem1.Header = "Test 123";\nthis.MainMenu.Items.Add(newMenuItem1);\n\n//Add to a sub item\nMenuItem newMenuItem2 = new MenuItem();\nMenuItem newExistMenuItem = (MenuItem)this.MainMenu.Items[0];\nnewMenuItem2.Header = "Test 456";\nnewExistMenuItem.Items.Add(newMenuItem2);	0
15238524	15238439	Typed Datatable - find int array using linq	var q = from t in tableName\n               where arInts.Contains(t.fieldName)\n               select t;	0
13149067	13148867	Scraping With HtmlAgilityPack	HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();\ndoc.Load(fileName);\n\nvar result = doc.DocumentNode.SelectNodes("//div[@class='boxes-contents cf']//tbody/tr")\n                .First(tr => tr.Element("td").Element("img").Attributes["title"].Value == "Lumber")\n                .Elements("td")\n                .First(td=>td.Attributes["class"].Value=="num")\n                .InnerText\n                .Trim();	0
20699844	20623509	DevExpress GridView Scroll Bar (adjusting Grid Left Coord to bring focused column in the center of the grid)	for (int i = 0; i < view.VisibleColumns.Count; i++)\n        {\n            if (info.GetColumnLeftCoord(view.GetVisibleColumn(i))\n                < view.ViewRect.Width - info.ViewRects.IndicatorWidth)\n\n                visibleColumnCount++;\n        }\n        return visibleColumnCount;\n    }	0
3579005	3578962	change the color of a char	// Save selection\nvar oldStart = richTextBox1.SelectionStart;\nvar oldLength = richTextBox1.SelectionLength;\n\n// Select the text to change\nrichTextBox1.Select(richTextBox1.TextLength - 1, 1);\n// Change color\nrichTextBox1.SelectionColor = Color.Red;\n\n// Restore selection\nrichTextBox1.Select(oldStart, oldLength);	0
16599789	16599728	Forcing the use of a factory object to instantiate a class	public class Factory {\n   private static Dictionary<Type, Func<Model>> creators;\n   public void AddCreator<T>(Func<T> creator) where T:Model\n   {\n      creators.Add(typeof(T), ()=> creator());\n   }\n\n   public static T Instance() where T : Model \n   {\n       return (T)(creators[typeof(T)] ());\n   }\n}	0
20553046	20552909	Checking property of EF6 model to see if it has a value or not?	HasLogo = (section.LogoFileID.HasValue) ? "Yes" : "No";	0
7194307	7194156	Reducing number of locally defined fields	public void GetSomeData1(DataParameters[] parameters, Action responseHandler)\n    {\n      Transactions.GetSomeData1(response => SomeData1ResponseHandler(response, responseHandler), parameters);\n    }\n\n    private void SomeData1ResponseHandler(Response response, Action responseHandler)\n    {\n      if (response != null)\n      {\n        CreateSomeData1(response.Data, responseHandler);\n      }\n    }\n\n    public void CreateSomeData1(Data data, Action responseHandler)\n    {\n      //Create the objects and then invoke the Action\n      ...\n\n      if(responseHandler != null)          \n      {\n        responseHandler();\n      }\n    }	0
10919107	10918994	How to call function with callbacks in Java like I do it in C#?	private void ParentFunc {\n    WorkerClass worker = new WorkerClass();\n\n    worker.doWork(new Callback<Integer>() {\n        public void invoke(Integer arg) {\n            System.out.println("Progress" + arg);\n        }\n    });\n}\n\npublic class WorkerClass {\n    public doWork(Callback<Integer> callback) {\n        for (int i=1; i<1000; i++) callback.invoke(i);  \n    }\n}\n\npublic interface Callback<T> {\n    public void invoke(T arg);\n}	0
16581944	16581903	LINQ to find set difference based on a column	var result = products.Where(p => !persons.Select(x => x.Id)\n                                         .Contains(p.Id));	0
11104139	11104113	C# Any string starting with	if(stringVariable.StartsWith("ta")) {\n    // starts with ta\n}	0
5437197	5437159	Is this the correct way to split a string using line breaks	myData.Split(new string[]{Environment.NewLine}, StringSplitOptions.RemoveEmptyEntries)	0
19303230	19299942	Validate XML nodes against a schema using accesory XSD files	public static void AddElementToSchema(XmlSchema xmlSchema, string elementName, string elementType, string xmlNamespace)\n{\n    XmlSchemaElement testNode = new XmlSchemaElement();\n    testNode.Name = elementName;\n    testNode.Namespaces.Add("", xmlNamespace);\n    testNode.SchemaTypeName = new XmlQualifiedName(elementType, xmlNamespace);\n    xmlSchema.Items.Add(testNode);\n    xmlSchema.Compile(XMLValidationEventHandler);\n}	0
9472635	9472130	How to focus cell on new row in WPF DataGrid	DataGridCell cell = GetCell(rowIndex, colIndex);\ncell.Focus;	0
18996423	18951197	Null parameter when trying to pass a blob to C# controller	var length = Request.ContentLength;\n            var bytes = new byte[length];\n            Request.InputStream.Read(bytes, 0, length);	0
7082059	7080970	Convert raw grayscale binary to JPEG	int height=41;\nint width=20;\nint[] data = {...};\n\nBufferedImage bi = new BufferedImage(width, height, BufferedImage.TYPE_BYTE_GRAY);\nfor ( int x = 0; x < width; x++ ) {\n  for ( int y = 0; y < height; y++ ) {\n  // fix this based on your rastering order\n  final int c = data[ y * width + x ];\n  // all of the components set to the same will be gray\n  bi.setRGB(x,y,new Color(c,c,c).getRGB() );\n  }\n}\nFile out = new File("image.jpg");\nImageIO.write(bi, "jpg", out);	0
25360569	25360539	How to check a Checkboxlist based on given value?	foreach(ListItem item in CheckBoxList1.Items)\n    item.Selected = values.Contains(item.Value);	0
7930984	7930927	Retrieve BLOB file	Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";\n Response.AddHeader("content-disposition", "attachment;  filename=whatever.xlsx");\n Response.BinaryWrite(yourbytes);	0
1985552	1985524	C# Refactoring of If Statement	bool valid = false; \n       if(ValidateRecordIdentifiers() && ValidateTotals() && ValidateRecordCount())\n        {\n          valid = true;\n        }\n\n\n/******AN Alternate Suggestion for the above code********/\n    bool valid =  ValidateRecordIdentifiers() && \n                  ValidateTotals() && \n                  ValidateRecordCount();\n/*******End Alternate Suggestion*************/\n\n\n   var statusMessage = (valid) ? \n       LogMessages.StatusMessages.JobValidationPassed :\n       LogMessages.StatusMessages.JobValidationFailed\n\n   LogLogic.AddEntry(LogLogic.GetEnumDescription(statusMessage));\n\n   return valid;	0
10497211	10496647	Set active membership provider programmatically	var p = (ProgressMembershipProvider)Membership.Providers["ProgressProvider"];\nvar user = p.GetUser("Foo", true);	0
8787481	8787121	Login to jira soap api	JiraSoapServiceService jiraSoapService = new JiraSoapServiceService();\n\n    public string Login(string user, string pwd)\n    {\n        string result = string.Empty;\n\n        result = jiraSoapService.login(user, pwd);\n\n        return result;\n\n    }\n\n\n    public void Logout(string token)\n    {\n        jiraSoapService.logout(token);\n    }	0
4953267	4952995	How to change orderby on postback for LINQ to SQL query	var q = from p in db.Items\n        select q;\n\nswitch(item)\n{\n    case 1:\n        q.OrderBy(x=> x.Name);\n        break;\n    case 2:\n        q.OrderBy(x=> x.MSRP);\n        break;\n    default:\n        break;\n\n}\n\nforeach(var n in q)\n{\n    // Do work\n}	0
1208631	1208560	How to wait on events on a second thread	private bool running = true;\nprivate AutoResetEvent waiter = new AutoResetEvent(false);\n\npublic void Run()\n{\nFileSystemWatcher watcher = new FileSystemWatcher("C:\\");\nFileSystemEventArgs changes = null;\n\nwatcher.Changed +=\n(object sender, FileSystemEventArgs e) => {\nchanges = e;\nwaiter.Set();\n};\n\nwatcher.EnableRaisingEvents = true;\n\nwhile (running)\n{\nwaiter.WaitOne();\nif (!running) break;\n\nConsole.WriteLine("Path: {0}, Type: {1}",\nchanges.FullPath, changes.ChangeType);\n}\n\nConsole.WriteLine("Thread complete");\n}\n\npublic void Stop()\n{\nrunning = false;\nwaiter.Set();\n}	0
30655884	30652829	Interfacing with xaml viewmodel	public Carvm()\n{\n    carLibrary = new CarLib();\n\n    carLibrary.List.Add(new Car("chevy", "corvette", "2016"));\n    carLibrary.List.Add(new Car("ford", "gt", "2016"));\n    carLibrary.List.Add(new Car("bmw", "m3", "2005"));\n\n    rmCommand = new DeleteCommand(carLibrary);\n    touchCommand = new AddCommand(carLibrary);\n    NewCar = new Car(); // this line is added\n\n}	0
11719587	11719534	SmtpClient sending without authentication	If the UseDefaultCredentials property is set to false and the Credentials property has not been set, then mail is sent to the server anonymously.	0
14051152	14050967	How to call a Successful Callback function after executing an Asynchronous method?	System.Threading.Tasks.Task.Factory.StartNew(\n                                        () => AddAttachment(document, docId, user)).ContinueWith(\n                                            task => OnComplete(task), }\n                                            TaskContinuationOptions.None);  \n\n\nprivate void OnComplete(task)\n{\n   if(task.IsFaulted)\n   {\n   }\n   else if(task.IsComplete) {}\n\n}	0
28167620	27266935	Get Calendar Items in Exchange	System.Net.ServicePointManager.ServerCertificateValidationCallback = Ise_ExchangeInterface.CertificateValidationCallBack;\n            m_Service = new ExchangeService(ExchangeVersion.Exchange2007_SP1);\n            m_Service.Credentials = new WebCredentials(m_UserName, m_Password);\n            m_Service.AutodiscoverUrl(m_UserName, Ise_ExchangeInterface.RedirectionUrlValidationCallback);	0
6119218	6119213	How can I convert List<byte> to byte[] in C#?	myArrayByte = myListByte.ToArray();	0
2634761	2634731	Best way to get all digits from a string	return new String(input.Where(Char.IsDigit).ToArray());	0
3918861	3881191	Browse ADAM and retrive values from C#	DirectoryEntry entry = new DirectoryEntry("LDAP://view.domain.com/OU=Servers,DC=vdi,DC=vmware,DC=int", "domain\\Administrator", "paSSw0rd");\n\nDirectorySearcher ds = new DirectorySearcher(entry);\nds.SearchScope = SearchScope.Subtree;\nds.PropertiesToLoad.AddRange(new String[] { "pae-SIDString", "ipHostNumber" });	0
30948213	30921190	How to deserialize an uploaded font from a Base64String?	// used to store our font and make it available in our app\n                var pfc = new PrivateFontCollection();\n\n                IntPtr data = Marshal.AllocCoTaskMem((int) ms.Length);\n\n                Marshal.Copy(fontBytes, 0, data, (int)ms.Length);\n\n                pfc.AddMemoryFont(data, (int)ms.Length);\n\n                Marshal.FreeCoTaskMem(data);\n\n                var fontWithMime = "data:application/x-font-truetype;charset=utf-8;base64," + cleanFontData;\n\n                fontName = pfc.Families[0].Name;	0
23101486	23101249	How to Scroll into selected item in listbox in windows phone 7	Listbox1.UpdateLayout();\nListbox1.ScrollIntoView(Listbox1.Items[Listbox1.SelectedIndex]);	0
21985790	21985678	Get text element from a javascript alert using webdriver	driver.SwitchTo().Alert().Text;	0
1063427	1063377	How to Add file to the folder only if the file doesnt exist using C#	if (!File.Exists(newfilename)) \n{\n    File.Move(oldfilename, newfilename);\n}	0
20619353	20588149	Put data directly into DataTable or dot net object?	using ADODB;\n\n  ADODB.Recordset resultSet = (ADODB.Recordset)Dts.Variables["MyResultSet"].Value;\n  int rows = resultSet.RecordCount;	0
9409529	9409051	Winforms: Keyboard shortcuts for Winforms app hosting other applications in its panels	::GetForegroundWindow()	0
18534463	18534132	MVC - Is it possible to send an array from a .ashx.cs file to a controller action?	ControllerName objectName = new ControllerName() ;\nobjectName.ActionName(Parameters)	0
9637448	9636714	Columns in Windows Phone 7	var wp = new WrapPanel\n    {\n        Orientation = System.Windows.Controls.Orientation.Vertical,\n        Height = 400\n    };\n\nwp.Children.Add(new Button { Content = "A", BorderBrush = new SolidColorBrush(Colors.Cyan) }); // Cyan is the same as Aqua\nwp.Children.Add(new Button { Content = "B", BorderBrush = new SolidColorBrush(Color.FromArgb(255, 95, 158, 160)) }); // CadetBlue\nwp.Children.Add(new Button { Content = "C", BorderBrush = new SolidColorBrush(Color.FromArgb(255, 139, 0, 139)) }); // DarkMagenta\nwp.Children.Add(new Button { Content = "D", BorderBrush = new SolidColorBrush(Colors.Magenta) }); // Fuschia is the same as Magenta\nwp.Children.Add(new Button { Content = "F", BorderBrush = new SolidColorBrush(Color.FromArgb(255, 173, 216, 230)) }); // LightBlue\nwp.Children.Add(new Button { Content = "G", BorderBrush = new SolidColorBrush(Colors.Orange) });\n\nthis.LayoutRoot.Children.Add(wp);	0
16319873	16319832	How can I assign a property to an attribute	[ExtractKey(ExtractionKeys.Extraction)]\n...\n\n\npublic static class ExtractionKeys\n{\n    public const string Extraction = "Extraction";\n}	0
1839072	1838564	How can I programmatically delete a line from a Word document using c#?	private static object missing = System.Reflection.Missing.Value;\n\n/// <summary>\n/// Deletes the line in which there is a selection.\n/// </summary>\n/// <param name="application">Instance of Application object.</param>\nprivate void DeleteCurrentSelectionLine(_Application application)\n{\nobject wdLine = WdUnits.wdLine;\nobject wdCharacter = WdUnits.wdCharacter;\nobject wdExtend = WdMovementType.wdExtend;\nobject count = 1;\n\nSelection selection = application.Selection;\nselection.HomeKey(ref wdLine, ref missing);\nselection.MoveDown(ref wdLine, ref count, ref wdExtend);\nselection.Delete(ref wdCharacter, ref missing);\n}	0
23808448	23807307	Getting nsi:type in xml	XmlNode typeOfNode = \n    xdoc.SelectSingleNode("MyObjectBuilder_Sector/SectorObjects/MyObjectBuilder_EntityBase");\n\n//here typeValue variable will contains "MyObjectBuilder_CubeGrid"\nString typeValue = typeOfNode.Attributes["xsi:type"].Value;	0
731689	731651	Passing a byte stream from model to the view so it can be saved by the user	Response.AddHeader("content-disposition", fileName);    \nResponse.ContentType = "application/pdf";\nResponse.BinaryWrite(byteArray);	0
1140316	1139996	WPF ListBox Button Selected Item	var curItem = ((ListBoxItem)myListBox.ContainerFromElement((Button)sender)).Content;	0
7569966	7530074	How do you create a custom collection editor form for use with the property grid?	public class CustomCollectionModalEditor: UITypeEditor\n{\n    public override UITypeEditorEditStyle GetEditStyle(ITypeDescriptorContext context)\n    {\n        if (context ==null || context.Instance == null)                \n            return base.GetEditStyle(context);\n\n        return UITypeEditorEditStyle.Modal;\n    }\n\n    public override object EditValue(ITypeDescriptorContext context, IServiceProvider provider, object value)\n    {\n        IWindowsFormsEditorService editorService;\n\n        if (context == null || context.Instance == null || provider == null)\n            return value;\n\n        editorService = (IWindowsFormsEditorService)provider.GetService(typeof(IWindowsFormsEditorService));\n\n        CForm CollectionEditor = new CForm();\n\n        if (editorService.ShowDialog(CollectionEditor) == System.Windows.Forms.DialogResult.OK)\n            return CollectionEditor.Programmed;\n\n        return value;\n        //return base.EditValue(context, provider, value);\n    }\n}	0
16045976	16044087	deserializing data best practices	var fieldValues = new string[3];\nvar currentField = 0;\nvar line = "InternalNameA8ValueDisplay NameA?InternalNameB8ValueDisplay NameB?";\n\nforeach (var c in line)\n{\n    if (c == '8' && currentField == 0)\n    {\n        currentField++; continue;\n    }\n\n    if (c == '?')\n    {\n        currentField++; continue;\n    }\n\n    fieldValues[currentField] += c;\n}	0
33885177	33885156	C# Local variables	string D1;\n    if (A1.Text != "" || A1.Text != null)\n    {\n        D1 = "<"+A1.Text+">";\n    }\n    else\n    {\n        D1 = "null";\n    }\n\n    // Then you can reference `D1` later in the same method.\n    this.label1.Text = D1;	0
10556477	8097611	How to Update a Task (change User Story) using Rally API?	public string ProxyUpdateTask(Task myTask, string strWorkProduct)\n    {\n\n        var message = @"<span style=""color:green;"">SUCCESS</span>";\n        const string errPrefix = @"<span style=""color:red;"">ERROR</span>";\n\n        var toUpdate = new DynamicJsonObject();\n\n        long oid;\n        Int64.TryParse(myTask.ObjectId, out oid);\n\n        toUpdate["WorkProduct"] = String.Format("/hierarchicalrequirement/{0}", myTask.UserStoryId);\n\n\n        try\n        {\n            var result = _restApi.Update("task", oid, toUpdate);\n            if (!result.Success) \n                message = String.Format(@" {2} updating (ObjectID={0}) failed. {1}", myTask.ObjectId, result.Errors, errPrefix);\n        }\n        catch (WebException ex)\n        {\n            message = String.Format(" {0} - {1}", errPrefix, ex.Message);\n        }\n        catch (Exception ex)\n        {\n            message = String.Format(" {0} - {1}", errPrefix, ex.Message);\n        }\n\n        return message;\n\n    }	0
13759299	13759278	How can I subtract 6 hour from the current time?	DateTime dt1 = dt.AddHours(-6);	0
31207268	31207226	How to create custome tabs like below image?	TabControl.Multiline Property	0
16399196	16397061	Insert the date into 2 tables	cmd.CommandText = "insert into tbl_item (@itemcode,@itemname) values(ItemCode,ItemName);insert into  tbl_image (@itemcode,@itemimage) values(ItemCode,ItemImage)";	0
24031021	24030861	How to display a table containing data inside message box using C#	ShowDialog()	0
8529347	8529335	Decimal to string conversion issue	double foo = -0.00001;\nConsole.WriteLine(foo.ToString("f5"));	0
25272005	25271807	Two different applications using codebase and GAC for loading the same assembly	Assembly.Load(byte[])	0
12500403	12500280	Linq - How do I coalesce these into a single IQuerable?	things.SelectMany(t => t.Strings);	0
9737175	9729570	How to fluidly reorder a collection in a listbox?	public class SuperObservableCollection<T> : ObservableCollection<T>\n{\n    public void SetItems(IEnumerable<T> items)\n    {\n        suppressOnCollectionChanged = true;\n        Clear();\n        AddRange(items);\n    }\n\n    private bool suppressOnCollectionChanged;\n    public void AddRange(IEnumerable<T> items)\n    {\n        suppressOnCollectionChanged = true;\n\n        if (items != null)\n        {\n            foreach (var item in items)\n                Add(item);\n        }\n\n        suppressOnCollectionChanged = false;\n        NotifyCollectionChanged();\n    }\n\n    protected override void OnCollectionChanged(NotifyCollectionChangedEventArgs e)\n    {\n        if (!suppressOnCollectionChanged)\n            base.OnCollectionChanged(e);\n    }\n\n    public void NotifyCollectionChanged()\n    {\n        OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset));\n    }\n}	0
2313125	2312966	Add new column and data to datatable that already contains data - c#	//call SQL helper class to get initial data \nDataTable dt = sql.ExecuteDataTable("sp_MyProc");\n\ndt.Columns.Add("MyRow", typeof(System.Int32));\n\nforeach(DataRow dr in dt.Rows)\n{\n    //need to set value to MyRow column\n    dr["MyRow"] = 0;   // or set it to some other value\n}\n\n// possibly save your Dataset here, after setting all the new values	0
31677881	31677817	How can I start an exe file with an input parameter?	echo C:\...path\my.exe parameter > myapp.bat	0
29894848	29894727	Creating a DateTime using AutoMapper	Mapper.CreateMap<enquiryListEntry, EnquiriesListViewModel>()\n    .ForMember(dest => dest.flightDate, opt.MapFrom(src => new DateTime(src.flightYear, src.flightMonth, src.flightDay)));	0
8818564	8818443	What kind of date format is "401769" and how can I get this formatted like a real date?	DateTime.FromOADate(39316.262472303242)	0
25818796	25818722	Matching each char in strings	public static bool IsMatch(string pattern, string line)\n    {\n        var patternSplit = pattern.Split(',');\n        if (!line.StartsWith(patternSplit[0])) return false;\n        if(patternSplit.Count() > 2){\n           for (var i = 1; i < patternSplit.Count() - 1; i++)\n           {\n               if (!line.Contains(patternSplit[i])) return false;\n           }\n        }\n        if (!line.EndsWith(patternSplit[patternSplit.Count() - 1])) return false;\n        return true;\n    }\n\n\nstatic void Main(string[] args)\n        {\n            var matchingData = "quick brown fox jumped over a lazy dog";\n            var failingData = "I am batman";\n            var pattern = "qu,pe,ov,og";\n            if(IsMatch(pattern, matchingData))Console.WriteLine("{0} matches pattern {1}", pattern, matchingData);\n            if(!IsMatch(pattern, failingData)) Console.WriteLine("{0} does not match {1}", pattern, failingData);\n            Console.ReadKey();\n        }	0
24918691	24905239	NodaTime get Country Time based on CountryCode	// You should use dependency injection really - that makes the code much more\n// testable. Basically, you want an IClock...\nIClock clock = SystemClock.Instance;\n\nvar countryCode = "IN";\nvar location = TzdbDateTimeZoneSource.Default\n                 .FirstOrDefault(location => location.CountyCode == countryCode);\nif (location == null)\n{\n    // This is up to you - there's no location with your desired country code.\n}\nelse\n{\n    var zone = DateTimeZoneProviders.Tzdb[location.ZoneId];\n    var zonedNow = clock.Now.InZone(zone);\n    // Now do what you want with zonedNow... I'd avoid going back into BCL\n    // types, myself.\n}	0
29747089	29744251	No drop with basic gongsolution sample	public void DragOver(DropInfo dropInfo)\n{\n    dropInfo.Effects = System.Windows.DragDropEffects.Move;\n}	0
25479886	25479810	How to get value from list string?	var result = "1,red,2,blue,3,green,4,orange";\nvar arr=result.split(',');\nvar odd = jQuery.map( arr, function(n,i){\nreturn i%2 ? n : null;\n});\n\nvar even = jQuery.map( arr, function(n,i){\nreturn i%2 ? null : n;\n});	0
10065358	10065259	Connection string for MySQL database on webserver having shared IP address - C#	Server=91.215.159.xxx;Port=3306;Database=myDataBase;Uid=myUsername;Pwd=myPassword;	0
33809408	33808955	How to make sure that a action class parameter is not null	public override void OnActionExecuting(HttpActionContext actionContext)\n{\n    var parameterDescriptor = actionContext.ActionDescriptor.GetParameters().FirstOrDefault(x => typeof(CollectionFilterMapping).IsAssignableFrom(x.ParameterType));\n\n    if (parameterDescriptor != null && actionContext.ActionArguments[parameterDescriptor.ParameterName] == null)\n    {\n        actionContext.ActionArguments[parameterDescriptor.ParameterName] = Activator.CreateInstance(parameterDescriptor.ParameterType);\n    }\n\n    base.OnActionExecuting(actionContext);\n}	0
18615187	18614006	Implement block comment/uncomment in ScintillaNET control	private void commentBlockToolStripMenuItem_Click(object sender, EventArgs e)\n    {\n        if (txtSQL.Selection.Text.Length > 0)\n        {\n            Range range = txtSQL.Selection.Range;\n            int f = range.StartingLine.Number;\n            int t = range.EndingLine.Number;\n            for (int i = f; i <= t; i++)\n            {\n                txtSQL.InsertText(txtSQL.Lines[i].StartPosition,"--");\n            }\n            txtSQL.Selection.Start = txtSQL.Lines[f].StartPosition;\n            txtSQL.Selection.End = txtSQL.Lines[t].EndPosition;\n        }\n    }	0
31588953	31588678	Filtering a list in a list using linq	var fullList = BLogic.GetDataStoreCompaniesForFilterList();\nvar filterList = fullList\n  .Where(w => \n       w.Name.ToLower().StartsWith(filterString.ToLower()) || filterString.Length > 2 && \n       w.Vat.ToLower().Contains(filterString.ToLower()) || w.IndustryLang != null && \n       w.IndustryLang.Any(ww => \n           ww.LanguageId == usrX.LanguageId && \n           ww.Name.ToLower().Contains(filterString.ToLower()))\n   ).ToList();	0
778866	778678	How to change the color of progressbar in C# .NET 3.5?	public class NewProgressBar : ProgressBar\n{\n    public NewProgressBar()\n    {\n        this.SetStyle(ControlStyles.UserPaint, true);\n    }\n\n    protected override void OnPaint(PaintEventArgs e)\n    {\n        Rectangle rec = e.ClipRectangle;\n\n        rec.Width = (int)(rec.Width * ((double)Value / Maximum)) - 4;\n        if(ProgressBarRenderer.IsSupported)\n           ProgressBarRenderer.DrawHorizontalBar(e.Graphics, e.ClipRectangle);\n        rec.Height = rec.Height - 4;\n        e.Graphics.FillRectangle(Brushes.Red, 2, 2, rec.Width, rec.Height);\n    }\n}	0
13959161	13959098	SelectList for years	var selectList = \n    new SelectList(Enumerable.Range(2008, (DateTime.Now.Year - 2008) + 1));	0
10279278	10279177	How to compare, in C#, two lists of objects on one or more properties of these objects?	class Employee : IComparable\n    {\n       private string name;\n       public   string Name\n       {\n          get { return name; }\n          set { name = value ; }\n       }\n\n       public Employee( string a_name)\n       {\n          name = a_name;\n       }\n\n       #region IComparable Members\n       public   int CompareTo( object obj)\n       {\n         Employee temp = (Employee)obj;\n         if ( this.name.Length < temp.name.Length)\n           return -1;\n         else return 0;\n       }\n   }	0
12988266	12988260	How do I test if a bitwise enum contains any values from another bitwise enum in C#?	if((x & y) != 0) {...}	0
4567894	4567868	troubles declaring static enum, C#	public enum ProfileMenuBarTab { MainProfile, Edit, PhotoGallery }	0
11033769	11033444	Handle Mouse Right Button Double Click for Shape	private void OnMouseDownClickCount(object sender, MouseButtonEventArgs e)\n{\n    // Checks the number of clicks.\n    if (e.ClickCount == 1)\n    {\n        // Single Click occurred.\n        lblClickCount.Content = "Single Click";\n    }\n    if (e.ClickCount == 2)\n    {\n        // Double Click occurred.\n        lblClickCount.Content = "Double Click";\n    }\n    if (e.ClickCount >= 3)\n    {\n        // Triple Click occurred.\n        lblClickCount.Content = "Triple Click";\n    }\n}	0
1601640	1601609	How to check if a DateTime occurs today?	if (newsStory.WhenAdded.Date == DateTime.Today)\n{\n\n}\nelse\n{\n\n}	0
27725350	27723890	change color cells in datagridview programmaticly	protected override void OnLoad(EventArgs e) {\n  base.OnLoad(e);\n\n  // your DataGridView code here...\n}	0
18080972	18067992	Extend a model to add methods	// Note - needs to be in the same namespace as the auto-generated declaration\n\npublic partial class Foo\n{\n    // Add your own methods here, which can refer to the properties declared\n    // for the same type in the auto-generated code\n}	0
10453451	10453230	view Prepared Statement	var query = cmd.CommandText;\n\nforeach (var p in cmd.Parameters)\n{\n    query = query.Replace(p.ParameterName, p.Value.ToString());\n}	0
8984211	8971994	Ask for a password before restoring a minimized window	private const int WM_SYSCOMMAND = 0x0112; \n    private const int SC_MINIMIZE = 0xf020;\n    protected override void WndProc(ref Message m) \n    { \n        if (m.Msg == WM_SYSCOMMAND) \n        { \n            if (m.WParam.ToInt32() == SC_MINIMIZE) \n            { \n                m.Result = IntPtr.Zero; \n                panel1.Height = this.Height; // cover the whole form\n                panel1.Width = this.Width;\n                panel1.Visible = true; // make it visible\n            }\n        } \n        base.WndProc(ref m); \n    }	0
27572891	27572709	mongodb get all subdocuments from all documents	db.test.find({"customers.cart":"34323"})	0
22823092	22823031	List where Clause with Remove	MyGlobals.lstNewItems.RemoveAll(item => \n    item.sItemName == rows[i].Cells[0].Value.ToString()\n    && item.sType == "File");	0
32360664	32360543	How I can handling success logon with C#	SystemEvents.SessionSwitch += SystemEvents_SessionSwitch;\n        private void SystemEvents_SessionSwitch(object sender, SessionSwitchEventArgs e)\n        {\n            if(e.Reason==SessionSwitchReason.SessionLogon)\n            {\n\n            }\n        }	0
9383030	9382846	how to insert (C#) variables in xml	var str = new XElement("product", \n                    new XElement("name", pName), \n                    new XElement("price", pPrice))\n          .ToString();	0
23964313	23964273	Regex expression for full path	using System.IO;\nvar path = "";\nif (path == Path.GetFullPath(path) && Path.GetExtension(path) == ".exe")\n{\n    //We have a valid path.\n}	0
17465545	17465392	Compute occurrences of column data within a DataSet	DataRow[] rows= ds.Select("Teams = 'Boys'");\nConsole.WriteLine(rows.Length.ToString())	0
4691366	4691245	Allocating data in Array with same length string	char separator = ' ';\nint length = 10;\nvar splitted = paragraph.Split(separator);\nList<string[]> arrays = new List<string[]>();\nfor (int i = 0; i < splitted.Length / length + 1; i++)\n{\n    arrays.Add(splitted.Where((x, y) => y >= i * length && y < (i + 1) * length)\n        .Select( word => word + separator).ToArray());\n}\n\nforeach (var arr in arrays)\n{\n    foreach (var cell in arr)\n    {\n        Console.Write(cell);\n    }\n    Console.WriteLine();\n}	0
17340091	17339922	C# - How to write a List<List<string>> to CSV file?	List<List<String>> dataList = new List<List<string>>();\n//...\nconst char SEPARATOR = ",";\nusing (StreamWriter writer = new StreamWriter("file.csv"))\n{\n    dataList.ForEach(line =>\n    {\n        var lineArray = line.Select(c =>\n            c.Contains(SEPARATOR) ? c.Replace(SEPARATOR.ToString(), "\\" + SEPARATOR) : c).ToArray();\n        writer.WriteLine(string.Join(SEPARATOR, lineArray));\n    });\n}	0
10479048	10479033	Integer via TempData @ C# ASP.NET MVC3 EntityFramework	answer.QuestionId = (int)TempData["QuestionId"];	0
5333333	5333306	How to pass a variable through url and use it inside a controller	routes.MapRoute(\n   "RouteName",\n   "profiles/{action}/{userName}",\n   new { controller = "Profiles", action = "Details", userName = UrlParameter.Optional }\n);	0
468276	467951	Connecting two shapes together, Silverlight 2	var transform1 = shape1.TransformToVisual(shape1.Parent as UIElement);\nvar transform2 = shape2.TransformToVisual(shape2.Parent as UIElement);\n\nvar lineGeometry = new LineGeometry()\n{\n  StartPoint = transform1.Transform(new Point(shape1.ActualWidth / 2, shape1.ActualHeight / 2.0)),\n  EndPoint = transform2.Transform(new Point(shape2.ActualWidth / 2.0,    shape2.ActualHeight / 2.0))\n};\n\nvar path = new Path()\n{\nData = lineGeometry\n};	0
25124922	25124740	DataGrid DataTable binding - Get selected DataTable row index	dataGrid\n  .SelectedItems\n  .Cast<DataRowView>()\n  .Select(view => dataTable.Rows.IndexOf(view.Row));	0
4939012	4938715	Using Reflection for finding deprecation	class TestClass\n{\n    public TestClass()\n    {\n        DeprecatedTester.FindDeprecatedMethods(this.GetType());\n    }\n\n    [Obsolete("SomeDeprecatedMethod is deprecated, use SomeNewMethod instead.")]\n    public void SomeDeprecatedMethod() { }\n\n    [Obsolete("YetAnotherDeprecatedMethod is deprecated, use SomeNewMethod instead.")]\n    public void YetAnotherDeprecatedMethod() { }\n\n    public void SomeNewMethod() { }        \n}\n\npublic class DeprecatedTester\n{\n    public static void FindDeprecatedMethods(Type t)\n    {\n        MethodInfo[] methodInfos = t.GetMethods();\n\n        foreach (MethodInfo methodInfo in methodInfos)\n        {\n            object[] attributes = methodInfo.GetCustomAttributes(false);\n\n            foreach (ObsoleteAttribute attribute in attributes.OfType<ObsoleteAttribute>())\n            {\n                Console.WriteLine("Found deprecated method: {0} [{1}]", methodInfo.Name, attribute.Message);\n            }\n        }\n    }\n}	0
28444151	28443475	.NET vs Mono: different results for conversion from 2^32 as double to int	" Conversion from floating-point numbers to integer values truncates the number toward zero. When converting from a float64 to a float32, precision can be lost. If value is too large to fit in a float32 (F), positive infinity (if value is positive) or negative infinity (if value is negative) is returned. If overflow occurs converting one integer type to another, the high order bits are truncated"	0
19266307	19266207	Constraining T to a common generic property	public interface IEntity<T>\n{\n    T Data { get; set; }\n}	0
21555021	21517322	How to ignore null values in JSON response from asmx	public class MyCustomClassObject \n{\n    public Dictionary<string, object> Foo { get; set; }\n\n    public MyCustomClassObject()\n    {\n        this.Foo = new Dictionary<string, object>();\n    }\n\n}\n\npublic MyCustomClassObject GetTestData()\n{\n    MyCustomClassObject x = new MyCustomClassObject();\n    x.Foo.Add("PropertyA", 2);\n    x.Foo.Add("PropertyC", "3");\n    return x.Foo;\n}	0
23265675	23255322	Clear all TextBox in Window	static public void TraverseVisualTree(Visual myMainWindow)\n    {\n        int childrenCount = VisualTreeHelper.GetChildrenCount(myMainWindow);\n        for (int i = 0; i < childrenCount; i++)\n        {\n            var visualChild = (Visual)VisualTreeHelper.GetChild(myMainWindow, i);\n            if (visualChild is TextBox)\n            {\n                TextBox tb = (TextBox)visualChild;\n                tb.Clear();\n            }\n            TraverseVisualTree(visualChild);\n        }\n    }	0
30580217	30579906	link button on Master Page with Click Event on Content Page Stack-overflow Exception	myLink = value	0
19783714	19783461	Regarding the use virtual keyword for a property	public class User\n{\n   public int ID { get; set; }\n   public virtual Role Role { get; set; }\n}\npublic class Role\n{\n   public int ID { get; set; }\n   public string Name { get; set; }\n   public virtual List<User> UsersInRole { get; set; }\n}	0
23169498	23169330	Bind a List<string> to a TextBox	public MainWindow()\n    {\n        InitializeComponent();\n        fileNames = new List<string>();\n        this.tb_files.DataContext = this;\n    }	0
6603093	6598607	Interfacing with TomTom device (Display devices screen on computer)	cat /dev/fb > /mnt/sdcard/screenshot.raw	0
24518392	24518335	how can i make a button invisible for some users in c#?	bool userIsPermitted = GetUserPermission(currentuser);\nInitializeControls(userIsPermitted);\n\n...\n\nInitializeControls(bool isAllowedToUseControls)\n{\n   button1.Visibility = isAllowedToUseControls;\n   button1.Enabled = isAllowedToUseControls;\n}	0
22933641	22932974	How do I check if Property X of a COM object has value Y in C#?	object is ContactItem	0
31284536	31284103	Winform clone DataGridViewRow along with DataBoundItem	var currentCell = dgv.CurrentCell;\nvar bs = (BindingSource)dgv.DataSource;\nvar data = (List<A>)bs.DataSource;\nvar currentSelection = (A)row.DataBoundItem;\ndata.Add(currentSelection);\n\nbs.ResetBindings(false); // This should refresh the grid\ndgv.CurrentCell = currentCell; // Put back the current cell	0
12572824	12570443	How can I change row colors of WPF Datagrid based on a cell value taken from a Dictionary using an MVVM model?	{Binding Path=DataContext.ColumnName, \n         RelativeSource={RelativeSource AncestorType=Window}}	0
2408497	2408485	LINQ-to-SQL: Searching against a CSV	var geographyMatches = from cg in db.ContactGeographies\n                               where geographyList.Contains(cg.GeographyId)\n                               select new { cg.ContactId };	0
18869785	18868856	Counting no. of filled rows in Access Db	string ConnectionString = @"Provider=Microsoft.ACE.OLEDB.12.0" + ";Data Source=" + ResultFilePath + ";Persist Security Info=False";	0
16322071	16321759	Model Tracking In Entity Framework	var items = context.Foo.AsNoTracking();	0
26035804	26035449	Get relative path of XML File located in another project but Same Solution	XDocument.Load("../../../../../ABC.Data/ABC.Data/AA.xml");	0
22465436	22436284	Parsing multi-part message, body only	string.Format ("Content-Type: multipart/mixed; boundary=\"{0}\"\r\n", boundary);	0
3293890	3292997	Mapping a Private Field in NHibernate (with Fluent NH)	HasMany(x => x.Products).KeyColumn("ProductId")\n    .AsBag().Inverse()\n    .Access.CamelCaseField(Prefix.Underscore);\n    // plus cascade options if desired	0
594643	594230	Wait for two threads to finish	Forker p = new Forker();\np.Fork(delegate { DoSomeWork(); });\np.Fork(delegate { DoSomeOtherWork(); });\np.Join();	0
6062554	6062527	How to kill Thread on exit?	Thread t = new Thread(Main.MyThread);\nt.IsBackground = true;\nt.Start();	0
5645820	5645784	Date input Regex	(((((0[1-9])|(1\d)|(2[0-8]))((0[1-9])|(1[0-2])))|((31((0[13578])|(1[02])))|((29|30)((0[1,3-9])|(1[0-2])))))((20[0-9][0-9])|(19[0-9][0-9])))|((2902(19|20)(([02468][048])|([13579][26]))))	0
6858870	6858838	Define two methods with same parameter type	Department GetDepartmentByName(...)\n\nDepartment GetDepartmentByEmployeeID(...)	0
33153895	33135886	C# Drawing multiple charts in real time in a separate thread	lock (_bufferRawData) {\n        for (int sampleIdx = 0; sampleIdx < e.rawData.Length; sampleIdx++)\n        {\n           // Append data\n           _bufferRawData.Add(e.rawData[sampleIdx]);\n           _bufferXValues.Add(DateTime.Now);\n        }\n    }	0
9601339	9600833	Regex.Split adding empty strings to result array	var matches = Regex.Matches(removedSpaces, @"(\w+|[&!|()])");\n\nforeach (var match in matches)\n    Console.Write("'{0}', ", match); // '!', '(', 'LIONV6', '|', 'NOT_superCHARGED', ')', '&', 'RHD',	0
19053084	19053047	List<string> emailAddress how to replace value in a particular string	email = email.Replace(";", ",");	0
2069479	2069449	Implementing XOR in a simple image encryption method	ImageBytes[i] = (byte)(ImageBytes[i] ^ 5);	0
20396706	20396248	ASP.NET Web Api custom parameter name	public string Get()\n{\n  var query = HttpContext.Current.Request.QueryString;\n\n   //Parse the parameter out of the query-variable\n\n}	0
21546397	21542987	Removing Line Separator between two cells in DataGridView	dataGridView1.EnableHeadersVisualStyles = false;\n        Rectangle headerRect = this.dataGridView1.GetCellDisplayRectangle(dataGridView1.Columns["phone"].Index, -1, true); //get the column header cell\n        headerRect.X = headerRect.X + headerRect.Width-2;\n        headerRect.Y += 1;\n        headerRect.Width = 2*2;\n        headerRect.Height -= 2;\n        DataGridViewColumn dataGridViewColumn = dataGridView1.Columns["<Column>"];\n        Color cl; \n        cl = dataGridView1.ColumnHeadersDefaultCellStyle.BackColor;\n        e.Graphics.FillRectangle(new SolidBrush(cl), headerRect);	0
34181388	34181296	Checking for a word inside a string	// Add other punctuation if need \nvar array = str.Split(" ,;.".ToCharArray(), StringSplitOptions.RemoveEmptyEntries) ;\nbool containsWord = array.Any(s => s.Equals("hi", StringComparison.InvariantCultureIgnoreCase));	0
15465990	15465070	How to add values per character in c#?	using System;\nusing System.Windows.Forms;\nnamespace WindowsFormsApplication6\n{\n    public partial class Form1 : Form\n    {\n        public Form1()\n        {\n            InitializeComponent();\n        }\n        int amount;\n        private void textBox1_TextChanged(object sender, EventArgs e)\n        {\n            amount = 5;\n            amount = amount + textBox1.Text.Length;            \n            label1.Text = amount.ToString();\n        }\n    }\n}	0
25805275	25805164	Binding XML data to Model in C# MVC	var person = from a in xml.Descendants("person")\n              select new People \n              {\n                Name = a.Element("name").Value,\n                Age = a.Element("age").Value,\n                Hobby = a.Descendants("hobby")\n                          .Select(x=> new Hobbies\n                                       {\n                                         Title =x.Element("title").Value,\n                                         Description = x.Element("description").Value\n                                       }).ToList()\n               };	0
752211	752191	LINQ to SQL - No Add method available	db.PageHits.InsertOnSubmit(hit);	0
27541067	27540826	How to format text loaded from file?	sText = @File.ReadAllText("template.htm"));\nformated = sText.Replace("{0}", "Add some additional text here");	0
9099081	9099021	How to make a documentation for a function which has an IDictionary<TKey, TValue> parameter?	/// <param name="listMap">List map parameter representing xxx. The keys in the dictionary are XXX and the values are YYY</param>	0
16588451	16588338	C# is there a way to use a method like a constructor	List<MyClass> myClass = new List<MyClass>();\nMyClass myClassInstance = new MyClass();\nmyClass = myClassInstance.Query("data.xml");\nmyClassInstance.Assign(myClass, i);	0
28083949	28083585	Loop trought Dictionary<string, object> only for a key in c#	[TestMethod]\n    public void test()\n    {\n        string json = "{\"labels\" : [{\"id\" : \"1\",\"descrizione\" : \"Etichetta interna\",\"tipo\" : \"0\",\"template_file\" : \"et_int.txt\"}, {\"id\" : \"2\",\"descrizione\" : \"Etichetta esterna\",\"tipo\" : \"1\",\"template_file\" : \"et_ext.txt\"}],\"0\" : 200,\"error\" : false,\"status\" : 200}";\n        var root = JsonConvert.DeserializeObject<Rootobject>(json);\n\n        foreach (var label in root.Labels)\n        {\n            //Use label.Id, label.Descrizione, label.Tipo, label.TemplateFile\n        }\n    }\n\n    public class Rootobject\n    {\n        public Label[] Labels { get; set; }\n        public int _0 { get; set; }\n        public bool Error { get; set; }\n        public int Status { get; set; }\n    }\n\n    public class Label\n    {\n        public string Id { get; set; }\n        public string Descrizione { get; set; }\n        public string Tipo { get; set; }\n        public string TemplateFile { get; set; }\n    }	0
15535152	15534878	Color excel cells using winforms	for (int i = 0; i < row; i++)\n{   \n     for (int j = 0; j < col; j++)\n     {\n        Range range = worksheet.Cells[i + 2, j + 1];\n        range.Interior.Color = buttons[i][j].BackColor.ToArgb();\n     }\n}	0
18096875	18096833	Run exe from its folder	file:///	0
29017580	29017465	Unpredictable results using sendkeys with capslock	[DllImport("kernel32.dll", CharSet = CharSet.Auto,SetLastError = true)]\nstatic extern EXECUTION_STATE SetThreadExecutionState(EXECUTION_STATE esFlags);\n\n[FlagsAttribute]\npublic enum EXECUTION_STATE :uint\n{\n     ES_AWAYMODE_REQUIRED = 0x00000040,\n     ES_CONTINUOUS = 0x80000000,\n     ES_DISPLAY_REQUIRED = 0x00000002,\n     ES_SYSTEM_REQUIRED = 0x00000001\n     // Legacy flag, should not be used.\n     // ES_USER_PRESENT = 0x00000004\n}	0
32735621	32735377	Sitecore: Save date in sitecore field with type="DateTime" from <Input type="text">	var dateTime = DateTime.Parse(dateFrom.Value);\nvar isoDate = DateUtil.ToIsoDate(dateTime);\nitem["Visible From"] = isoDate ;	0
6990558	5577223	How to generate a 'dynamic' member by codedom?	CodeMemberField dynamicMember = new CodeMemberField ( );\ndynamicMember.Name = dynamicMemberName;\ndynamicMember.Attributes = MemberAttributes.Private;\ndynamicMember.Type = new CodeTypeReference ( "dynamic" );\noperationCodeType.Members.Add ( dynamicMember );	0
24100880	24100482	C# check if a string is a valid WebProxy format	var ValidIpAddressPortRegex = @"^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5]):[\d]+$";\nif (System.Text.RegularExpressions.Regex.IsMatch(proxy_string_to_validate, ValidIpAddressPortRegex ))\n{\n    do_stuff_with_proxy();\n}\nelse\n{\n    //MessageBox.Show("IP:PORT url not valid!","Information");\n}	0
6362406	6362315	SQL statement to get data from a week back?	WHERE  DATEDIFF(day,  People.lastmodified, GETDATE()) <= 7	0
3459323	3459230	Dynamic Variable Name Use in C# for WinForms	for(...)\n{\n     CheckBox c = this.Controls["chkCategory" + i.ToString()] as CheckBox ;\n\n     c.Text = categories[i];  \n}	0
6568886	6568875	Regex: How to get filename without leading numbers?	Regex rgx = new Regex("^[0-9]*");\nstring s = rgx.Replace("413_somename.suffix", "");	0
12473100	12471463	Find adjacent elements in a 2D matrix	public static IEnumerable<T> AdjacentElements<T>(T[,] arr, int row, int column)\n{\n    int rows = arr.GetLength(0);\n    int columns = arr.GetLength(1);\n\n    for (int j = row - 1; j <= row + 1; j++)\n        for (int i = column - 1; i <= column + 1; i++)\n            if (i >= 0 && j >= 0 && i < columns && j < rows && !(j == row && i == column))\n                yield return arr[j, i];\n}\n\n...\n\nvar arr = new[,] { {1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12} };\n\nvar results = AdjacentElements(arr, 1, 3);\n\nforeach(var result in results) \n    Console.WriteLine(result)	0
5805228	5805106	Hashing multiple byte[]'s together into a single hash with C#?	MD5 md5 = new MD5CryptoServiceProvider();\n\n// For each block:\nmd5.TransformBlock(block, 0, block.Length, block, 0);\n\n// For last block:\nmd5.TransformFinalBlock(block, 0, block.Length);\n\n// Get the hash code\nbyte[] hash = md5.Hash;	0
24311178	24311040	Take results of stored procedure and use in SQL query in my code behind	CREATE TABLE #spResults\n(col1, col2, col3..)\n\nINSERT INTO #spResults\nEXEC sprocName(@Param)\n\nSELECT * FROM MyTable JOIN #spResults ON <Cond>	0
3787280	3787137	Change image source in code behind - Wpf	ImageViewer1.Source = new BitmapImage(new Uri(@"\myserver\folder1\Customer Data\sample.png"));	0
8057101	8057042	Where is the public properties of a asp.net web control saved?	//stores it in memory\npublic string name {get;set;} \n\n//viewstate backed property, preserved on postback when viewstate is enabled\npublic string name {\n    get\n    {\n        return (string)ViewState["name "] ?? String.Empty; //default value\n    }\n    set\n    {\n        ViewState["name "] = value;\n    }\n}	0
25383727	25383309	Using Radio Button in GridView	protected void Button1_Click(object sender, EventArgs e)\n{\nforeach (GridViewRow gvr in GridView1.Rows)\n   {\n    RadioButton rb = (RadioButton)gvr.FindControl("RadioButton1");\n\n    if (rb.Checked)\n    {\n        HiddenField hf = (HiddenField)gvr.FindControl("HiddenField1");\n        Response.Write(rb.Text.ToString() + "<br />" + hf.Value.ToString());\n    }\n    else\n    {\n        Response.Write("empty<br />");\n    }\n}\n}	0
13013562	13012497	Query PrincipalSearcher for containing multiple strings	var groups = new List<string>();\nPrincipalContext ctx = new PrincipalContext(ContextType.Domain);\nGroupPrincipal qbeGroup = new GroupPrincipal(ctx);\nPrincipalSearcher srch = new PrincipalSearcher(qbeGroup);\n    foreach (var group in srch.FindAll())\n    {\n       if (group.Name.Contains("Administrators") || group.Name.Contains("Users"))\n       {\n             groups.Add(group.Name);\n       }\n    }\nreturn groups.ToArray();	0
8193339	8187035	Issue Registering x64 Assemblies for COM Interop	var type = Type.GetTypeFromProgID("ProgID.Interop.5683");\nvar obj = Activator.CreateInstance(type);	0
32340137	32339283	WebApi get the post raw body inside a filter	public class MyAttribute:ActionFilterAttribute\n{\n    public override void OnActionExecuted(HttpActionContext actionContext)\n    {\n        string rawRequest;\n        using (var stream = new StreamReader(actionContext.Request.Content.ReadAsStreamAsync().Result))\n        {\n            stream.BaseStream.Position = 0;\n            rawRequest = stream.ReadToEnd();\n        }\n    }\n}	0
22224953	22224412	how to create nested node C#	foreach (DataRow dr in dt.Rows) {}	0
9477462	9477376	Passing a variable from server side to javascript	btnAdd.Attributes.Add("onclick", "OpenAttachmentUpload('" + ID + "')");	0
10458665	10458629	How do I fix this function so that I can input a List of any class	private static void CopyObjList<T>(List<T> Group, List<T> AddGroup)\n{\n      Group.AddRange(AddGroup);\n}	0
23799192	23797833	EF6 - using Contains with a list	var recipes = db.Recipes\n    .Where(r => r.Ingredients.All(i => ingredients.Contains(i.PropertyNameToMatch));	0
15682773	15681880	c# Extend base class' method	class BetList : List<Bet>\n{\n    public uint Sum \n    { \n        get { return this.Count > 0 ? this.Sum(bet => bet.Amount) : 0; }\n    }\n}	0
20886616	20006346	Windows Phone 8 WebBrowser does not load local file, if there are get parameters	browser.Navigate(new Uri("www/index.html#p=123&p2=567", UriKind.Relative));	0
10820603	10819500	Only allow the newest instance of my application to execute?	Process[] processes = Process.GetProcesses();\nstring thisProcess = Process.GetCurrentProcess().MainModule.FileName;\nstring thisProcessName = Process.GetCurrentProcess().ProcessName;\nforeach (var process in processes)\n{\n    // Compare process name, this will weed out most processes\n    if (thisProcessName.CompareTo(process.ProcessName) != 0) continue;\n    // Check the file name of the processes main module\n    if (thisProcess.CompareTo(process.MainModule.FileName) != 0) continue;\n    if (Process.GetCurrentProcess().Id == process.Id) \n    {\n        // We don't want to commit suicide\n        continue;\n    }\n\n    // Tell the other instance to die\n    process.CloseMainWindow();\n}	0
23021515	23021457	SignalR - Server side method to detect if a client disconnects from a hub?	public override Task OnConnected()\n{\n    return base.OnConnected();\n}\n\npublic override Task OnDisconnected()\n{\n    //custom logic here\n    return base.OnDisconnected();\n}\n\npublic override Task OnReconnected()\n{\n    return base.OnReconnected();\n}	0
7708243	7708082	Dictionary with Arbitrary Tuple for Key (Without Wrapping in a Class)	public class TupleDictionary<T1, T2, TValue> : Dictionary<Tuple<T1,T2>,TValue>\n{\n    public TValue this[T1 t1, T2 t2]\n    {\n        get { return this[new Tuple<T1, T2>(t1, t2)]; }\n        set { this[new Tuple<T1, T2>(t1,t2)] = value; }\n    }\n\n    public void Add(T1 t1, T2 t2, TValue value)\n    {\n        Add(new Tuple<T1, T2>(t1, t2), value);\n    }\n\n    public void Remove(T1 t1, T2 t2)\n    {\n        Remove(new Tuple<T1, T2>(t1, t2));\n    }\n\n    public bool ContainsKey(T1 t1, T2 t2)\n    {\n        return ContainsKey(new Tuple<T1, T2>(t1, t2));\n    }\n\n    public bool TryGetValue(T1 t1, T2 t2, out TValue value)\n    {\n        return TryGetValue(new Tuple<T1, T2>(t1, t2), out value);\n    }\n}	0
20634747	20634145	How to remove contextmenu items from gecko webbrowser control,"i want to disable view source in browser"	private void geckoWebBrowser1_ShowContextMenu(object sender, GeckoContextMenuEventArgs e)\n  {      \n   foreach(MenuItem i in e.ContextMenu.MenuItems)      \n   {\n     if(i.Text == "View in System Browser")\n        e.ContextMenu.MenuItems.Remove(i);\n   }\n}	0
14476978	14476036	Run a delegate asynchronously in Windows Phone	Task ts = Task.Factory.StartNew(() => myAction(myString));	0
19027216	19026919	Is correct to place a switch-block inside another one?	switch(cmdName + "-" + cmdValue)\n{\n    case "getShapefile-buildings":\n        HandleShapeFile(ref shapfile);\n    break;\n}	0
14369509	14369401	Associate a keypress event with a event handler in a array of textboxes	tb[i].KeyPress += new System.Windows.Forms.KeyPressEventHandler(textBoxP_KeyPress);	0
28806838	28806704	How to reload the xml file created into the datagridview	private static void CopyValuesFromDataTableToXml(string fileName, DataTable table)\n    {\n        XmlDocument doc = new XmlDocument();\n        doc.Load(fileName);\n        foreach (DataRow row in table.Rows)\n        {\n            string name = (string)row["Name"];\n            //fish out the element out of the xml\n            XmlElement element = doc.SelectSingleNode(string.Format("//data[@name='{0}']", name)) as XmlElement;\n            //set value\n            element.SelectSingleNode("./value").InnerText = (string)row["Value"];\n            //set comment\n            element.SelectSingleNode("./comment").InnerText = \n                string.Format(\n                "[Font]{0}[/Font][DateStamp]{1}[/DateStamp][Comment]{2}[/Comment]",\n                row["Font"],\n                row["DateStamp"],\n                row["Comment"]);\n        }\n\n        //here would belong the code to update the version\n\n        doc.Save(fileName);\n    }	0
9495306	9495277	MVC route with default action and parameter, several actions by controller	routes.MapRoute(\n            "DefaultIndex", // Route name\n            "portfolio/{id}", // URL with parameters\n            new { controller="portfolio", action = "Index", id = UrlParameter.Optional }\n        );	0
9040004	9039861	Linq Nhibernate : Unable to pull a value from a foreign key table	var computerFonts = FontColors.AsEnumerable().Select(f =>\nnew ComputerFontColors\n{\n  FontColor = f.Color,\n  FontName = f.Fonts.Name,\n  ComputerUsedOn = ComputerServices.GetByFontId(f.Fonts.Id)\n});	0
30343047	30341000	Intergrating life of player in each level in unity	DontDestroyOnload(this);	0
214167	214065	Capturing key press messages	protected override bool ProcessCmdKey(ref Message msg, Keys keyData)\n{\n    const int WM_KEYDOWN = 0x100;\n    const int WM_SYSKEYDOWN = 0x104;\n\n    if ((msg.Msg == WM_KEYDOWN) || (msg.Msg == WM_SYSKEYDOWN))\n    {\n        switch (keyData)\n        {\n            case Keys.Down:\n                this.Text = "Down Arrow Captured";\n                break;\n\n            case Keys.Up:\n                this.Text = "Up Arrow Captured";\n                break;\n\n            case Keys.Tab:\n                this.Text = "Tab Key Captured";\n                break;\n\n            case Keys.Control | Keys.M:\n                this.Text = "<CTRL> + M Captured";\n                break;\n\n            case Keys.Alt | Keys.Z:\n                this.Text = "<ALT> + Z Captured";\n                break;\n        }\n    }\n\n    return base.ProcessCmdKey(ref msg, keyData);\n}	0
1982808	1982603	What's the right way to append a ToolButton to a Toolbar in Gtk?	myToolBar.Insert (myToolItem, myToolBar.NItems);	0
27122811	27122202	C# Regex to grab 2 pieces of info from each HTML TR element - located inside different TD elements	/(?:<strong\b[^>]*>(?<name>.*?)<\/strong>|MySpecialAction\?.*?list=(?<id>[^&"]+))/	0
1156366	1156346	using LINQ to XML to query inner xml of child nodes	var rootElement = XElement.Parse(xml);\n            var results = rootElement.\n               .Elements()\n               .Where( e => e.Attribute("name") == "photo" )\n               .SelectMany( e => e.Elements )\n               .Select( e => e.Value );	0
2237476	2237460	Install program that has to be run as administrator	Process.StartInfo.UseShellExecute = true;\nProcess.StartInfo.Verb = "runas";	0
5837753	5837735	How to tell the difference between an HtmlGenericControl that is a DIV and one that is a UL?	foreach (Control c in myControl.Controls)\n    {\n        if(c.GetType().Equals(typeof(HtmlGenericControl)) &&\n           string.Equals((HtmlGenericControl)c).TagName, "div", StringComparison.OrdinalIgnoreCase)\n        {\n            //do something\n        }\n    }	0
27673856	27673759	WinRT Progress Indicator implement 500ms wait to prevent flickering	var delay = Task.Delay(5000).ContinueWith(e =>	0
16547617	16547050	Delete non-empty worksheets from excel workbook	app.DisplayAlerts = false;\n    foreach (var item in _view.Sheets)\n    {\n        Exc.Worksheet ws = wb.Worksheets[item.Name];\n        if (!item.Include)\n        {\n            ws.Delete();\n        }\n    }\n    app.DisplayAlerts = true;	0
32113373	32112894	LINQ - GroupBy Item and filter based on two Properties	var filteredquery = query\n                           .GroupBy(x => x.Id)\n                           .Select(chunk => chunk\n                               .OrderByDescending(item => item.MajorV)\n                               .ThenByDescending(item => item.MinorV)\n                               .First())\n                           .ToList();	0
12793680	12787985	How to call an asmx service which needs authorization from WCF in .NET 3.5	public decimal ReportSales()\n{\n    var currentUser = new WindowsPrincipal((WindowsIdentity)\n    System.Threading.Thread.CurrentPrincipal.Identity);\n    if (currentUser.IsInRole(WindowsBuiltInRole.BackupOperator))\n    {\n        return 10000M;\n    }\n    else\n    {\n       return -1M;\n    }\n }	0
26018902	26018626	Clean algorithm to generate all sets of the kind (0) to (0,1,2,3,4,5,6,7,8,9)	static IEnumerable<T[]> CombinationsAnyLength<T>(params T[] values)\n{\n    Stack<int> stack = new Stack<int>(values.Length);\n    int i = 0;\n    while (stack.Count > 0 || i < values.Length) {\n        if (i < values.Length) {\n            stack.Push(i++);\n            int c = stack.Count;\n            T[] result = new T[c];\n            foreach (var index in stack) result[--c] = values[index];\n            yield return result;\n        } else {\n            i = stack.Pop() + 1;\n            if (stack.Count > 0) i = stack.Pop() + 1;\n        }\n    }\n}\n\nCombinationsAnyLength(1, 2, 3, 4) outputs:	0
27633547	27527550	How to get a active file/Application Complete path with file Extension	public static string GetMainModuleFilepath(int processId)\n    {\n        string wmiQueryString = "SELECT * FROM Win32_Process WHERE ProcessId = " + processId;\n        using (var searcher = new ManagementObjectSearcher(wmiQueryString))\n        {\n            using (var results = searcher.Get())\n            {\n                ManagementObject mo = results.Cast<ManagementObject>().FirstOrDefault();\n                if (mo != null)\n                {\n                    return (string)mo["CommandLine"];\n                }\n            }\n        }\n        Process testProcess = Process.GetProcessById(processId);\n        return null;\n    }	0
17834886	17834522	to show a set of value in list box	while (await statement.StepAsync())\n{\n    mylist1.Items.Add(statement.Columns["Name"]);\n}	0
2679237	2675715	Parsing an Open XML doc via styled blocks	.//w:p\n./w:pPr\n./w:pStyle	0
4714900	4714615	How to work with the console via MyApp?	Process myProcess = new Process();\n    //All the process code here\n    myProcess.Start();\n\n    myProcess.StandardOutput.ReadToEnd();	0
12321151	12321069	Creating a unique URL safe hash	public static string EncodeBase36(int i)\n{\n  Contract.Requires<ArgumentException>(i>=0);\n  //Base conversion\n  string s="";\n  while(i!=0)\n  {\n    int digit = i % 36;\n    i/=36;\n    if(digit<10)\n      s=((char)('0'+digit)).ToString()+s;\n    else\n      s=((char)('a'+digit-10)).ToString()+s;\n  }\n  // Enforce minimum length\n  while(s.Length<3)\n  {\n    s = "0" + s;\n  }\n  return s;\n}	0
3987217	3987150	Sorted dataview to datatable	private DataTable getSortedTable(DataTable dt)\n {\n    dt.DefaultView.Sort = "columnName DESC";\n    return dt.DefaultView.ToTable();\n  }	0
19261325	19260921	How do I add a service reference to a C# library?	EndpointAddress address = new EndpointAddress("http://serviceEndpointUri");\n    BasicHttpBinding binding = new BasicHttpBinding();\n\n    using (ReferenceServiceClient client = new ReferenceServiceClient(binding, address))\n    {\n        ...\n    }	0
21219402	21218716	Storing Data in SQLite	// It's not clear what cateName is, but I'll assume *that* bit is valid...\nstring sql = new SQLiteCommand("insert into " + cateName +\n     " (Name, DateCreated, Reminder, Content) values " +\n     "(@Name, @DateCreated, @Reminder, @Content);\n\nusing (var command = new SQLiteCommand(sql, connection))\n{\n    command.Parameters.Add("@Name", SQLiteType.Text).Value = noteName;\n    command.Parameters.Add("@DateCreated", SQLiteType.DateTime).Value = currentDate;\n    command.Parameters.Add("@Reminder", SQLiteType.Text).Value = reminder;\n    command.Parameters.Add("@Content", SQLiteType.Text).Value = content;\n    command.ExecuteNonQuery();\n}	0
5792221	5791917	How to consolidate results from multiple IEnumerable<T> using LINQ	// You can construct this with an array if it isn't already in this form.\nIEnumerable<IEnumerable<ResortSupplier>> supplierLists = ...\n\nvar query = from suppliers in supplierLists\n            from supplier in suppliers\n            group supplier by supplier.SupplierCode into g\n\n            let products = g.SelectMany(s => s.ResortProducts)\n                            .GroupBy(p => p.Code)\n                            .Select(prodGroup => new Product\n                                    {\n                                       Code = prodGroup.Key,\n                                       PricingDetail = prodGroup\n                                                       .SelectMany(p => p.PricingDetail)\n                                                       .ToList()\n                                    })\n\n            select new ResortSupplier\n            {\n                SupplierCode  = g.Key, \n                ResortProducts = products.ToList()                              \n            };	0
25710319	25710066	How to identify whether List<T> is a list of Ts that implement a specific interface	var movie = new Movie() { ... };\n\nforeach (var prop in typeof(Movie).GetProperties())\n{\n    if (prop.PropertyType.IsGenericType && \n        prop.PropertyType.GetGenericTypeDefinition() == typeof (List<>))\n    {\n        /* Get the generic type parameter of the List<> we're working with: */\n        Type genericArg = prop.PropertyType.GetGenericArguments()[0];\n\n        /* If this is a List of something derived from IMedia: */\n        if (typeof(IMedia).IsAssignableFrom(genericArg))\n        {\n            var enumerable = (IEnumerable)prop.GetValue(movie);\n\n            List<IMedia> media = \n                enumerable != null ? \n                enumerable.Cast<IMedia>().ToList() : null;\n\n            // where DoSomething takes a List<IMedia>\n            DoSomething(media);\n        }\n    }\n}	0
5766607	5766574	Start A Process With Parameters	string username = "MyUsername";\nProcess.Start(Path.Combine("MyExe.exe" + " \"" + username + "\"");	0
20671367	20671346	Why adding data to datagridview with bindingsource from dataset is blank?	dt1.Rows.Add(dr1);	0
26733624	26571057	Extract ZipFile Using C# With Progress Report	/*...*/\nusing (ZipFile zip = ZipFile.Read(ROBOT_INSTALL_SPECIAL))\n        {\n            zip.ExtractProgress += \n               new EventHandler<ExtractProgressEventArgs>(zip_ExtractProgress);\n            zip.ExtractAll(ROBOT0007, ExtractExistingFileAction.OverwriteSilently);\n\n        }\n/*...*/\n\nvoid zip_ExtractProgress(object sender, ExtractProgressEventArgs e)\n{\n   if (e.TotalBytesToTransfer > 0)\n   {\n      progressBar1.Value = Convert.ToInt32(100 * e.BytesTransferred / e.TotalBytesToTransfer);\n   }\n}	0
13234983	13234447	Datetime check in Linq where statement	var pcPageList = db.PcPages\n      .Where(m => m.Quarter == exactQuarter && m.Url == pageUrl)\n      // You may need to materialize the results of the query at this point\n      //   or use Convert.ToDateTime(...) instead of ToDateTime()\n      .Select(m => new { Row = m, UpdatedOn = m.UpdatedOn.ToDateTime() })\n      .Where(a => a.UpdatedOn.Month == 11 && a.UpdatedOn.Day == 2)\n      .Select(a => a.Row)\n      .OrderBy(m => m.UpdatedOn)\n      .FirstOrDefault();	0
31740711	31740550	How to retrieve an installed file path from Registry	var regView = Environment.Is64BitOperatingSystem ? RegistryView.Registry64 : RegistryView.Registry32;\n    var registry = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, regView);\n\n    var keyPath = @"HKEY_LOCAL_MACHINE\SOFTWARE\Bentley\AutoPIPE\V8i SELECTSeries 6 Ribbon Preview and Reporting\RibbonUI.xml";\n    var key = registry.OpenSubKey(keyPath);	0
18206831	18172543	Xml.Serializer illegal cast exception in C++ ActiveX control hosted in C# .Net 4.0 Application	MyClass* obj = static_cast<MyClass*>(serializer->Deserialize(reader));	0
1602661	1602652	Accessing a Static Method in C#	CsvWriter.Writer.WriteLine	0
1520305	1519358	When to use Factory method pattern?	public ITax BuildNewSalesTax()\npublic ITax BuildNewValueAddedTax()	0
8891729	8891545	How can i set the properties of button kept in the item template of DataList on run time?	void Item_Bound(Object sender, DataListItemEventArgs e)\n  {\n\n    if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)\n    {\n       // Retrieve the Button control in the current DataListItem.\n       Button btn = (Button)e.Item.FindControl("ItemBtn");\n\n       //Then set the buttons properties over here\n     }\n   }	0
7006227	7006128	TreeView multilevel custom template with buttons	public class TreeViewItemToLevelConverter : IValueConverter\n{\n    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)\n    {\n        if (!(value is DependencyObject))\n            return 0;\n\n        return findLevel(value as DependencyObject, -1);\n    }\n\n    private int findLevel(DependencyObject tvi, int level)\n    {\n        DependencyObject tv = ItemsControl.ItemsControlFromItemContainer(tvi) as DependencyObject;\n\n        if (tv != null)\n            return findLevel(tv, level + 1);\n        else\n            return level;\n    }\n\n    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)\n    {\n        throw new Exception("The method or operation is not implemented.");\n    }\n}	0
6059218	6059136	Convert this SQL Statement to LINQ	var meterReadingTasks = from task in context.Tasks\n                       where task.TaskType == "MeterReading"\n                       select task.MeterReadingOrderERPRouteCreateResponseID;\n\nvar results = from m in context.MeterReadingOrderERPRouteCreateResponses\n              where !meterReadingTasks.Contains(m.Id)\n              select new { m.ID, m.UniqueID, m.RouteHeaderID, m.RouteObjectState, m.OriginalRouteUniqueID};	0
19189455	19189009	Better way of getting index from multidimensional array	int firstIndex;\nint lastIndex; \nfor(int i = 0; i < val.GetLength(1); i++)\n{\n    if(val[0,i].Contains("Rak"))\n    {\n        firstIndex = i;\n        break;\n    } \n}\nfor(int i = val.GetLength(1) - 1; i>=0; i--)\n{\n    if(val[0,i].Contains("Rak"))\n    {\n        lastIndex = i;\n        break;\n    } \n}	0
8574510	8574254	How to find dd/mm/yyyy date on string using c#?	string UpdateDates(string input)\n{\n    return Regex.Replace(input, @"\d{2}/\d{2}/\d{4}", m => DateTime.Now.ToString("dd/MM/yyyy"));\n}	0
481858	481803	Converting some LISP to C#	var g = 2 * (gethash(word, good) | 0);\nvar b = gethash(word, bad) | 0;\n\nif( (g + b) >= 5)\n{\n    return Math.Max( \n    0.01, \n    Math.Min(0.99, \n    Math.Min(1, b / nbad) / \n    (Math.Min(1, g / ngood) + Math.Min(1, b / nbad))));\n}	0
8510090	8507546	Castle Windsor Fluent Configuration: Is it possible to make a specific lifestyle for a given service without using the concrete implementation?	container.Register(AllTypes\n                   .FromThisAssembly()\n                   .InSameNamespaceAs<IMyService>()\n                   .WithServiceDefaultInterfaces()\n                   .ConfigureIf(s => typeof(IMyService).IsAssignableFrom(s.Implementation),\n                                s => s.LifestyleSingleton(),\n                                s => s.LifestyleTransient()));	0
15223375	15220921	How to store double[] array to database with Entity Framework Code-First approach	public string InternalData { get; set; }\n public double[] Data\n {\n    get\n    {\n        return Array.ConvertAll(InternalData.Split(';'), Double.Parse);                \n    }\n    set\n    {\n        _data = value;\n        InternalData = String.Join(";", _data.Select(p => p.ToString()).ToArray());\n    }\n }	0
12183037	12182983	Generating a random number related to input parameters	int seed = \n    BitConverter.ToInt32(BitConverter.GetBytes(\n        x * 17 + y\n    ));\nnew Random(seed).NextDouble();	0
9327603	9327474	Entity Framework - Select distinct in	List<String> AuctionIDs = (from tagItem in Tags\n                           where searchItems.Contains(tagItem.Label)\n                           select tagItem.AutionID).Distinct().ToList();	0
8773719	8773640	how to copy data in following case	T ApplyCurrentValues<T>(string entitySetName, T currentEntity)	0
30888939	30886534	Custom DataType for Umbraco containing MultiUrlPicker	var urlPicker = new MultiUrlPickerDataEditor {Settings = new MultiUrlPickerSettings{ Standalone = false }};	0
10742155	10641040	Make a database connection to Sage Abra Suite	// Build the connection string\n      string connectionString = @"Provider=VFPOLEDB.1;Data Source= myServer;Collating Sequence=general";\n\n      // Create the connection\n      OleDbConnection connection = new OleDbConnection(connectionString);\n\n      // Open the connection\n      connection.Open();	0
2482825	2482773	How Can I Get CurrentWindow?	class Program\n{\n    [DllImport("user32.dll", SetLastError = true)]\n    static extern IntPtr FindWindow(string lpClassName, string lpWindowName);\n\n    static void Main(string[] args)\n    {\n        var hWnd = FindWindow(null, "Untitled - Notepad");\n        if (hWnd != IntPtr.Zero)\n        {\n            Console.WriteLine("window found");\n        }\n        else\n        {\n            Console.WriteLine("No window with given title has been found");\n        }\n    }\n}	0
2025955	2025934	Decrypting string using ASP.Net encrypted by Php	Byte.Parse(hexCode, System.Globalization.NumberStyles.HexNumber);	0
11897508	11897419	Where CultureInfo Coming From?	System.Threading.Thread.CurrentThread.CurrentCulture = new CultureInfo("zh-CN");	0
14306844	14306768	How to run stored procedure from code behind	using( SqlConnection con = new SqlConnection(connenctionstring))\n{\n using(SqlCommand myCMD = new SqlCommand("sp_Test", con))\n {\n  myCMD.CommandType = CommandType.StoredProcedure;\n  con.Open();\n  myCMD.ExecuteNonQuery();//as its insert command\n  con.Close();\n }\n}	0
15526734	15304130	Send a windows form control to front and back on a form	Textbox.sendtoback();\n     Textbox.bringtofront();	0
28447378	28426100	Using Html.Action and PartialView but get a Duplicate type name within an assembly	int webSiteNbr;\nbool result = int.TryParse(WebConfigurationManager.AppSettings["WebSite"], out webSiteNbr);\nPageTab pageTab = PageTab.Home;\nint pageTabVal = (int)pageTab;\n\nvar pagContentList2 = from p in db.PageContents\n                      from w in db.WebSites\n                      where w.WebSiteID == webSiteNbr && p.PageTab == pageTabVal && p.PageContentSeqNbr == id\n                      //select p;\n                      select new PageContentVM\n                      {\n                          PageContentID = p.PageContentID,\n                          PageContentLongDesc = p.PageContentLongDesc\n                      };\n\nreturn PartialView("_PageContentDisplay", pagContentList2.Single());	0
4125008	3942438	Auditing to Ignore Certain Property Changes with NHibernate Event Listeners	private bool IsDirty(PostUpdateEvent @event) {\n    // Get all the mapped property names\n    var propertyNames = @event.Session.Factory.GetClassMetadata(@event.Entity.GetType()).PropertyNames;\n\n    // Get the property index to ignore\n    var propertyIndexesToIgnore = @event.Entity.GetType().GetProperties()\n        .Where(p => p.GetCustomAttributes(typeof(IgnoreLoggingAttribute), false).Count() > 0)\n        .Select(p => Array.IndexOf(propertyNames, p.Name)).ToArray();\n\n    if (@event.OldState != null && @event.State != null) {\n        for (var i = 0; i < @event.OldState.Length; i++) {\n            if (!propertyIndexesToIgnore.Contains(i) && !@event.OldState[i].Equals(@event.State[i]))\n                return true;\n        }\n    }\n\n    return false;\n}	0
14061230	14059381	MVVM Set MenuItem's DataContext	cinch:SingleEventCommand.TheCommandToRun="{BindingPath=PlacementTarget.DataContext.OpenBackupInExplorerCommand, \n                                           RelativeSource={RelativeSource FindAncestor, \n                                                                          AncestorType={x:Type ContextMenu}}}"	0
9602065	9601842	how to detect only windows 2003 computers from domain	using (var mc = new ManagementClass(@"\\" + computerName + @"\root\cimv2:Win32_OperatingSystem"))\n{\n    foreach (var obj in mc.GetInstances())\n    {\n       if (((bool)obj.Properties["Primary"].Value))\n       {\n          int productType = (int)obj.Properties["ProductType"].Value;\n          string version = obj.Properties["Version"].Value.ToString();\n          bool isServer = (productType == 2 || productType == 3); // "Domain Controller" or "Server\n\n          if (version == "5.2.3790" && isServer)\n          {\n             // "Caption" should contain something like "Microsoft(R) Windows(R) Server 2003..."\n             // Please resist parsing that, however.                  \n             Console.WriteLine(obj.Properties["Caption"].Value);\n          }\n       }\n    }\n }	0
22547108	22545428	C# Excel get range of cells visible on the screen	Sub dural()\n    Dim w As Window, r As Range\n    Set w = ActiveWindow\n    Set r = w.VisibleRange\n    r.MergeCells = True\n    r.HorizontalAlignment = xlCenter\n    r.VerticalAlignment = xlCenter\n    r.Value = "Hello World"\nEnd Sub	0
32288083	32287440	MongoDB Text Search with projection	var client = new MongoClient();\nvar db = client.GetDatabase("test");\nvar col = db.GetCollection<BigClass>("big");\nawait db.DropCollectionAsync(col.CollectionNamespace.CollectionName);\n\nawait col.Indexes.CreateOneAsync(Builders<BigClass>.IndexKeys.Text(x => x.Title));\n\nawait col.InsertManyAsync(new[]\n{\n    new BigClass { Title = "One Jumped Over The Moon" },\n    new BigClass { Title = "Two went Jumping Over The Sun" }\n});\n\n\nvar filter = Builders<BigClass>.Filter.Text("Jump Over");\n// don't need to Include(x => x.TextMatchScore) because it's already been included with MetaTextScore.\nvar projection = Builders<BigClass>.Projection.MetaTextScore("TextMatchScore").Include(x => x._id).Include(x => x.Title);\nvar sort = Builders<BigClass>.Sort.MetaTextScore("TextMatchScore");\n\nvar result = await col.Find(filter).Project<SmallClass>(projection).Sort(sort).ToListAsync();	0
12031468	12030969	Refreshing the listbox item after an element is changed	// If we already have the parameter set then edit it.\nif (lstbxSetParameters.Items.Contains(currentParameter))\n{\n    var newItem = new ParameterItem((lstbxSetParameters.SelectedItem as ParameterItem).Name, currentParameter.Value);\n    var index = lstbxSetParameters.SelectedIndex;\n    lstbxSetParameters.Items.RemoveAt(index);\n    lstbxSetParameters.Items.Insert(index, newItem);\n    lstbxSetParameters.SelectedIndex = index;\n}	0
15462267	15461724	C# : Call a method every 5 minutes from a foreach loop	public void ProcessData()\n    {\n        int i = 1;\n        foreach(var item in File.ReadLines(path)) //This line has been edited\n        {\n            DataRow dtRow= dataTable.NewRow();\n            dtRow["ID"]= .... //some code here;\n            dtRow["Name"]= .... //some code here;\n            dtRow["Age"]= .... //some code here;\n            if (i%25 == 0) //you can change the 25 here to something else\n            {\n                SaveData(/* table name */, /* dataTable */);\n            }\n            i++;\n        }\n        SaveData(/* table name */, /* dataTable */);\n    }\n\n    public void SaveData(string tableName, DataTable dataTable )\n    {\n        //Some code Here\n        //After dumping data to DB, clear DataTable\n        dataTable.Rows.Clear();\n    }	0
6614504	6614451	Timer increases memory usage in C# app	var timer = new Timer\n{\n    Interval = 1000,\n};\ntimer.Tick += (s, evt) =>\n{\n    label1.Text = DateTime.Now.ToLongTimeString();\n};\ntimer.Start();	0
8577721	8577683	strip out digits or letters at the most right of a string	int lastDash = text.LastIndexOf('-');\nstring afterDash = text.Substring(lastDash + 1);\nint dot = afterDash.IndexOf('.');\nstring data = dot == -1 ? afterDash : afterDash.Substring(0, dot);	0
25945455	25814163	How to know which controller method will be called from Web API Authorization filter	actionContext.ActionDescriptor.ActionName	0
9488207	9488132	How to refer to a Cell in a ASP.NET GridView without using its index?	ImageButton ibtStatus = (ImageButton)e.Row.FindControl(ibtIDStatus);	0
9660541	9660280	How do I programmatically locate my Dropbox folder using C#?	var dbPath = System.IO.Path.Combine(\n                    Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "Dropbox\\host.db");\n\nvar dbBase64Text = Convert.FromBase64String(System.IO.File.ReadAllText(dbPath));\n\nvar folderPath = System.Text.ASCIIEncoding.ASCII.GetString(dbBase64Text);	0
19072637	19072197	Binding properties of User Control in Windows Phone Application	public partial class LongListSelectorItemControl\n{\n\n\n   public static readonly DependencyProperty TitleProperty =\n            DependencyProperty.Register("Title", typeof(string), typeof(LongListSelectorItemControl), new PropertyMetadata(default(string), TitlePropertyChanged));\n\n        private static void TitlePropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)\n        {\n            LongListSelectorItemControl myControl=d as LongListSelectorItemControl;\n            myControl.TitleTextBlock.Text = e.NewValue as string;\n        }\n\n        public string Title\n        {\n            get { return (string) GetValue(TitleProperty); }\n            set { SetValue(TitleProperty, value); }\n        }\n....\n}	0
2229030	2223282	.NET custom MembershipProvider decrypt password	private string UnEncodePassword(string encodedPassword)\n{\n    string password = encodedPassword;\n    byte[] bytesIn = Convert.FromBase64String(encodedPassword);\n    byte[] bytesRet = DecryptPassword(bytesIn);\n    password = System.Text.Encoding.Unicode.GetString(bytesRet, 16, bytesRet.Length - 16);\n\n    return password;\n}	0
16711792	16710418	Get Latest Turkish Currency symbol	case "tr-TR":\n                    var original = CultureInfo.GetCultureInfo("tr-TR");\n                    var mutableNfi = (NumberFormatInfo)original.NumberFormat.Clone();\n                    mutableNfi.CurrencySymbol = "TL";\n                    double price = Convert.ToDouble(retailerProduct.Price);\n                    stringBuilder.Append(price.ToString("C", mutableNfi));\n                    break;	0
15253179	15253110	connectionstring with windows username and password, can we?	Integrated Security=true;	0
19113175	19096013	Detect current database is partial restored	var restoreType = dbContext.Database.SqlQuery<string>(@"Select restore_type FROM [msdb].[dbo].[restorehistory]").FirstOrDefault<string>();	0
5957073	5957012	How to get the list index of the nearest number?	int index = list.IndexOf(closest);	0
9432274	9432124	Converting binary data to bytes in c#	using (var fileToReadFrom = File.OpenRead(@"..."))\nusing (var fileToWriteTo = File.OpenWrite(@"..."))\n{\n    var s = "";\n    while (true)\n    {\n        var byteRead = fileToReadFrom.ReadByte();\n        if (byteRead == -1)\n            break;\n        if (byteRead != '0' && byteRead != '1')\n        {\n            // If you want to throw on unexpected characters...\n            throw new InvalidDataException(@"The file contains a character other than 0 or 1.");\n            // If you want to ignore all characters except binary digits...\n            continue;\n        }\n        s += (char) byteRead;\n        if (s.Length == 8)\n        {\n            fileToWriteTo.WriteByte(Convert.ToByte(s, 2));\n            s = "";\n        }\n    }\n}	0
13005861	13005098	Parsing HTML Table in C#	WebClient webClient = new WebClient();\nstring page = webClient.DownloadString("http://www.mufap.com.pk/payout-report.php?tab=01");\n\nHtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();\ndoc.LoadHtml(page);\n\nList<List<string>> table = doc.DocumentNode.SelectSingleNode("//table[@class='mydata']")\n            .Descendants("tr")\n            .Skip(1)\n            .Where(tr=>tr.Elements("td").Count()>1)\n            .Select(tr => tr.Elements("td").Select(td => td.InnerText.Trim()).ToList())\n            .ToList();	0
19081762	19081646	How to use delegate as invoke parameter?	methodInfo.Invoke(null, new object[] { new Action(C.A) });	0
19887270	19887197	How to update status value in gridview?	int statusID =0;\n\nif(Session["statusID"] != null && int.TryParse(Session["statusID"].ToString(), out statusID) && statusID ==1)\n{\n    using(SqlConnection con = new SqlConnection(ConnectionString))// set ConnectionString\n    {\n        using(SqlCommand cmd = new SqlCommand("update tblstatus set statusID=2 where      expenesesid=@expensesid",con)) // set appropriate query\n        {\n            sqldatadapter da=new sqldatadapter(cmd) ;\n            con.Open();\n            cmd.ExecuteNonQuery();\n        }\n    }\n}	0
2472542	2472441	How to override Equals on a object created by an Entity Data Model?	public partial class Person\n{\n    public override bool Equals(Object obj)\n    {\n        //your custom equals method\n    }\n}	0
2401558	2400720	XML deserialization problem (attribute with a namespace)	[Serializable]\n[XmlRoot(Namespace = "http://www.w3.org/1999/02/22-rdf-syntax-ns#", ElementName = "Description")]\npublic class BasicEntity\n{\n    [XmlElement(Namespace = "http://s.opencalais.com/1/pred/", ElementName = "name")]\n    public string Name { get; set; }\n\n    [XmlAttribute("about", Form=XmlSchemaForm.Qualified, Namespace = "http://www.w3.org/1999/02/22-rdf-syntax-ns#")]\n    public string Uri { get; set; }\n}	0
537394	431658	How would I add new data via a REST service opposed to RPC style service?	[WebInvoke(RequestFormat = WebMessageFormat.Xml, \n           ResponseFormat = WebMessageFormat.Xml,\n           Method = "POST", UriTemplate = "tasks/{description}", \n           BodyStyle = WebMessageBodyStyle.Bare)]\n[OperationContract]\nvoid AddTask(string description);	0
9647143	9641305	Windows Phone Hold Gesture	bool hold = false;\nDispatcherTimer timer = new DispatcherTimer();\n\nprivate void x_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)\n    {\n        hold = true;\n        timer.Interval = new TimeSpan(0, 0, 0, 0, 500);//days,hours,minutes,seconds,milliseconds\n        timer.Tick += new EventHandler(timer_tick);\n        timer.Start();\n    }\nprivate void x_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)\n    {\n        hold=false;\n    }\n\nprivate void timer_Tick(object sender, EventArgs e)\n    {\n        timer.Stop();\n        if(hold = true)\n           {\n           //et voil??, hold-event after 0,5 seconds\n           // place actions that should be handled after 0,5seconds HERE\n           }\n     }	0
29548513	29497200	OAuth Bearer Access Token sliding expiration	[Authorize]\npublic class RefreshTokenController : ApiController\n{\n    [HttpGet]\n    public HttpResponseMessage ReissueToken()\n    {\n        // just use old identity\n        var identity = ((ClaimsPrincipal)User).Identity as ClaimsIdentity;\n\n        var ticket = new AuthenticationTicket(identity, new AuthenticationProperties());\n        DateTimeOffset currentUtc = new SystemClock().UtcNow;\n\n        ticket.Properties.IssuedUtc = currentUtc;\n        ticket.Properties.ExpiresUtc = currentUtc.AddMinutes(30);\n\n        string token = Startup.OAuthBearerAuthOptions.AccessTokenFormat.Protect(ticket);\n\n        return new HttpResponseMessage(HttpStatusCode.OK)\n        {\n            Content = new ObjectContent<object>(new\n            {\n                accessToken = token,\n                expiresIn = (int)((ticket.Properties.ExpiresUtc.Value - ticket.Properties.IssuedUtc.Value).TotalSeconds),\n            }, Configuration.Formatters.JsonFormatter)\n        };\n    }\n}	0
6918445	6918070	How do I search for a specific cell in a DataGridView?	int FindCellRowIndex( string columnName, string rowContent ){\n    foreach (DataGridViewRow row in dgView.Rows){             \n           foreach (DataGridViewCell cell in row.Cells){\n               if( cell.OwningColumn.Name() == columnName && cell.Value != null && Convert.Tostring(cell.Value) == rowContent)\n                  return row.Index;\n           }             \n    }\n    return -1;\n}	0
6468565	6467367	add parameter to function in c# and js	objHandler.Read('one', function (serverResponse) {	0
5013984	5013936	How to Read values from XML file	using System.Xml.Linq;\nXDocument xdoc = XDocument.Load("RESTORE.XML");\nxdoc.Descendants("EmployeeID").First().Value;\nxdoc.Descendants("EmployeeName").First().Value;	0
21314925	21312986	Setting the default index of my combo box only on initial open	private void Form1_Load(object sender, EventArgs e)\n{\n    //To make combobox non editable\n    comboBox1.DropDownStyle = ComboBoxStyle.DropDownList;\n\n    //Set preferred index to show as default value\n    comboBox1.SelectedIndex = 2;\n}	0
7201610	7201587	Converting inerface with delegate from vb to c#	public delegate void AnswerValueChangedEventHandler(\n  object sender, \n  NotebookAnswerChangedEventArgs e);\n\npublic interface ICSIItem {\n  void Initialize();\n  event AnswerValueChangedEventHandler AnswerValueChanged;\n  object DataContext { get; set; }\n}	0
13748194	13745586	Outputting filtered results into an excel readable format without using .linq	// Construct a tab-separated string with your variables:\nStringBuilder str = new StringBuilder();\nstr.Append(i.ToString());\nstr.Append("\t");\nstr.Append(lineStart.ToString());\nstr.Append("\t");\nstr.Append(letters.ToString());\n...\n\n// Push the string into your list:\nmyList.Add(str.ToString());\n...\n\n// Finally, you can write the contents of your list into a text file:\nSystem.IO.File.WriteAllLines("output.txt", myList.ToArray());	0
16105117	16104727	LINQ order a collection of objects by date in descending order	.OrderByDescending(d => Convert.ToDateTime(d.DateCreated)).Take(10)	0
24573275	24570029	Prevent ExpanderView from expanding on click or overwrite expand method	contact.IsExpanded = false;\nexp.UpdateLayout();\ncontact.IsExpanded = true;	0
32268273	32268142	DateTime.TryParse to other culture info	DateTime reportDate;\n\nif (!DateTime.TryParse(result,\n    System.Globalization.CultureInfo.GetCultureInfo("sv-SE"),\n    System.Globalization.DateTimeStyles.None, out reportDate))\n{\n    ModelState.AddModelError("Date", "Felaktikt datum");\n}	0
2476548	2476523	C# How can I trigger an event at a specific time of day?	DateTime.Now	0
2288123	2288087	How can I write my application as a multithreaded application in C#?	void main()\n{\n   Thread worker = new Thread(new ThreadStart(DoStuff));\n   worker.Start();\n}\n\nprivate void DoStuff() \n{\n  // long running work in here\n}	0
16984054	16983766	How to get changed/sent properties at controller?	[HttpPost]\npublic ActionResult Update(int id)\n{\n    // Load the entity to be updated from the database\n    ClassX data = db.ClassXs.SingleOrDefault(x => x.Id == id);\n\n    // Modify only the properties that were present in the request \n    // (BE EXTREMELY CAREFUL WITH THAT -> YOUR CODE IS VULNERABLE TO MASS ASSIGNMENT\n    // AND THE PROPER SOLUTION IS TO USE A VIEW MODEL WHICH WILL ONLY CONTAIN THE PROPERTIES\n    // THAT ARE ALLOWED TO BE UPDATED FROM THE VIEW)\n    this.UpdateModel(data);\n\n    // at this stage the data instance will have its properties coming from the view\n    // updated with fresh values => now you can commit it to the database\n    ...\n}	0
6813568	6813320	Setting attributes of a property in partial classes	using System.ComponentModel.DataAnnotations;\n\n[MetadataType(typeof(EmployeeMetadata))]\npublic partial class Employee\n{\n  private class EmployeeMetadata\n  {\n     [Required]\n     public object Name; // Type doesn't matter, it is just a marker\n  }\n}	0
15713025	15670123	Binding Refresh on a dataGrid WinForms	public class Class1 : INotifyPropertyChanged\n{\n    public event PropertyChangedEventHandler PropertyChanged;\n\n    private int myValue;\n    public int MyValue\n    {\n        get { return myValue; }\n        set \n        {\n            if (myValue != value)\n            {\n                myValue = value;\n                OnPropertyChanged("MyValue");\n            }\n        }\n    }\n\n    protected virtual void OnPropertyChanged(string property)\n    {\n        var notify = PropertyChanged;\n        if (notify != null)\n            notify(this, new PropertyChangedEventArgs(property));\n    }\n}	0
14567272	14567221	How can i add to the List<string> the last file from the directory?	for (int i = radarFiles.Length - 1; i >= 0; i--)\n{\n}	0
26615411	26612035	Scrolling Troubles	FlowLayoutPanel\n    AutoSize = true\n    AutoScroll = false\n    WrapContents = true\n    Anchor = Top (required) | Left (optional)\n\nMainForm\n    AutoScroll = true	0
4020414	4020255	Serializing to XML via DataContract: custom output?	[DataContract]\npublic class MyObject {\n    Int32 _Numerator;\n    Int32 _Denominator;\n    public MyObject(Int32 numerator, Int32 denominator) {\n        _Numerator = numerator;\n        _Denominator = denominator;\n    }\n    public Int32 Numerator {\n        get { return _Numerator; }\n        set { _Numerator = value; }\n    }\n    public Int32 Denominator {\n        get { return _Denominator; }\n        set { _Denominator = value; }\n    }\n    [DataMember(Name="Frac")]\n    public String Fraction {\n        get { return _Numerator + "/" + _Denominator; }\n        set {\n            String[] parts = value.Split(new char[] { '/' });\n            _Numerator = Int32.Parse(parts[0]);\n            _Denominator = Int32.Parse(parts[1]);\n        }\n    }\n}	0
17334737	17334652	How to get the type of a variable using reflection c#	foreach (FieldInfo fieldInfo in typeof(A).GetFields(BindingFlags.Instance |\n                               BindingFlags.Static |\n                               BindingFlags.NonPublic |\n                               BindingFlags.Public))\n                {\n                    Console.WriteLine(fieldInfo.FieldType.Name);\n                }	0
313352	313324	Declare a Dictionary inside a static class	private static readonly Dictionary<string, string> ErrorCodes\n    = new Dictionary<string, string>\n{\n    { "1", "Error One" },\n    { "2", "Error Two" }\n};	0
17427194	17427012	mvc4 actionlink passing variable	public ActionResult Create()\n{\n    ...\n    return View(Client);\n}	0
23400154	23400036	WebApi return JSON and put a '$' symbol as prefix in some properties?	public class Customer\n{\n    public int Id { get; set; }\n    public string Name { get; set; }\n    [JsonProperty(PropertyName = "$BagData")]\n    public BagData BagData { get; set; }\n}	0
21068713	21057354	How do I send arbitrary JSON data, with a custom header, to a REST server?	/// <summary>\n    /// Creates a new instance of the <see cref="T:System.Net.Http.StringContent"/> class.\n    /// </summary>\n    /// <param name="content">The content used to initialize the <see cref="T:System.Net.Http.StringContent"/>.</param><param name="encoding">The encoding to use for the content.</param><param name="mediaType">The media type to use for the content.</param>\n    [__DynamicallyInvokable]\n    public StringContent(string content, Encoding encoding, string mediaType)\n      : base(StringContent.GetContentByteArray(content, encoding))\n    {\n      this.Headers.ContentType = new MediaTypeHeaderValue(mediaType == null ? "text/plain" : mediaType)\n      {\n        CharSet = encoding == null ? HttpContent.DefaultStringEncoding.WebName : encoding.WebName\n      };\n    }	0
21552460	21551126	Evading button, but in a clean way	IF cursor is near the button AND cursor is between button and center AND button is near the edge THEN jump over towards the center	0
2948176	2948118	Replace text in code with counting numbers	static private void Trace()\n{\n     StackFrame callStack = new StackFrame(1, true);\n     Log.WriteLine(\n       String.Format("At {0}:{1}",\n         callStack.GetFileName(),\n         callStack.GetFileLineNumber()));\n}	0
9590824	9518375	reference value in DataColumn Expressions	Parent.rate * loan_amt	0
23940706	23940582	How to get a Listbox to read to a Listbox	listBox1.Items.AddRange(File.ReadAllLines(label1.Text));	0
19464050	19463958	How do you increment a value in a DataGridView in C# if it exists in the datagrid already	var matchedRow = productList.Rows.OfType<DataGridViewRow>()\n                            .FirstOrDefault(row=>row.Cells[0].Value != null &&\n                                                 row.Cells[0].Value.Equals(itemInfo[0]));\nif(matchedRow != null){\n  int qty = (int)matchedRow.Cells[6].Value + 1;\n  double price = (double)matchedRow.Cells[3].Value;\n  matchedRow.Cells[7].Value = price * qty;\n}	0
23030565	23030497	Create pair values from consecutive int array elements	int[] Arr = new int[] { 1, 2, 0, 3, 4 };\nint ExactResultLength = (int)(((double)Arr.Length / 2) + 0.5);\nint[] res = new int[ExactResultLength];\n\nint j = 0;\nfor (int i = 0; i < Arr.Length; i+= 2)\n{\n    if(i + 1 < Arr.Length)\n        res[j] = Arr[i] + Arr[i+1];\n    else\n        res[j] = Arr[i];\n\n    j++;\n}	0
21654396	21654082	For each control loop only affecting one Control	foreach (Control c in this.Controls)\n{\n    if (c.Height > 25)\n    {\n        c.BackColor = Color.Red;\n        pictureBox1.Location = new Point(x1, y1);\n        if (pictureBox1.Bounds.IntersectsWith(c.Bounds))\n        {\n            isCollide = true;\n            label1.Text = "true";\n            c.BackColor = Color.Green;\n            break;\n        }\n        else\n        {\n            isCollide = false;\n            label1.Text = "false";\n        }\n    }\n}	0
22806434	22588176	Separating Clock In and Clock Out data stored within one column	SqlDataAdapter sda1 = new SqlDataAdapter("SET ROWCOUNT 10 SELECT USERINFO.USERID [User ID], USERINFO.NAME [Name], USERINFO.DEFAULTDEPTID [Dept.],CONVERT(VARCHAR(10),CHECKINOUT.CHECKTIME,103) [Date], MIN(CONVERT (VARCHAR(5),CHECKINOUT.CHECKTIME,108)) [Clock In], MAX(CONVERT (VARCHAR(5),CHECKINOUT.CHECKTIME,108)) [Clock Out] FROM USERINFO ,CHECKINOUT where USERINFO.USERID = CHECKINOUT.USERID GROUP BY USERINFO.USERID, USERINFO.NAME, USERINFO.DEFAULTDEPTID, CONVERT(VARCHAR(10),CHECKINOUT.CHECKTIME, 103)", con);\n        sda1.Fill(dta);\n        dataGridView1.DataSource = dta;	0
541747	541635	How do I find the fully qualified hostname of my machine in C#?	System.Net.Dns.GetHostEntry("").HostName	0
10453301	10453223	Parsing date from xml	DateTime.ParseExact(item.Element("Date").Value, "M/d/yyyy", CultureInfo.InvariantCulture)	0
7405634	7405267	Extract PDF text by coordinates	PDDocument doc = PDDocument.load(@"c:\invoice.pdf");\n\nPDFTextStripperByArea stripper = new PDFTextStripperByArea();\nstripper.addRegion("testRegion", new java.awt.Rectangle(0, 10, 100, 100));\nstripper.extractRegions((PDPage)doc.getDocumentCatalog().getAllPages().get(0));\n\nstring text = stripper.getTextForRegion("testRegion");	0
32069863	32069729	How to ensure the correct state of local variables when using BeginInvoke method	string message;\nwhile (balloonMessages.TryDequeue(out message))\n{\n     var localCopy = message;\n     Console.WriteLine("Outside: {0}", localCopy);\n     BeginInvoke((MethodInvoker)delegate()\n     {\n          Console.WriteLine("Inside: {0}", localCopy);\n     });\n}	0
26626951	26626843	How to expire ASP Session if user will not interact with web page for specific time?	SlidingExpiration="true"	0
29668187	29667154	Horizontal gravity on a gameObject in Unity	Rigidbody2D playerRigidbody;\nConstantForce2D customGravity;\n\nvoid Awake () {\n    playerRigidbody = GetComponent<Rigidbody2D> ();\n    customGravity = GetComponent<ConstantForce2D> ();\n\n    float gravityForceAmount = playerRigidbody.mass * Physics2D.gravity.magnitude;\n    customGravity.force = new Vector2 (-gravityForceAmount, 0); // gravity to the left\n}\n\nvoid Update () {\n    if(mass or gravity changes)\n        modify the constant force;\n}	0
28171578	28170842	Application hangs on Lock statement	object closeLockObj = new object();\npublic void Close()\n{\n    try\n    {\n        lock (closeLockObj)\n        {\n\n            if (newLocationHandle != IntPtr.Zero){\n            CloseHandle(newLocationHandle);\n            newLocationHandle = IntPtr.Zero;\n            }......\n\n        }\n    }\n    catch (Exception excpt)\n    {\n    //stack trace\n    }\n}	0
3373738	3373415	Cannot control Windows Form objects from another method in the same file as the Windows Form	public void UpdateUI()\n{\n    label3.Enabled = true;\n    this.Show();\n}	0
15491216	15491208	NullReferenceException when trying to use a foreach on an Interface	private List<IEnemy> Enemies = new List<IEnemy>();	0
11347750	11347610	How can I remove this if condition from my view?	public string SourceImageUrl\n{\n    get\n    {\n        switch (StreamSourceId)\n        {\n            case 1: return "~/Public/assets/images/own3dlogo.png";\n            case 2: return "~/Public/assets/images/twitchlogo.png";\n            default: return null;\n        }\n    }\n}	0
4748617	4748489	Adding properties of an Object together in a collection	ContactList contactList = myContactDictionary[id];\nAggregateLabel existing = contactList.AggLabels.FirstOrDefault(\n                              l => l.Name == dr["LABEL_NAME"].ToString()\n                          );\nif (existing == null) { contactList.AggLabels.Add(\n                            new AggregatedLabel() {\n                                Name = dr["LABEL_NAME"].ToString(),\n                                Count = Convert.ToInt32(dr["LABEL_COUNT"])\n                            }\n                        );\n                      }\nelse { existing.Count += Convert.ToInt32(dr["LABEL_COUNT"]); }	0
15412360	15411572	Unable to find a default constructor to use for type System.Json.JsonObject	using System.Collections.Generic;\nusing System.Linq;\nusing System.Net.Http;\nusing System.Web.Mvc;\nusing Newtonsoft.Json.Linq;\nusing PayPoint.Models;\nusing System.Threading.Tasks;\n\nnamespace PayPoint.Controllers\n{\n    public class HomeController : Controller\n    {\n        public ActionResult Index()\n        {\n            var model = new List<Tweets>();\n            const string webUri = "http://search.twitter.com/search.json?q=dave";\n\n            var client = new HttpClient();\n            var tweetTask = client.GetAsync(webUri);\n            Task<JObject> jsonTask = tweetTask.Result.Content.ReadAsAsync<JObject>();\n            var results = jsonTask.Result;\n\n            model.AddRange((from b in results["results"]\n                     select new Tweets()\n                         {\n                             Name = b["from_user"].ToString(),\n                             Text = b["text"].ToString()\n                         }).ToList());\n\n            return View(model);\n        }\n    }\n}	0
32475473	32475335	How do I club two string formats, or add a character to a string format	string result = string.Format("{0:G29}%", 1.2300000000);	0
16731091	16730942	MVC 4 - How to handle objects with time series	List<Price> Stock.PricesPerDay	0
6388833	6388701	Is there a difference between adding CommandBindings to a control vs using RegisterClassCommandBinding?	element.CommandBindings.Clear()	0
1041972	1038278	Returning an HtmlTable to be written with ajax	protected string Table_Maker() {\n    HtmlTable tbl = new HtmlTable();\n    HtmlTableCell cell = new HtmlTableCell();\n    HtmlTableRow row = new HtmlTableRow();\n    cell.InnerText = "WhateverText";\n    row.Cells.Add(cell);\n    tbl.Rows.Add(row);\n\n    StringBuilder sb = new StringBuilder();\n    using( StringWriter sw = new StringWriter( sb ) ) {\n        using( HtmlTextWriter tw = new HtmlTextWriter( sw ) ) {\n            tbl.RenderControl( tw );\n        }    \n    }    \n    return sb.ToString();\n}	0
9560495	6782489	Create Bitmap from a byte array of pixel data	var b = new Bitmap(Width, Height, PixelFormat.Format8bppIndexed);\n\n    ColorPalette ncp = b.Palette;\n    for (int i = 0; i < 256; i++)\n        ncp.Entries[i] = Color.FromArgb(255, i, i, i);\n    b.Palette = ncp;\n\n    var BoundsRect = new Rectangle(0, 0, Width, Height);\n    BitmapData bmpData = b.LockBits(BoundsRect,\n                                    ImageLockMode.WriteOnly,\n                                    b.PixelFormat);\n\n    IntPtr ptr = bmpData.Scan0;\n\n    int bytes = bmpData.Stride*b.Height;\n    var rgbValues = new byte[bytes];\n\n    // fill in rgbValues, e.g. with a for loop over an input array\n\n    Marshal.Copy(rgbValues, 0, ptr, bytes);\n    b.UnlockBits(bmpData);\n    return b;	0
31329760	31325028	Retrieve and store text from H5 Element using Web Driver & C#	By css = By.CssSelector("h5.page-sub-header-com.page-sub-header-subtext");\nstring element = Driver.FindElement(css).Text;	0
6460975	6460793	Using Rijndael to encrypt/decrypt files	int decrypt_length = decryptStream.Read(inputFileData, 0, (int)inputFileStream.Length);\nFileStream outputFileStream = new FileStream(outputFile, FileMode.Create, FileAccess.Write);\noutputFileStream.Write(inputFileData, 0, decrypt_length);	0
33223789	33196536	GetPreviewBitmapFile save preview bitmap with strange colors (SolidWorks)	//to compare output\niSwApp.GetPreviewBitmapFile(@"c:\Path\Part1.SLDPRT", "Default", @"c:\Path\Part1_0.bmp");\n\nobject com = iSwApp.GetPreviewBitmap(@"c:\Path\Part1.SLDPRT", "Default");\nstdole.StdPicture pic = com as stdole.StdPicture;\nBitmap bmp = Bitmap.FromHbitmap((IntPtr)pic.Handle);\nbmp.Save(@"c:\Path\Part1_1.bmp");	0
26681551	26678279	WebBrowser control content width/height	protected void TakeScreenshot(WebBrowser wb)\n{\n    mshtml.IHTMLDocument2 docs2 = (mshtml.IHTMLDocument2)wbNY.Document.DomDocument;\n    mshtml.IHTMLDocument3 docs3 = (mshtml.IHTMLDocument3)wbNY.Document.DomDocument;\n    mshtml.IHTMLElement2 body2 = (mshtml.IHTMLElement2)docs2.body;\n    mshtml.IHTMLElement2 root2 = (mshtml.IHTMLElement2)docs3.documentElement;\n\n    int width = Math.Max(body2.scrollWidth, root2.scrollWidth);\n    int height = Math.Max(root2.scrollHeight, body2.scrollHeight);\n\n    // Resize the control to the exact size to display the page. Also, make sure scroll bars are disabled\n    wb.Width = width;\n    wb.Height = height;\n\n    Bitmap bitmap = new Bitmap(width, height);\n    wb.DrawToBitmap(bitmap, new Rectangle(0, 0, width, height));\n    bitmap.Save(SaveImgDirectory + filename);\n}	0
15095384	15010319	Zedgraph X-axis scaling values	pane.XAxis.Type = AxisType.Log;	0
12852991	12821107	How to set BindingExpression.Status to Active programmatically?	MyData myDataObject = new MyData(DateTime.Now);      \nBinding myBinding = new Binding("MyDataProperty");\nmyBinding.Source = myDataObject;\nmyText.SetBinding(TextBlock.TextProperty, myBinding);	0
5596826	5596621	Accessing items in GridView	protected void gvShowComm_RowUpdating(object sender, GridViewUpdateEventArgs e)\n{\n    //Product_ID is a column that I am displaying in my GV!\n    int Product_ID = Int32.Parse(e.Keys["Product_ID"]);\n\n    Entity_Product_Point ev = new Entity_Product_Point();\n\n    ev.MyDateTime = DateTime.Parse(e.NewValues["MyProp"]);\n\n    // And so on...\n}	0
34423139	34423053	Read the lines in a text file after a certain line (c sharp)?	List<string> AllLines = File.ReadAllLines(yourpath).ToList();\n\nint StartIndex = AllLines.IndexOf(ContainerStartString) + 1;\nint EndIndex =  AllLines.IndexOf(ContainerEndString) - 1;\nList<string> MyLines = AllLines.GetRange(StartIndex, EndIndex);	0
2396483	2396422	C# merge two objects together at runtime	public static void MergeWith<T>(this T primary, T secondary) {\n    foreach (var pi in typeof(T).GetProperties()) {\n       var priValue = pi.GetGetMethod().Invoke(primary, null);\n       var secValue = pi.GetGetMethod().Invoke(secondary, null);\n       if (priValue == null || (pi.PropertyType.IsValueType && priValue.Equals(Activator.CreateInstance(pi.PropertyType)))) {\n          pi.GetSetMethod().Invoke(primary, new object[]{secValue});\n       }\n    }\n}	0
14176640	14175915	How to make storyboard autoreplay itself over and over again in Windows Phone	// Like Here my storyboard is sbSquare\n    private void sbSquare_Completed(object sender, EventArgs e)\n    {\n        this.sbSquare.Begin();\n    }	0
2584343	2584251	How to expose overloaded methods to an embedded IronPython interpreter?	public delegate void MyMethodDel(params object[] args);\n\nvoid MyPrintMethod(params object[] args)\n{\n  switch (args.Length)\n  {\n    case 1:\n      Console.WriteLine((string)args[0]);\n      break;\n    ...\n    default:\n      throw new InvalidArgumentCountException();\n  }\n}	0
192690	192653	How come I can't see member 'Default' on a class derived from ApplicationSettingsBase?	private static ServerSettings defaultInstance = ((ServerSettings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new ServerSettings())));\n\npublic static ServerSettings Default \n{\n    get { return defaultInstance; }\n}	0
28863684	28838090	Lambda Linq Iqueryable group - add another grouping	query = query.OrderBy(x => x.Location.ID).ThenBy(x => x.HolterTestType);\n        var htList = query.ToList();\n\n        // now Group by Location. \n        var reportContents = htList.GroupBy(x => x.Location.ID);\n\n        foreach (var r in reportContents)\n        {\n            //Group by TestType, to get counts.\n            var t = r.GroupBy(x => x.HolterTestType);\n            var tList = t.ToList();\n\n            foreach(var u in tList)\n            {\n                var cc = new CompletedCount();\n                var loc = LocationDao.FindById(r.Key);\n                cc.Description = loc.Description;\n                cc.RegionId = loc.Region.ID;\n                cc.DivisionId = loc.Region.Division.ID;\n                cc.TestTypeId = u.Key;\n                cc.Count = u.Count();\n                ccRpt.CompletedCounts.Add(cc);\n            }\n        }	0
15715432	15714727	Improving performance of slow query - Potentially by disabling change tracking	context.Entry(targetBundle)\n    .Collection(p => p.TradesReportEntries)\n    .Query()\n    .Where( e => <your filter here> )\n    .Select( <your projection here> )	0
11221913	10266625	same scroll bar for two richtextboxes	public enum ScrollBarType : uint\n    {\n        SbHorz = 0,\n        SbVert = 1,\n        SbCtl = 2,\n        SbBoth = 3\n    }\n\n    public enum Message : uint\n    {\n        WM_VSCROLL = 0x0115\n    }\n\n    public enum ScrollBarCommands : uint\n    {\n        SB_THUMBPOSITION = 4\n    }\n\n    [DllImport("User32.dll")]\n    public extern static int GetScrollPos(IntPtr hWnd, int nBar);\n\n    [DllImport("User32.dll")]\n    public extern static int SendMessage(IntPtr hWnd, uint msg, IntPtr wParam, IntPtr lParam);\n   // Set the dual scrolling on the richTextbox1 and affects richTextbox2\n\n    private void richTextBox1_VScroll(object sender, EventArgs e)\n    {\n        int nPos = GetScrollPos(richTextBox1.Handle, (int)ScrollBarType.SbVert); \n        nPos <<= 16;\n        uint wParam = (uint)ScrollBarCommands.SB_THUMBPOSITION | (uint)nPos;\n        SendMessage(richTextBox2.Handle, (int)Message.WM_VSCROLL, new IntPtr(wParam), new IntPtr(0));\n    }	0
21536025	21535709	Read from a SQL database and output result to a file	using System.Io;\n\nusing (FileStream fs = new FileStream(filepath, FileMode.OpenOrCreate, FileAccess.Write))\nusing (StreamWriter sw = new StreamWriter(fs))\n{\nwhile (readerObj.Read())\n{\nstring something = "";\nsw.writeline(something);\n}\n}	0
24059775	24059130	Post Parameter is always null, c# api controller	curl -i -H "Accept: application/json" -X POST -d "=myStr" http://localhost:61393/api/admin/import	0
27757370	27757299	How to retain changed state of controls when windows phone app is closed and opened again	IsolatedStorageSettings localSettings = IsolatedStorageSettings.ApplicationSettings\n\n//save the theme when user chooses their preference\nlocalSettings.Values["theme"] = "light";\n\n//retrieve the user's preference\nstring theme = (string)localSettings.Values["theme"];	0
849367	849359	How to draw text on picturebox?	private void pictureBox1_Paint(object sender, PaintEventArgs e)\n{\n    using (Font myFont = new Font("Arial", 14))\n    {\n        e.Graphics.DrawString("Hello .NET Guide!", myFont, Brushes.Green, new Point(2, 2));\n    }\n}	0
17974730	17974592	Trying to search ListView for subitems matching a string	ListViewItem searchItem = null;\nint index = 0;\ndo\n{\n    if (index < Program.booker.listView.Items.Count)\n    {\n        //true = search subitems\n        //last false param = no partial matches (remove if you want partial matches)\n        searchItem = Program.booker.listView.FindItemWithText(date, true, index, false);\n        if (searchItem != null)\n        {\n            index = searchItem.Index + 1;\n\n             //rest of code\n        }\n    }\n    else\n        searchItem =null;\n\n} while (searchItem != null);	0
16133626	16133189	How to populate a property with data from another property at load	public ICollection<Y> SomeNarrowList\n{\n    get { return SomeList.Select(p => p.Element).ToList(); }\n}	0
12776481	12723945	Display all exceptions in English locale	[DllImport("Kernel32.dll", SetLastError=true)]\nstatic extern uint FormatMessage( uint dwFlags, IntPtr lpSource, \n   uint dwMessageId, uint dwLanguageId, ref IntPtr lpBuffer, \n   uint nSize, string[] Arguments);	0
12880987	12880925	How do I get the default constructor value in a function	public AppXmlLogWritter(int intLogIDPrefix, string strLogApplication, string strLogFilePath)\n          :this()\n    {\n        LogIDPrefix = intLogIDPrefix;\n        LogApplication = strLogApplication;\n        LogFilePath = strLogFilePath;\n    }	0
11561307	11561145	How to query DataSets using LINQ and ouput in JSON format	var cities  = GetCities();\nvar employees = GetEmployees();\nreturn new JsonResult { Data = new { Content = new { Employees = employees, Cities = cities } } };	0
24997791	24997432	Check if Dictionary<string,string> has continuous elements (DateTime)	bool hasContinuousDays = false;\n\nvar selectedDates = new Dictionary<string, string>();\nselectedDates.Add("2014-06-21", DateTime.Now.ToString());\nselectedDates.Add("2014-06-22", DateTime.Now.AddDays(1).ToString());\nselectedDates.Add("2014-06-23", DateTime.Now.AddDays(2).ToString());\nselectedDates.Add("2014-06-24", DateTime.Now.AddDays(3).ToString());\n\nDateTime lastDay = DateTime.Parse(selectedDates.Values.First());\nhasContinuousDays = selectedDates.Values.Skip(1).All(\n        str=> {\n                var day = DateTime.Parse(str); \n                var b = day == lastDay.AddDays(1); \n                lastDay = day; \n                return b;\n            });\n\nhasContinuousDays .Dump();	0
34287396	34287273	How do I get yesterday's date with customized time?	var dateTime = DateTime.Now.AddDays(-1).Date.AddHours(14.5);	0
7594841	7568708	Is it possible to send a Int[] to an Oracle Stored Procedure using OleDb	TABLE OF VARCHAR2(30) INDEX BY BINARY_INTEGER;	0
18616	18608	Is it a bad idea to expose inheritance hierarchy in namespace structure?	using System.Data;\nusing System.Data.Sql;	0
23732215	23732024	Trouble writing text from a RichEditBox to a file with a C# Windows Store app	string textboxtext;\nEditor.Document.GetText(Windows.UI.Text.TextGetOptions.None, out textboxtext)\nawait FileIO.WriteTextAsync(file, textboxtext);	0
19105320	19105298	Select from list with list as property	return people.Where(p => p.Services.Any(s => s.Id == 3)).ToList();	0
16484810	16484448	is there a way to get a function to repeat itself if a condition isnt met	static int cantryagain=0;\n\nprivate void myfunction()\n{\n    for (int i = 0; i < 2; i++) // will loop a max of 2 times\n    {\n        if(variableA=1)\n        {\n            //do my stuff\n            //ta daaaa\n            break; //Breaks out of the for loop so you don't loop a second time\n        }\n        else if (i == 0)  // Don't bother if this isn't the first iteration\n        {\n            //do something magical that will help make variableA=1 but \n            //if the magic doesnt work i only want it to try once.\n        }\n    }\n}	0
6985002	6984919	WPF/C# - Applying date format to listview	DisplayMemberBinding="{Binding Path=startDate, StringFormat='yyyy-MM-dd HH:mm:ss.fff'}"	0
3135794	3135648	Databind to a tooltip	dsMyRows_OnCurrentItemChanged(sender, EventArgs e)\n{\n    ttPersonWhoDidAction.SetToolTip(lblDate, ((DataRowView)dsMyRows.Current)["TextValue"]);\n}	0
31512057	29410097	WPF application framework IView issue	public interface IToolbarView : System.Waf.Applications.IView\n{\n}	0
5978751	5978667	How to secure the ASP.NET_SessionId cookie?	// this code will mark the forms authentication cookie and the\n// session cookie as Secure.\nif (Response.Cookies.Count > 0)\n{\n    foreach (string s in Response.Cookies.AllKeys)\n    {\n        if (s == FormsAuthentication.FormsCookieName || s.ToLower() == ?asp.net_sessionid?)\n        {\n             Response.Cookies[s].Secure = true;\n        }\n    }\n}	0
18053492	17829355	Fit Label size to drawn text	using (Graphics g = lbl.CreateGraphics()) {\n    SizeF size = g.MeasureString(lbl.Text, lbl.Font);\n    // Change size of label if too small\n}	0
6552724	6552630	In Windows Forms, is there a control that shows a text overlay like a tooltip without all the tooltip behavior?	private void button1_Click(object sender, EventArgs e)\n{\n  ToolTip tip = new ToolTip();\n  tip.ToolTipTitle = "Title";\n  tip.Show("Hello", button1, 10, button1.Height - 6, 5000);\n}	0
21229094	21228593	How to calculate widget bounds?	// copied from UIDragObject.UpdateBounds()\npublic static Bounds GetContentRectBounds(UIRect content, UIPanel uiPanel){\n    Matrix4x4 toLocal = uiPanel.transform.worldToLocalMatrix;\n    Vector3[] corners = content.worldCorners;\n    for( int i = 0; i < 4; ++i ){\n        corners[i] = toLocal.MultiplyPoint3x4(corners[i]);\n    }\n    Bounds mBounds = new Bounds(corners[0], Vector3.zero);\n    for( int i = 1; i < 4; ++i ){\n       mBounds.Encapsulate(corners[i]);\n    }\n    return mBounds;\n}	0
1177660	1177434	Isn't a generic IList assignable from a generic List?	public static bool IsGenericList(Type type)\n{\n  if (!type.IsGenericType)\n    return false;\n  var genericArguments = type.GetGenericArguments();\n  if (genericArguments.Length != 1)\n    return false;\n\n  var listType = typeof (IList<>).MakeGenericType(genericArguments);\n  return listType.IsAssignableFrom(type);\n}	0
25023929	25009764	how to test themethod returns the correct value and set the correct values in another variable?	public static class FluentAssertionsExtensions\n{\n    public static void ShouldBeEquivalentWithOrder<T>(this IEnumerable<T> enumerable1, IEnumerable<T> enumerable2)\n    {\n        enumerable1 = enumerable1.ToList(); // to materailize the collection\n        enumerable2 = enumerable2.ToList(); // to materailize the collection\n        enumerable1.Should().ContainInOrder(enumerable2); \n        enumerable2.Should().ContainInOrder(enumerable1); // to meke sute enumerable2 is not just a subset of enumerbale1\n    }\n}	0
15635253	15635120	Validating certain parts of input string using Fluent Validation	.Must(str => str.StartsWith("adm"))	0
15287828	15287805	Select Multiple elements in a row using Linq	var users = MyTable.AsEnumerable()\n  .Select(x => \n     new { Col1 = x.Field<string>("Col1"), Col2 = x.Field<string>("Col2")})\n  .ToList();	0
668780	666823	Writing to the command line in a windowed app	using System;\nusing System.Collections.Generic;\nusing System.Windows.Forms;\nusing System.Runtime.InteropServices;\n\nnamespace PEFixer\n{\n    static class Program\n    {\n        [DllImport("kernel32.dll")]\n        private static extern bool AttachConsole(int dwProcessId);\n\n        /// <summary>\n        /// The main entry point for the application.\n        /// </summary>\n        [STAThread]\n        static int Main(string[] args)\n        {\n            if (args.Length > 0)\n            {\n                AttachConsole(-1);\n                return Form1.doTransformCmdLine(args);\n            }\n            else\n            {\n                Application.EnableVisualStyles();\n                Application.SetCompatibleTextRenderingDefault(false);\n                Application.Run(new Form1());\n            }\n            return 0;\n        }\n    }\n}	0
28469174	28468815	New Windows C# Build Causes App to Lose Saved Preferences	%USERPROFILE%\Local Settings\Application Data\<Company Name>\<appdomainname>_<eid>_<hash>\<verison>\user.config	0
22625875	22625835	how to create a table having spaces between the words?	string s = "CREATE TABLE ["+"" + rchtxtFieldCode.Text + "] "+ " (" + rchFieldTitle.Text + " " + combDataType.Text + "" + ")";\n                       //^_______________________________^	0
3572250	3572186	How to open save file dialog when i click on ok of a Message Box	MessageBox.Show("Save The Current File");\n            if (Convert.ToBoolean( DialogResult.OK ))\n            {\n                SaveFileDialog saveFileDialog1 = new SaveFileDialog();\n                saveFileDialog1.InitialDirectory = @"C:\";                  \n                saveFileDialog1.RestoreDirectory = true;\n\n                if (saveFileDialog1.ShowDialog() == DialogResult.OK)                    \n                    string s= saveFileDialog1.FileName;                    \n            }	0
14760229	14758680	IDBCommand Parameters for multi-line insert	IDbCommand cmd = new SqlCommand();\nStringBuilder sb = new StringBuilder();\nsb.Append("insert into foo(col, col2, col3), values");\nint parms = 0;\n\nfor(int i = 0 ; i<3; i++)\n{\n    sb.AppendFormat("( @{0}, @{1}, @{2}),", parms, parms + 1, parms + 2);\n    cmd.Parameters.Add(new SqlParameter((parms++).ToString(), ""));\n    cmd.Parameters.Add(new SqlParameter((parms++).ToString(), ""));\n    cmd.Parameters.Add(new SqlParameter((parms++).ToString(), ""));\n}\nsb.Append(";");\ncmd.Parameters;\ncmd.CommandText = sb.ToString().Replace(",;", ";");	0
27978253	27937260	Failed to retrieve data from the database. Details: [Database Vendor Code: 1370 ] in Crystal Reports using ASP.ET	string databaseName = "hr";\n    string serverName = "hr_domain"; // DSN Name\n    string userID = "xxxxxxx";\n    string pass = "xxxxxxxx";\n    protected void btn_search_Click(object sender, EventArgs e)\n    {\n        CrystalReportViewer1.Visible = true;\nReportDocument reportDocument = new ReportDocument();\n        string reportPath = Server.MapPath(@"~/GeneralEmpReports/test.rpt");\n        reportDocument.Load(reportPath);\n        reportDocument.SetDatabaseLogon(userID, pass, serverName, databaseName);\n        reportDocument.SetParameterValue("D", tbx_ddoCode.Text.ToUpper());\n        CrystalReportViewer1.ReportSource = reportDocument;\n    }	0
9028959	9028794	C# how to trigger a callback?	void button1_Click(object sender, EventArgs e) {\n    button1.Enabled = false;\n    BeginAsyncOperation(updateUI);\n}\nvoid BeginAsyncOperation(Action operation) {\n    operation.BeginInvoke(OnAsyncCallback, null);\n}\nvoid OnAsyncCallback(IAsyncResult result) {\n    if(result.IsCompleted) {\n        if(!InvokeRequired)\n            callback();\n        else BeginInvoke(new Action(callback));\n    }\n}\n//\npublic void callback() {\n    button1.Enabled = true;\n    // something else\n}\npublic void updateUI() {\n    // long function....doing 10s\n    System.Threading.Thread.Sleep(10000);\n}	0
122354	121662	Implementing User-Controlled Style Changes in ASP.NET	Imports System.Drawing\n\nPrivate Function createImage(ByVal srcPath As String, ByVal fg As Color, ByVal bg As Color) As Bitmap\n    Dim img As New Bitmap(srcPath)\n    For x As Int16 = 0 To img.Width\n        For y As Int16 = 0 To img.Height\n            If img.GetPixel(x, y) = Color.Black Then\n                img.SetPixel(x, y, fg)\n            Else\n                img.SetPixel(x, y, bg)\n            End If\n        Next\n    Next\n    Return img\nEnd Function	0
8531909	8531788	I want to keep checking the content of a label?	DependencyPropertyDescriptor dpd = DependencyPropertyDescriptor.FromProperty(ContentControl.ContentProperty, typeof(Label));\n            if (dpd != null)\n            {\n                dpd.AddValueChanged(label1, delegate\n                {\n                    // Add property change logic.\n                });\n            }	0
24661087	24661009	Extract sentence with a keyword	public static string Extract(string str, string keyword)\n{\n    string[] arr = str.Split('.');\n    string answer = string.Empty;\n\n    foreach(string sentence in arr)\n    {\n        //Add any other required punctuation characters for splitting words in the sentence\n        string[] words = sentence.Split(new char[] { ' ', ',' });\n        if(words.Contains(keyword)\n        {\n            answer += sentence;\n        }\n    }\n\n    return answer;\n}	0
29081813	29081706	How do I read each character for each "line" in a list (in order) C#	string line;\nusing (StreamReader reader = new StreamReader("C:\\temp\\test-1.txt"))\n{\n    while (reader.Peek() > -1)\n    {\n        line = reader.ReadLine();\n        foreach (char c in line)\n        {\n            Console.WriteLine(c);\n        }\n    }\n}	0
23053296	23053189	Joining two tables using LINQ and fetching few columns as result from both tables	public IQueryable GetAllCountry()\n {\n    using (Context context = new Context())\n    {\n    var countries = context.COUNTRY.Select(c => new\n     {\n         country = new\n          {\n              ID = c.ID,\n              Description = c.DESCRIPTION,\n              Currency = c.VFS_CURRENCY.CURRENCY_SYMBOL,\n              List<Language> = context.LANGUAGE.Where( l => l.Currency_ID ==c.COUNTRY.CURRENCY_ID}).ToList()//I just guess your LANGUAGE table has Currency_ID column\n           }\n         });\n\n            return countries;\n        }\n\n    }	0
5415102	5414997	wp7 Date Formatting during Binding	public string OilChangedDisplayDate\n{\n    get { return OilChangedDate.ToShortDateString(); }\n}	0
30480722	30480637	Represent a Number as a Binary in C#	Checkbox1.Checked = value & 1;\nCheckbox2.Checked = value & 2;\nCheckbox3.Checked = value & 4;\nCheckbox4.Checked = value & 8;	0
31844011	31843970	How to get data from datagridview using loop	for (int i = 0; i < dataGridView1.RowCount; i++)\n{\n    //Add items in the listview\n    string[] arr = new string[2];\n    ListViewItem itm;\n\n    //Add first item\n    arr[0] = dataGridView1.Rows[i+1].Cells["F1"].Value.ToString();\n    arr[1] = "Send";\n    itm = new ListViewItem(arr);\n    listView1.Items.Add(itm);\n\n}	0
30784917	30784508	Progressbar for filling TextBox using MVVM Light Toolkit in WinRT	public string FirstName\n    {\n        get\n        {\n            return this.firstName;\n        }\n        set\n        {\n            if (this.firstName != value)\n            {\n                bool oldValueIsEmpty = String.IsNullOrWhiteSpace(this.firstName);\n                this.firstName = value;\n                this.RaisePropertyChanged(() => this.FirstName);\n\n                var vm1 = (new ViewModelLocator()).MainViewModel;\n                if (String.IsNullOrWhiteSpace(value))              //   Checks the string length \n                {\n                    vm1.ProgressPercent -= 3;\n                }\n                else if (oldValueIsEmpty)\n                {\n                    vm1.ProgressPercent += 3;\n                }\n            }\n        }\n    }	0
30123177	30123127	Merge two dynamic lists and override values	from x in list1.Concat(list2)\ngroup x by x.Id into g\nselect new {\n   Id = g.Key,\n   LikesRed = g.Any(x => x.LikesRed),\n   LikesBlue = g.Any(x => x.LikesBlue)\n}	0
10251355	10249120	Creating FTP client for asp with C#	void UploadFile(Stream object)	0
10611852	10611835	Export To Excel - Issue with "&" in a QueryString	Server.UrlEncode	0
19503897	19503131	LINQ to XML - finding Elements inside only certain Parent/Ancestor Elements	Root.Descendants(ns + "entry")\n    .Select(elem=>elem.Descendants(ns + "title").Single());	0
9944437	9943751	XML to JSON conversion accessing member in C#	XmlDocument xDoc = new XmlDocument();\nxDoc.LoadXml(xstr);\nstring jsonText = JsonConvert.SerializeXmlNode(xDoc);\n\n\nJObject jObj = (JObject)JsonConvert.DeserializeObject(jsonText);\nstring air = jObj["Segment"]["@xsi:type"].ToString();\n//or\ndynamic jObj = JsonConvert.DeserializeObject(jsonText);\nstring air = jObj.Segment["@xsi:type"];	0
16650917	16490951	Enterprise Library logging to filter by category like some value	using Microsoft.Practices.EnterpriseLibrary.Common.Configuration;\nusing Microsoft.Practices.EnterpriseLibrary.Logging;\nusing Microsoft.Practices.EnterpriseLibrary.Logging.Configuration;\nusing Microsoft.Practices.EnterpriseLibrary.Logging.Filters;\nusing System;\nusing System.Linq;\n\n[ConfigurationElementType(typeof (CustomLogFilterData))]\npublic class RhinoFilter : LogFilter\n{\n    public RhinoFilter(string name)\n        : base(name)\n    {\n    }\n\n    public RhinoFilter(NameValueCollection settings) \n        : this("RhinoFilter")\n    {\n    }\n\n    public override bool Filter(LogEntry log)\n    {\n        return log.Categories.Any(x => x.StartsWith("Rhino."));\n    }\n}	0
3796437	3796290	SQL To Get Parent From Self Referencing Table	WITH ObjectHierarchy (ItemID, Name, ParentID, Level) AS\n(\n   SELECT \n      ItemID, \n      Name, \n      ParentID, \n      1 as Level \n   FROM Item it, Object ob\n   WHERE it.ParentID = ob.ObjectID\n   AND ob.ItemID = @itemIdToBeSearched\n\n   UNION ALL\n\n   SELECT\n      i.ItemID,\n      i.Name,\n      i.ParentID,\n      oh.Level + 1 AS Level\n   FROM Item i\n   INNER JOIN ObjectHierarchy oh ON\n      i.ParentID = oh.ItemID\n   AND oh.ItemID = @itemIdToBeSearched\n\n)\n\nSELECT parentID\nFROM ObjectHierarchy \nWHERE LEVEL = 1	0
16811905	16811859	how to display textBox control in MessageBox?	.DisplayModal()	0
793332	793271	Program hangs, waiting for input that I can never give	this.tl = new TcpListener(IPAddress.Any, PORT);\ntl.Start();\nwhile(true)\n{\n  TcpClient tcl = tl.AcceptTcpClient();\n  TcpHelper th = new TcpHelper(tcl,conf);\n  new Thread(new ThreadStart(th.Start)).Start();\n  //t.Start();\n}	0
16442521	16442286	Deleting a large number of records takes a VERY long time	var deleteOld = "DELETE FROM CpuMeasurements WHERE curr.Timestamp < {0}";\nmsdc.ExecuteStoreCommand(deleteOld, oldestAllowedTime);	0
33108763	33108603	Remove item from List C#	var itemsToDelete = allData.Where(w => !library.Any(p => p.Id == w.Id && p.Nbr == w.Nbr)).ToList();	0
2267714	2267668	How to obtain app.config of a different application and modify it	ExeConfigurationFileMap fileMap2 \n                = new ExeConfigurationFileMap();\n            fileMap2.ExeConfigFilename = @"OtherFile";\n\n            Configuration config2 =\n              ConfigurationManager.OpenMappedExeConfiguration(fileMap, ConfigurationUserLevel.None);\n\n            ConnectionStringSettings newSettings = \n                config.ConnectionStrings.ConnectionStrings["oldSConString"];\n\n            ConnectionStringsSection csSection \n                = config2.ConnectionStrings;\n\n            csSection.ConnectionStrings.Add(newSettings);                \n            config2.Save(ConfigurationSaveMode.Modified);	0
32859791	32858164	Set crystal report textobject bold at runtime using C#	System.Drawing.Font font1 = new System.Drawing.Font("Arial", 12, FontStyle.Bold);\ntxtTest.ApplyFont(font1);	0
6283990	6283952	How can I perform a numerically-valid sort using strings?	pageList.Sort((a, b) => Int32.Parse(a.ImageName.Replace(".tif", "")).CompareTo(Int32.Parse(b.ImageName.Replace(".tif","")))	0
27468213	27464494	Correct implementation of WPF custom MessageBox using MVVM pattern	void Current_DispatcherUnhandledException(object sender, DispatcherUnhandledExceptionEventArgs e)\n{\n    CustomMessageBoxViewModel messageBox = new CustomMessageBoxViewModel();\n    messageBox.Sender = sender;\n    messageBox.Exception = e.Exception;\n    CustomMessageBoxWindow messageBoxWindow = new CustomMessageBoxWindow();\n    messageBoxWindow.DataContext = messageBox;\n    messageBoxWindow.ShowDialog();\n\n    e.Handled = true;\n}	0
15569518	15569062	C# 3 argument checkbox DataView.RowFilter Filtering with multiple columns	StringBuilder filter = new StringBuilder();\n\nif(a.checked)\n   filter.Append("filter here");\n\nif(b.checked)\n    filter.Append("filter here");\n\nviews.RowFilter= filter.toString();	0
7344237	7344126	Generate all possible sequences from an Enumerable<int>	public static IEnumerable<List<T>> GetPermutations<T>(IEnumerable<T> items)\n    {\n        if (!items.Any()) \n            yield return new List<T>();\n        foreach (var i in items)\n        {\n            var copy = new List<T>(items);\n            copy.Remove(i);\n            foreach(var rest in GetPermutations(copy))\n            {\n                rest.Insert(0, i);\n                yield return rest;\n            }\n        }\n    }\n\n    public static IEnumerable<IEnumerable<T>>  GetEnumPermutations<T>(IEnumerable<T> items )\n    {\n        return GetPermutations(items);\n    }	0
6171294	6171238	How to set a default initialization cookie in ASP.NET MVC	public class LocalizationAwareAttribute : ActionFilterAttribute\n{\n    public override void OnActionExecuting(ActionExecutingContext filterContext)\n    {\n        var httpContext = filterContext.HttpContext.Current;\n\n        if (!httpContext.Cookies.Keys.Contains("language"))\n        {\n            httpContext.Response.AppendCookie(new HttpCookie("language", 1));\n        }\n        if (!httpContext.Cookies.Keys.Contains("country"))\n        {\n            httpContext.Response.AppendCookie(new HttpCookie("country", 7));\n        }\n    }\n}	0
19362677	19361206	Finding the Gap Numbers in a list	var openTags =\n    from item in source                           // Take the source items\n    group item by item.tagNo into g               // and group them by their tagNo.\n    let inUse = g.Select(_ => _.TermNo)           // Find all of the in-use tags\n    let max = inUse.Max()                         // and max of that collection.\n    let range = Enumerable.Range(1, max - 1)      // Construct the range [1, max)\n    select new\n    {                               // Select the following\n       TagNo = g.Key                // for each group\n       TermNo = range.Except(inUse) // find the available tags\n    };	0
12775615	12633982	How do I do Sub Object Custom Validation mvc3	foreach (var detail in this.Details)\n{\n   var validationResults = detail.Validate(validationContext);\n   foreach (var validationResult in validationResults)\n   {\n      yield return validationResult;\n   }\n}	0
1070957	1066102	How to use Terminal Services Gateway with the IMsRdpClient6 ActiveX Control?	MSTSCLib6.IMsRdpClient6 client6 = RdpClient.GetOcx() as MSTSCLib6.IMsRdpClient6;            \n\n        if (client6 != null)\n        {\n            MSTSCLib6.IMsRdpClientTransportSettings2 transport = client6.TransportSettings2;\n\n            if (Convert.ToBoolean(transport.GatewayIsSupported) == true)\n            {\n                client6.TransportSettings.GatewayHostname = "mygateway";\n                client6.TransportSettings.GatewayUsageMethod = 1;\n\n                client6.TransportSettings.GatewayCredsSource = 0;\n                client6.TransportSettings.GatewayProfileUsageMethod = 1;\n                client6.TransportSettings2.GatewayDomain = "mydomain";\n                client6.TransportSettings2.GatewayPassword = "mypassword";\n                client6.TransportSettings2.GatewayUsername = "myusername";\n            }\n        }	0
22142491	22142280	Invoking VB.Net Structure Property from C#	string string2 = the_structure.MyProperty;	0
31019736	31019324	Defining a Navigation property in EF 5, Code first migrations	[Table("Files")]\npublic class Files\n{\n    [Key]\n    [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]\n    [Display(Name = "FileID")]\n    public int FileID { get; set; }\n\n    [Required]\n\n    [Display(Name = "For User")]\n    public int UserId { get; set; }\n\n\n    [Display(Name = "Description")]\n    public string Desc { get; set; }\n\n    [Required]\n    [Display(Name = "Document Upload")]\n    public string DocumentPath { get; set; }\n\n    [ForeignKey("UserId")] // this is what I have tried\n    public virtual UserProfile UserProfile { get; set; }\n}	0
19839515	19839278	How to click button from form 1 and button from another form already clicking	private void button1_Click(object sender, EventArgs e)\n{\n    ths.button1_2.PerformClick();\n}	0
3902154	3902126	Platform Invoke, bool, and string	[DllImport("MyDll.dll")]\ninternal static extern void f( [MarshalAs(UnmanagedType.I1)] bool x );\n[DllImport("MyDll.dll")]\n[return: MarshalAs(UnmanagedType.LPStr)]\ninternal static extern string g();	0
17685315	17667988	C# - mouse hover in taskbar, thumbnails preview is generated in window 7.	[DllImport( "dwmapi.dll", PreserveSig = false )]\npublic static extern void DwmRegisterThumbnail( IntPtr destinationWindowHandle, IntPtr sourceWindowHandle, out IntPtr thumbnailHandle );\n\n[DllImport( "dwmapi.dll", PreserveSig = false )]\npublic static extern void DwmUnregisterThumbnail( IntPtr thumbnailHandle );\n\n[DllImport( "dwmapi.dll", PreserveSig = false )]\npublic static extern void DwmUpdateThumbnailProperties( IntPtr thumbnailHandle, ref ThumbnailProperties properties );	0
1197004	1196991	Get property value from string using reflection in C#	public static object GetPropValue(object src, string propName)\n {\n     return src.GetType().GetProperty(propName).GetValue(src, null);\n }	0
27210621	27210464	Create MemberExpression from a navigation property selector string, C#?	Employee employee = new Employee()\n{\n    Section = new Section() { SectionName = "test" }\n};\nMemberExpression sectionMember = Expression.Property(ConstantExpression.Constant(employee), "Section");\nMemberExpression sectionNameMember = Expression.Property(sectionMember, "SectionName");	0
4948107	4947868	generic field getter for a DataRow	public static T? GetValue<T>(this DataRow row, string field) where T : struct\n{\n    if (row.IsNull(field))\n        return new T?();\n    else\n        return (T?)row[field];\n}\n\npublic static T GetReference<T>(this DataRow row, string field) where T : class\n{\n    if (row.IsNull(field))\n        return default(T);\n    else\n        return (T)row[field];\n}	0
1089863	1077777	A product release changes its library name, how to be compatible with old and new?	private bool _useOldMethodName = false;\npublic void MethodAlias(string arg1)\n{\n    if (_useOldMethodName)\n    {\n        Reference.OldFunctionName(arg1);\n    }\n    else\n    {\n        try\n        {\n            Reference.NewFunctionName(arg1);\n        }\n        catch (MethodNotFoundException mnfe)\n        {\n            _useOldMethodName = true;\n        }\n    }\n}	0
166207	166174	How can I convert List<object> to Hashtable in C#?	var dict = myList.Cast<Foo>().ToDictionary(o => o.Description, o => o.Id);	0
21055093	21054861	htmlagilitypack getting field-item	hdoc2.DocumentNode.SelectNodes("//items/div[starts-with(@class, 'item')]/text()");	0
17283425	17283208	MySQL C# Find Lat Lon entries within a certain max distance	IQueryable<myTable> busLst = (from b in db.myTable.AsEnumerable()\n                                             where (3959 * Math.Acos(Math.Cos(radians(latLonRequest.lat)) * Math.Cos(radians(b.lat))\n                                            * Math.Cos(radians(b.lon) - radians(latLonRequest.lon)) + Math.Sin(radians(latLonRequest.lat)) *\n                                            Math.Sin(radians(b.lat)))) < latLonRequest.MaxDistance\n                                             select b\n                                            );	0
19315986	19315799	Create a dictionary from enum values	var res = Enum.GetValues(typeof(TEnum)).Cast<TEnum>().ToDictionary(e => e + "_" + (int)(object)e, e => e.ToString());	0
33864414	33864205	How to rename a file while uploading	string createfolder = "E:/tmp/jobres/" + uId;\n\nSystem.IO.Directory.CreateDirectory(createfolder);\n\n//AsyncFileUpload1.SaveAs(Path.Combine(createfolder,"Give Something Here whatever is changing at all time like time value"+AsyncFileUpload1.PostedFile.FileName));\n\nAsyncFileUpload1.SaveAs(Path.Combine(createfolder,"DateTime.Now"+AsyncFileUpload1.PostedFile.FileName));	0
29515456	29515290	EF doesn't saving foreign data	using(MyEntities me = new MyEntities())\n{\n    Contact ct = me.Contact.Include("Location").SingleOrDefault(x=>x.User.UserID == WebSecurity.CurrentUserId);\n    ct.Titile = "sometitle"; //assignment and saving works\n    ct.Location = me.Location.SingleOrDefault(x=>x.Location_ID == 19); //only assignment works\n    me.SaveChanges();\n}	0
19347559	19347483	Linking txt file info with other file	public class Student\n{\n    public Student()\n    {\n        Marks = new List<StudentMark>();\n    }\n    public string Name { get; set; }\n    public List<StudentMark> Marks { get; set; }\n\n    public void Load(string line)\n    {\n        string[] parts = line.Split(' ');\n        Name = parts[0];\n        //Other properties, if any:\n        //LastName = parts[1];\n    }\n}\npublic class StudentMark\n{\n    public float Mark { get; set; }\n    public string Lesson { get; set; }\n}	0
2798241	2798215	Hide TabControl buttons to manage stacked Panel controls	using System;\nusing System.Windows.Forms;\n\nclass StackPanel : TabControl {\n  protected override void WndProc(ref Message m) {\n    // Hide tabs by trapping the TCM_ADJUSTRECT message\n    if (m.Msg == 0x1328 && !DesignMode) m.Result = (IntPtr)1;\n    else base.WndProc(ref m);\n  }\n}	0
6131923	6131636	Send byte[] from c# via Win32 SendMessage	WM_ COPYDATA	0
17719137	17712416	How to Handle Primary Key in Entity Framework 5 Code First	context.Record.AddOrUpdate(c => c.RecordName, new Record()\n            {\n                RecordName = "New Record",\n                Created = DateTime.UtcNow,\n                Updated = DateTime.UtcNow,\n             })	0
24869586	24531381	Populate a winform label dynamically from values in a single radlistview	void radListView1_ItemCheckedChanged(object sender, ListViewItemEventArgs e)\n{\n    string text = "";\n    foreach (ListViewDataItem item in radListView1.CheckedItems)\n    {\n        text += item.Text + ", ";\n    }\nradLabel1.Text = text;\n}	0
458940	458913	How to get the table a foreign key refers to	foreach (ForeignKey key in currentTable.ForeignKeys)\n{\n    foreach (ForeignKeyColumn column in key.Columns)\n    {\n        Console.WriteLine("Column: {0} is a foreign key to Table: {1}",column.Name,key.ReferencedTable);\n    }\n}	0
9034324	9034233	How to cyclically play video from one position to another using MediaElement in WPF	TimeSpan startTime = TimeSpan.FromSeconds(45);\nTImeSpan endTime = TimeSpan.FromSeconds(55);\nint timeDifference = endTime.TotalSeconds - startTime.TotalSeconds;\n\nmediaElement.Position = startTime;\n\nTimer t = new Timer() { Interval = timeDifference * 1000, AutoReset = true };\nt.Tick += (sender, e) { mediaElement.Position = startTime };\nt.Start();	0
1399015	1399008	How to convert a relative path to an absolute path in a Windows application?	string absolute = Path.GetFullPath(relative);	0
9405515	9405368	Disabling the EF Object graph for a query	var entities = dbContext.MyEntities.Where(/**/).AsNoTracking();	0
13522593	13522285	How to get the selected line in a Text Box?	Rect rec = textbox.GetRectFromCharacterIndex(textbox.SelectionStart);\n        double rectop = rec.Top;\n        double lineheight = text.LineHeight;\n        int result = (int)(rectop / lineheight + 1);	0
20788405	20784409	take query from sql by LINQ	var j = (from a in linqedit.Kharids    \n     join k in linqedit.KalaNames on a.KalaName_ref equals k.ID   \n      join n in linqedit.KindOfKharids on a.KindOfKharid_ref equals n.ID \n         into temptbl\n         from m in temptbl.DefaultIfEmpty()\n     join g in linqedit.VahedeKharids on a.Vahedekharid_ref equals g.ID\n     select new\n     {\n         a.ID,\n         ???_???? = k.Name,\n         ????? = a.mount.Value,\n         ????_???? = g.Name,\n         ???? = a.Price,\n         ???_???? = n.Name,\n         ???_?????? = a.NameKHaridar,\n         ????? = a.Date.Date.Year + "/" + a.Date.Date.Month + "/" + a.Date.Date.Day\n     }).ToList();	0
18146142	18145721	Wait for all child processes of a ran process to finish C#	int counter == 0;\n     .....\n\n     //start process, assume this code will be called several times\n     counter++;\n     var process = new Process ();\n     process.StartInfo = new ProcessStartInfo(file);\n\n     //Here are 2 lines that you need\n     process.EnableRaisingEvents = true;\n     //Just used LINQ for short, usually would use method as event handler\n     process.Exited += (s, a) => \n    { \n      counter--;\n      if (counter == 0)//All processed has exited\n         {\n         ShowWindow(Game1.Handle, SW_RESTORE);\n        SetForegroundWindow(Game1.Handle);\n         }\n    }\n    process.Start();	0
4689986	4689861	How to measure the size of a C# program	FileInfo fi = new FileInfo(Assembly.GetEntryAssembly().Location);\nConsole.WriteLine(fi.Length);	0
239359	238413	Lambda Expression Tree Parsing	public class Class1\n{\n    public string Selection { get; set; }\n\n    public void Sample()\n    {\n        Selection = "Example";\n        Example<Book, bool>(p => p.Title == Selection);\n    }\n\n    public void Example<T,TResult>(Expression<Func<T,TResult>> exp)\n    {\n        BinaryExpression equality = (BinaryExpression)exp.Body;\n        Debug.Assert(equality.NodeType == ExpressionType.Equal);\n\n        // Note that you need to know the type of the rhs of the equality\n        var accessorExpression = Expression.Lambda<Func<string>>(equality.Right);\n        Func<string> accessor = accessorExpression.Compile();\n        var value = accessor();\n        Debug.Assert(value == Selection);\n    }\n}\n\npublic class Book\n{\n    public string Title { get; set; }\n}	0
21461160	21461113	Customised method for List collection based on a type	public static List<LatestNewsCategory> getUniqueCategories(this IList<LatestNews> list)	0
21783663	21783609	Check wether a value is present in a different list	var ids = rsearch.hosts.Select(c => c.HostID).ToList();\n\nrsearch.hostservices = db.Services\n.Where(j => ids.Contains(j.HostID)).ToList();	0
7742670	7742511	C# Controlling access to an array property element	public class IndexedClass\n{\n    // Property \n    public byte this[int index]\n    {\n        get\n        {\n            return myList[index];\n        }\n        set\n        {\n            Modified = !myList[index].Equals(value);\n            myList[index] = value;\n        }\n    }\n\n}\n\npublic class IndexedClassGroup\n{\n    // Property \n    public IndexedClass this[int index]\n    {\n        get\n        {\n            return myList[index];\n        }\n        set\n        {\n            Modified = !myList[index].Equals(value);\n            myList[index] = value;\n        }\n    }\n\n}	0
32190928	32148959	.NET: Retrieving Data From parse database	public async void GetData()\n{\n    ParseClient.Initialize("app_key", ".net_key");\n    var query1 = ParseObject.GetQuery("test").WhereEqualTo("objectId", "xxxxxxxx");\n    var result = await query1.FindAsync();\n}	0
23018086	23015770	Reading from Excel dynamically in C#	Range excelRange = sheet.UsedRange;\nobject[,] valueArray = (object[,])excelRange.get_Value(\n    XlRangeValueDataType.xlRangeValueDefault);	0
32859575	32859467	Search a substring in another string	string name = "BLK000012345summary.pdf";\nstring fileName = "20150929111111zp2zq23BLK000012345summary.pdf";\n\nbool value = fileName.Contains(name);	0
2981241	2979432	Directory file size calculation - how to make it faster?	private static long DirSize(string sourceDir, bool recurse)\n    {\n        long size = 0;\n        string[] fileEntries = Directory.GetFiles(sourceDir);\n\n        foreach (string fileName in fileEntries)\n        {\n            Interlocked.Add(ref size, (new FileInfo(fileName)).Length);\n        }\n\n        if (recurse)\n        {\n            string[] subdirEntries = Directory.GetDirectories(sourceDir);\n\n            Parallel.For<long>(0, subdirEntries.Length, () => 0, (i, loop, subtotal) =>\n            {\n                if ((File.GetAttributes(subdirEntries[i]) & FileAttributes.ReparsePoint) != FileAttributes.ReparsePoint)\n                {\n                    subtotal += DirSize(subdirEntries[i], true);\n                    return subtotal;\n                }\n                return 0;\n            },\n                (x) => Interlocked.Add(ref size, x)\n            );\n        }\n        return size;\n    }	0
16970686	16964036	Cannot use Server.MapPath to access a external file	Server.MapPath("folder/conf.xml.config")	0
7978773	7978483	Need help to validate existing group of records	var results = from t1 in DataContext.Table1\n                      join t2 in DataContext.Table2 on t1.Pid equals t2.Pid\n                      where t1.Pid == 1\n                      select t2.Cid;	0
7491450	7491419	C# Bitwise Operator With Ints	3:  0011\n    1:  0001\n\n3 & 1:  0001	0
4978770	4978755	How do I convert a string to currency with two decimal places in C#?	TotalValueLabel.Text = source.Rows[0][0].ToString("c");	0
18761182	18761004	How to check if any pdf file exists on server?	string[] files = System.IO.Directory.GetFiles(Server.MapPath("/somepath"), "*.txt");	0
2493068	2493032	How to get the last day of a month?	DateTime.DaysInMonth(1980, 08);	0
30765658	30763954	How do you save selected ComboBox items into a .txt file	public partial class MainWindow : Window \n{ \n    public MainWindow() \n    { \n          InitializeComponent(); \n    } \n    private void SaveButt_Click(object sender, RoutedEventArgs e) \n    {           \n          File.WriteAllText("C:\\file.txt", "Hello World!"); \n    } \n}	0
27253058	27252328	Outlook Interop ClearSelection Method	e.Data.GetData(?RenPrivateMessages?);	0
8755534	8715161	Read the calculated values from Excel using AddIn Formulas and Microsoft Object Library	string path = @"C:\Test2.xls";\n        string xlaPath = @"C:\Test2.xla";\n        Workbook theWorkbook;\n        Worksheet theWorksheet, theWorksheet2;\n        Range readRange;\n        Microsoft.Office.Interop.Excel.Application app = new Microsoft.Office.Interop.Excel.Application();\n        app.Workbooks.Open(xlaPath);\n        theWorkbook = app.Workbooks.Open(path);\n        theWorksheet2 = (Worksheet)theWorkbook.Worksheets.get_Item("Sheet2");\n        theWorksheet2.get_Range("A3").Value = 7;\n        theWorksheet2.get_Range("A4").Value = 7;\n        theWorkbook.RefreshAll();\n\n        theWorksheet = (Worksheet)theWorkbook.Worksheets.get_Item("Sheet1");           \n        readRange = theWorksheet.get_Range("A1");\n        Console.WriteLine(Convert.ToString(readRange.Value));\n        Console.ReadLine();            //theWorkbook.Save();             \n        theWorkbook.Close();\n        app.Workbooks.Close();	0
12637044	12636991	How to run .exe from C#	Process.Start(@"C:\ndfd\degrib\bin\degrib", \n              @"D:\Documents\Pacificwind.grb -C -msg 1 -Csv");\n\nProcess.Start(@"C:\ndfd\degrib\bin\degrib", \n              @"D:\Documents\Pacificwind.grb -C -msg all -nMet -Csv")	0
9885505	9885437	Creating a Custom Event	public class Metronome\n    {\n        public event TickHandler Tick;\n        public EventArgs e = null;\n        public delegate void TickHandler(Metronome m, EventArgs e);\n        public void Start()\n        {\n            while (true)\n            {\n                System.Threading.Thread.Sleep(3000);\n                if (Tick != null)\n                {\n                    Tick(this, e);\n                }\n            }\n        }\n    }\n    public class Listener\n    {\n        public void Subscribe(Metronome m)\n        {\n            m.Tick += new Metronome.TickHandler(HeardIt);\n        }\n    }\n    class Test\n    {\n        static void Main()\n        {\n            Metronome m = new Metronome();\n            Listener l = new Listener();\n            l.Subscribe(m);\n            m.Start();\n        }\n    }	0
24393065	24392790	How to output dataGrid Column to Labels?	private void cmdBot_Click(object sender, EventArgs e)\n{\n    labels = new List<Label>();\n\n    for (int i = 0; i <= dataGridView1.RowCount; i++)\n    {\n        Label gecoLabel = new Label();\n        //**Since you're already looping through every row, why not just set the label text at the same time?\n        gecoLabel.Text = dataGridView1.Rows[i].Cells["link"].FormattedValue.ToString();\n        gecoLabel.AutoSize = true;\n        gecoLabel.Location = new Point(100, 10 * i);\n        groupBox1.Controls.Add(gecoLabel);\n\n        labels.Add(gecoLabel);\n    }	0
5183467	5183354	Crystal Reports Omitting Data	WHERE state <> 'TX'	0
20893940	20893395	Deserialize JSON to multiple properties	public class MyObject\n{\n    public ChildObject MyChildObject;\n    public string MyChildObjectId;\n\n    [JsonProperty("ChildObject")]\n    public object ChildObject\n    {\n        get\n        {\n            return MyChildObject;\n        }\n        set\n        {\n            if (value is JObject)\n            {\n                MyChildObject = ((JToken)value).ToObject<ChildObject>();\n                MyChildObjectId = MyChildObject.Id;\n            }\n            else\n            {\n                MyChildObjectId = value.ToString();\n                MyChildObject = null;\n            }\n        }\n    }\n}	0
18328718	18309459	FileNotFoundException in c# connected with some dll	if (comboBox1.SelectedItem.ToString() == "master" && comboBox2.SelectedItem.ToString() == "master.sql")\n{\noConnection.Open();\n***SqlCommand SqlCmd = new SqlCommand();\nSqlCmd.CommandText = textentry;\nSqlCmd.Connection = oConnection;\nvar output = SqlCmd.ExecuteNonQuery();***\nif (MessageBox.Show("Execute " + comboBox2.SelectedItem.ToString() + " in the database " + comboBox1.SelectedItem.ToString() + " ?", "Execute?", MessageBoxButtons.YesNo) == DialogResult.Yes)\n{\n if (!output.Equals(0))\n    {\n        try\n        {\n            MessageBox.Show(comboBox2.SelectedItem.ToString() + " executed successfully in " + comboBox1.SelectedItem.ToString() + " database");\n        }\n        catch (Exception exc)\n        {\n            MessageBox.Show("Script Execution Failed,"+exc);\n        }\n    }\n}\nelse\n{\n    MessageBox.Show("Execution cancelled by the user");\n}\nelse\n{\n    MessageBox.Show("Either the database or the sql script file selected is wrong!!");\n}	0
33180269	33180180	sharing source file between two projets in one solution	using hello.Helpers;	0
11033587	11033218	Adding attributes to POCO properties for mapping x,y cells	public class SpreadSheetCell\n{\n    public int X {get; set;}\n    public int Y {get; set;}\n    public string Contents {get; set;}\n}\n\n...\nSpreadSheetCell[,] spreadSheet = new SpreadSheetCell[100,100];\nspreadSheet[1, 2] = new SpreadSheetCell\n                        {\n                          X = 1,\n                          Y = 2,\n                          Contents = "Something goes here..."\n                        };	0
18335783	18335754	Correct way to parse a String to DirectoryInfo?	if(di.Exists)	0
9846664	9846613	Is it possible to perform a linq query with string concatenation instead of identifiers?	.Where("Name = @0 AND AuthoredDate = \"" + dateKey + "\"")	0
21730189	21729487	Saving a media player video in the folder	private void button3_Click(object sender, EventArgs e)\n {\n     OpenFileDialog openFileDialog1 = new OpenFileDialog();\n     if (openFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)\n     {\n          this.textBox1.Text = openFileDialog1.FileName;\n          File.Copy(openFileDialog1.FileName,\n                    Path.Combine(savevideo, Path.GetFileName(openFileDialog1.FileName)));\n     }\n }	0
11445012	11426008	How to Load items in comobox inside a datagrid Silverlight?	ItemSource={Binding Path=Roles, Source={StaticResource YourViewModel}}"	0
29841741	29841698	C# - combobox selected value	cmd.Parameters.AddWithValue("@TipAutocar",cmbTip.GetItemText(cmbTip.SelectedItem));	0
33638544	33615126	Use App Pool Credentials for WebClient Request	using (var impersonationContext = WindowsIdentity.Impersonate(IntPtr.Zero))\n{\n    try\n    {\n        // this code is now using the application pool indentity\n    }\n    finally\n    {\n        if (impersonationContext != null)\n        {\n            impersonationContext.Undo();\n        }\n    }\n}	0
13833135	13791254	A new FontStyle is applied to different locations in RichTextBox	int ct = 0;\n    private void button1_Click(object sender, EventArgs e)\n    {\n        richTextBox1.Text += "\n\r";\n        richTextBox1.Text += ct.ToString()+". "+textBox1.Text;\n        richTextBox1.Text += ", " + textBox2.Text;\n        form2.richTextBox1.Text += textBox2.Text + "\n";\n        ct = ct + 1;\n        using (StringReader reader = new StringReader(form2.richTextBox1.Text))\n        {\n            for (int i = 0; i < ct; i++)\n            {\n                string A = reader.ReadLine();\n                richTextBox1.Find(A, RichTextBoxFinds.MatchCase);\n                richTextBox1.SelectionFont = new Font(richTextBox1.Font, FontStyle.Italic);\n            }\n        }\n    }	0
24764635	24743158	How to set the count property of a related entity without having to perform an extra query or include unnecessary data	CREATE FUNCTION dbo.getStudentCount(@studentCount int)\nRETURNS int\nAS\nBEGIN\n    DECLARE @r int\n    select @r = COUNT(*) from Student where CampaignId = @studentCount\n    RETURN @r\nEND\nGO\n\nALTER TABLE Campaign ADD StudentCount AS dbo.getStudentCount(Id)	0
6415177	6415020	Use a text file as storage for a very simple web application, how to do locking?	FileStream.Lock()	0
30299447	30299235	How to loop all data in checkedlistbox? [Solved]	foreach (DataRowView item in clbPackages.Items)\n{\n    MessageBox.Show(item["PACKAGE_GROUP_NAME"].ToString());               \n}	0
8615679	8615627	How to start processes sequentially through code	Process.Start("yourprogram.exe").WaitForExit();\nProcess.Start("yournextprogram.exe").WaitForExit();	0
14918121	14917634	Pass Array to a WCF function	List<ServiceReference1.Student> wcfStudentList = new System.Collections.Generic.List<ServiceReference1.Student>();\n        foreach (var student in studentList)\n        {\n            wcfStudentList.Add(new ServiceReference1.Student()\n            {\n                ID = student.ID,\n                Name = student.Name,\n                ..etc..\n            });\n        }\n        var data = client.GetStudentData(wcfStudentList.ToArray());	0
11892086	11891788	Iterating a multidimensional string array with speed	Console.WriteLine("started");\nvar sw = System.Diagnostics.Stopwatch.StartNew();\nlong iterations = 0;\n\nvar width=5000;\nvar height=3;\nstring[] data = new string[width*height];\nfor (int i = 0; i < width; i++)\n{\n    string d1 = data[i];\n    string d2 = data[width+i];\n    string d3 = data[width*2+i];\n\n    for (int j = 0; j < width; j++)\n    {\n        string e1 = data[j];\n        string e2 = data[width+j];\n        string e3 = data[width*2+j];\n        Interlocked.Increment(ref iterations);\n    }\n    //});\n\n    Interlocked.Increment(ref iterations);\n}\nConsole.WriteLine("Finished {0} iterations in {1} seconds", iterations, sw.Elapsed.TotalSeconds);	0
29323219	29290919	Selecting documents between user-specified dates using linq with mongodb	DateTime ownLow = new DateTime(2015, 3, 28, 21, 28, 13, 0);\n        DateTime ownHigh = new DateTime(2015, 3, 28, 21, 28, 20, 0);\n\n        string stringLow = ownLow.ToString("yyyy-MM-ddTHH:mm:ss.fffffffZ");\n        string stringHigh = ownHigh.ToString("yyyy-MM-ddTHH:mm:ss.fffffffZ");\n\n        DateTime lowDate = Convert.ToDateTime(stringLow);\n        DateTime highDate = Convert.ToDateTime(stringHigh);	0
34327914	34327863	Javascript Or JQuery Split Alpha Numeric String	string.match(/[a-z]+|\d+/ig)	0
30795038	30795013	Generate HTML code in asp.net with qoutes in the string	Comment.InnerHtml = "<div class=\"col-md-4 img-portfolio\">"	0
10231803	10231555	How To Know Selected Radio Button in Codebehind	foreach (GridViewRow row in gridview.Rows)\n{\n    RadioButton radioBtn=new RadioButton();\n    radioBtn=(RadioButton)row.findcontrol("YourRadiobuttonId");\n    if(radioBtn.Checked)\n    {\n        // Your appropriate code here\n    }\n\n}	0
24030808	23671813	ResponstDTO with complex Property in ServiceStack	static public Func<JsonObject,Cart> fromJson = cart => new Cart(new CartDto {\n        Id = cart.Get<string>("id"),\n        SelectedDeliveryId = cart.Get<string>("selectedDeliveryId"),\n        SelectedPaymentId = cart.Get<string>("selectedPaymentId"),\n        Amount = cart.Get<float>("selectedPaymentId"),\n        AddressBilling = cart.Object("references").ArrayObjects("address_billing").FirstOrDefault().ConvertTo(AddressDto.fromJson),\n        AddressDelivery = cart.Object("references").ArrayObjects("address_delivery").FirstOrDefault().ConvertTo(AddressDto.fromJson),\n        AvailableShippingTypes = cart.Object("references").ArrayObjects("delivery").ConvertAll(ShippingTypeDto.fromJson),\n        AvailablePaypmentTypes = cart.Object("references").ArrayObjects("payment").ConvertAll(PaymentOptionDto.fromJson),\n        Tickets = cart.Object("references").ArrayObjects("ticket").ConvertAll(TicketDto.fromJson)\n    });	0
14498704	14498206	Running batch file with arguments from C#	Arguments = String.Format("\"{0}\" \"{1}\"", _sourcePath, _tempTargetPath) ???	0
19174797	19174616	Merging data of 2 datatable columns and displaying as 1 column in datatgridview	cmd2 = new OleDbCommand("Select TOP " + PageSize + " PatientID,PFirstName&' '&PLastName as 'Full Name',RegDate,MobileNo,PEmailID from Patient_Registration ORDER BY PatientID", con);	0
6691629	6690789	Cross-thread operation not valid: Control 'listBox1' accessed from a > thread other than the thread it was created on	void xmpp_OnPresence(object sender, Presence pres)\n    {\n  this.Invoke(new MethodInvoker(delegate()\n                {\n\nlistBox1.Items.Add(pres.From .User ); --- **HERE I AM GETTING ERROR.**\n\n   }));\n}	0
5376395	5376279	Delete row of 2D string array in C#	var arrayUpdated = new string[a.GetUpperBound(1)][a.GetUpperBound(0)-1];\nfor (int n = index; n < a.GetUpperBound(1); n++)\n{\n     for (int i = 0; i < a.GetUpperBound(0); i++)\n     {\n         arrayUpdated [i, n] = a[i, 1];\n     }\n}	0
21669338	21669280	Number Calculation	if(total <= 5)\n   fee=0.15;\n else \n    fee=0.15 + (0.09 * (total - 5));\n\n fee = connection_fee + fee;	0
20309302	20309269	check if string exists in a file	using (StreamReader sr = File.OpenText(path))\n{\n    string[] lines = File.ReadAllLines(path);\n    bool isMatch = false;\n    for (int x = 0; x < lines.Length - 1; x++)\n    {\n        if (domain == lines[x])\n        {\n            sr.Close();\n            MessageBox.Show("there is a match");\n            isMatch = true;\n        }\n    }\n    if (!isMatch)\n    {\n        sr.Close();\n        MessageBox.Show("there is no match");\n    }\n}	0
22393355	22393273	How to call a function from another form	public partial class Form2 : Form\n{\n   Form1 mainForm;\n\n   public Form2(Form1 mainForm)\n   {\n       InitializeComponent();\n\n       this.mainForm = mainForm;\n       mainForm.MySQLConnect(this, new EventArgs());\n   }\n}	0
17444606	17444473	How can I pass an url as value on a querystring and then get it back as plain text	string qs = HttpUtility.UrlDecode(Request.QueryString["currenturl"].ToString());	0
30594153	30593794	Visual studio designer wont display my user controls but runs the application fine	pack://application:,,,/MyAssemblyName;component/MyResourcesFolder/MyImage.png	0
26593926	26593693	How do I use an overridden property value in a higher class?	public class Program\n{\n    public static void Main()\n    {\n        A a = new A();\n        a.PrintThing();\n\n        A newA = new B();\n        newA.PrintThing();\n    }\n\n    public class A\n    {\n        protected virtual bool Enabled\n        {\n            get\n            {\n                return true;\n            }\n        }\n\n        public void PrintThing()\n        {\n            Console.WriteLine(this.Enabled.ToString());\n        }\n    }\n\n    public class B : A\n    {\n        protected override bool Enabled\n        {\n            get\n            {\n                return false;\n            }\n        }\n    }\n}	0
6163537	6163503	Create an instance of a class from an instance of the type of its generic parameter	public static implicit operator ValueContainer<T>(T value) {\n    return new ValueContainer { Value = value };\n}	0
13572869	13572604	method to total data in a list of a class	var tat = new ThisAndThat();\ntat.This = 1;\ntat.That = 2.0F;\ntat.TheOther = 3.0;\ntat.Whatever = "Whatever";\n\nvar type = typeof(ThisAndThat);\nvar properties = type.GetProperties();\n\ndouble total = 0.0;\n\nforeach (System.Reflection.PropertyInfo pi in properties)\n{\n    switch (pi.PropertyType.ToString())\n    {\n        case "System.Int32": //int\n            total += (int) pi.GetValue(tat, null);\n            break;\n        case "System.Double":\n            total += (double) pi.GetValue(tat, null);\n            break;\n        case "System.Single": //float\n            total += (float) pi.GetValue(tat, null);\n            break;\n    }\n}\n\nMessageBox.Show(total.ToString());	0
21061239	21061160	How to click a button on form load using C#	public Form1()\n{\n   InitializeComponent();\n   Load += Form1_Shown;\n}\n\nprivate void Form1_Shown(Object sender, EventArgs e) \n{\n   btnFacebookLogin.PerformClick(); \n}	0
8622646	8622631	How to implement listview using Usercontrol and a flowlayout panel?	private void flowLayoutPanel1_ControlAdded(object sender, ControlEventArgs e)\n        {\n            e.Control.Click += new EventHandler(Clicked);\n        }\n\n        private void Clicked(object sender, EventArgs e)\n        {\n            //click event code goes here\n        }	0
5858116	5858017	How can i programmatically add a Tab to a form during runtime?	Form1.tabControl1.Controls.Add(myNewTabItem);	0
7936849	7936810	Simpler way of finding sentences is a large string?	char[] delimiters = new char[] { '.', '?' };\nstring[] sentences= text.Split(delimiters, StringSplitOptions.RemoveEmptyEntries);	0
8153691	8151414	Sorting a DataTable using LINQ	bool datesOverlap = table.Rows\n    .Cast<DataRow>()\n    .SelectWithPrevious((current, previous) => new\n        {\n            PreviousEndDate = (DateTime)previous["EndDate"],\n            StartDate = (DateTime)current["StartDate"]\n        })\n    .Any(x => x.StartDate < x.PreviousEndDate);	0
16758214	16757799	I can't open a file I have written 10 secs ago	Texture2D thiss = contentManager.Load<Texture2D>("items");	0
5908814	5907416	Problem During showing of ContextMenuStrip in XtraGridview control	private void gridView1_PopupMenuShowing(object sender, DevExpress.XtraGrid.Views.Grid.PopupMenuShowingEventArgs e) {\n            if(e.HitInfo.HitTest ==  GridHitTest.RowCell)    {\n                e.Allow == false;\n                // your code to show menu\n            }\n        }	0
27364706	27364647	DateTime stamp in output .zip file	string filePath = @"C:\TEMP\test.zip";\nstring finalPath = Path.Combine(Path.GetDirectoryName(filePath),\n                            Path.GetFileNameWithoutExtension(filePath) \n                                  + DateTime.Now.ToString("yyyyMMddHHmmss") \n                                  + Path.GetExtension(filePath));	0
24322634	24322494	How To Sync Timers	private void button1_Click(object sender, EventArgs e)\n{\n    timer1.Interval= 20000;\n    timer1.Start();\n}\n\nprivate void timer1_Tick(object sender, EventArgs e)\n{\n    timer1.Stop();\n    timer2.Enabled = true;\n}\n\nprivate void timer2_Tick(object sender, EventArgs e)\n{\n    //\n    //you job here\n\n}	0
16040772	15592894	Keeping list of attached files of a page with TempData without any conflict with another instanse of the page	public virtual ActionResult Create(string attkey)\n{\n     if (string.IsNullOrEmpty(attkey))\n     {\n         attkey = generatNewNameForSession('key'); // for examle: kye_jhtyujbvkjadsgfvn\n         Response.Redirect("myControle/Create, attkey="+attkey), true);\n        }\n        ViewBag.AttachmentsKey = attkey;\n        if (Session[attkey] == null)\n            KeepData(attkey, "");\n        .\n        .\n        .	0
1852210	1852200	How to split string into a dictionary	string sx = "(colorIndex=3)(font.family=Helvicta)(font.bold=1)";\n\nvar items = sx.Split(new[] { '(', ')' }, StringSplitOptions.RemoveEmptyEntries)\n    .Select(s => s.Split(new[] { '=' }));\n\nDictionary<string, string> dict = new Dictionary<string, string>();\nforeach (var item in items)\n{\n    dict.Add(item[0], item[1]);\n}	0
19550394	19550179	Linq to XML, Parsing string for list of Elements, Printing strings with two descendants each Elem on the list	XNamespace ns = XNamespace.Get("http://www.w3.org/2005/Atom");\n    XNamespace nsCap = XNamespace.Get("urn:oasis:names:tc:emergency:cap:1.1");\n    var xlist = root.Descendants(ns + "entry").Select(elem => new\n            {\n                Title = elem.Descendants(ns + "title").FirstOrDefault(),\n                AreaDesc = elem.Descendants(nsCap + "areaDesc").FirstOrDefault()\n            });\n\n    foreach (var el in xlist)\n    {\n        Console.WriteLine(string.Format("title: {0}, AreaDesc: {1}",\n            el.Title != null ? el.Title.Value : string.Empty,\n            el.AreaDesc != null ? el.AreaDesc.Value : string.Empty));\n    }	0
3878784	3878768	How to run a form with it's own message pump?	Application.Run();	0
7771712	7771646	How can I get the name of a HttpResponseHeader?	response.Headers.GetValues(response.Headers.GetKey(i))	0
819808	819773	Run single instance of an application using Mutex	bool createdNew;\n\nMutex m = new Mutex(true, "myApp", out createdNew);\n\nif (!createdNew)\n{\n    // myApp is already running...\n    MessageBox.Show("myApp is already running!", "Multiple Instances");\n    return;\n}	0
9069171	8861974	Concurrency - editing 1 resource a time	ConcurrentDictionary<int,object> lockObjects = new ConcurrentDictionary<int,object)\npublic void UpdateMySpecialEntity(Entity foo)\n{\n    object idLock =  lockObject.GetOrAdd(foo.id,new object());\n    lock (idLock)\n    {\n    // do lock sensitive stuff in here.\n    }\n}	0
10943848	10943722	Problems with dispatcher in C# console application	Dispatcher.Run()	0
12529202	12528675	Post Method in Webclient	postData.AppendFormat("{0}={1}", "username", HttpUtility.UrlEncode(textBox1.Text));\npostData.AppendFormat("&{0}={1}", "password", HttpUtility.UrlEncode(textBox2.Text));	0
5981266	5981164	Can't write string from table to string attribute in C#	public Project CreateProject(object projectName, object hoursPerDay, object hoursPerWeek, object daysPerWeek)\n{\n    return new Project(projectName.ToString(), Convert.ToInt32(hoursPerDay), Convert.ToInt32(hoursPerWeek), Convert.ToInt32(daysPerWeek);\n}	0
9664199	9664151	Controller wrapping in panel	for (int i = 0; i < DataRepository.Categories.Categories.Count; i++)\n{\n    CategoriesDataSet.CategoriesRow category = DataRepository.Categories.Categories[i];\n\n        if (!category.CategoryName.Equals("ROOT"))\n        {\n            SimpleButton button = new SimpleButton();\n            button.Text = category.CategoryName;\n            button.Tag = category.CategoryId;\n            button.Size = new Size(82, 70);\n\n            button.Left = i%4*82;\n            button.Top = i*70;\n\n            button.Click += CategoryButtonClick;\n            categoriesPanel.Controls.Add(button);\n        }\n    }	0
5509000	5508956	converting ARGB to RGB in WPF	string color_str = string.Format("#{0:X2}{1:X2}{2:X2}", Color.R, Color.G, Color.B);	0
25418144	25418125	how to assign values to list type class variable?	attendees = new List<EmailAddress>()\n{\n    new EmailAddress(...),\n    new EmailAddress(...),\n    new EmailAddress(...),\n    ...\n}	0
227745	227743	StringBuilder: how to get the final String?	.ToString()	0
7921968	7755463	MessagingSystem causes a NullReferenceException	snakeBlocks = null;\n\n//Do some stuff.\n\nsnakeBlocks = someNewInstanceOfGameObject;	0
6954739	6954688	hiding my window from the start?	protected override void OnLoad(EventArgs e)\n{\n    Visible = false;\n    ShowInTaskbar = false;\n    base.OnLoad(e);\n}	0
16649577	16648444	How to access button in an item template of an asp.net "gridview" using Javascript?	function myFunc(x){\nvar id=x.id;\nvar newID = id.substring(0, 18);\nnewID+="TextBox1";\ndocument.getElementById(newID).value="ghjhghjg";\nreturn false;\n}	0
12956780	12954212	SQLite Database Locked - Live synchronisation of two databases with row-by-row UPDATEs/INSERTs	Default Timeout	0
3301016	3300906	RegEx'ing Hotmail email addresses with C#	function bool IsHotmailAddress(string email) {\n    var r = new Regex(@"\@(live|hotmail)\.[a-z]{2,3}(\.[a-z]{2,3})?$", RegexOptions.IgnoreCase);\n    return r.IsMatch(email);\n}	0
15971438	15971251	Generic error in GDI+ occurs in Screen Capture	using (bmpScreenshot = new Bitmap(Screen.PrimaryScreen.Bounds.Width, Screen.PrimaryScreen.Bounds.Height, PixelFormat.Format32bppArgb))\nusing (gfxScreenshot = Graphics.FromImage(bmpScreenshot))\n{\n    // Take the screenshot from the upper left corner to the right bottom corner\n    gfxScreenshot.CopyFromScreen(Screen.PrimaryScreen.Bounds.X, Screen.PrimaryScreen.Bounds.Y, 0, 0, Screen.PrimaryScreen.Bounds.Size, CopyPixelOperation.SourceCopy);\n\n    Bitmap bmpScreenshot2 = new Bitmap(bmpScreenshot); // FIX: Change "S" to "s"...\n    // Save the screenshot to the specified path that the user has chosen\n    bmpScreenshot2.Save(savePath + "img" + times.ToString()+ ".png", ImageFormat.Png);\n}	0
8364840	8364283	pass string from one action to other in same controller	return RedirectToAction("Details", "Invoice", new { id = search.Trim() });	0
27137602	27135458	How left join in select union in linq c#?	var sample= (from e in table1\n             join d in table2 on e.column equals d.column into ej\n             from d in ej.DefaultIfEmpty()\n             select new {e.column , e.column , d.column });	0
9064560	9064485	compare datarows of different tables	var result= dataTable1.AsEnumerable().Intersect(dataTable2.AsEnumerable(),\n                                                    DataRowComparer.Default);	0
7343401	7343257	Excel Add-in - Delphi equivilent to VB	try\n  ExcelApplication.ActiveCell.QueryTable.Refresh(False);\nexcept\nend;	0
5756962	4977808	Best way to use javascript api for a desktop app	using Microsoft.JScript;\nobject result = Microsoft.JScript.Eval.JScriptEvaluate("my javascript code", Microsoft.JScript.Vsa.VsaEngine.CreateEngine());	0
15560069	15560011	How to read a CSV file one line at a time and parse out keywords	using (StreamReader sr = new StreamReader("c:/temp/ESMDLOG.csv"))\n        {\n            string currentLine;\n            // currentLine will be null when the StreamReader reaches the end of file\n            while((currentLine = sr.ReadLine()) != null)\n            {\n                // Search, case insensitive, if the currentLine contains the searched keyword\n                if(currentLine.IndexOf("I/RPTGEN", StringComparison.CurrentCultureIgnoreCase) >= 0)\n                {\n                     Console.WriteLine(currentLine);\n                }\n\n            }\n        }	0
12326583	12326509	How do I call a method on a WebBrowser inside an event handler?	((WebBrowser)sender).Navigate(...);	0
25009572	25009437	Running multiple async tasks and waiting for them all to complete	List<Task> TaskList = new List<Task>();\nforeach(...)\n{\n    var LastTask = new Task(SomeFunction);\n    LastTask.Start();\n    TaskList.Add(LastTask);\n}\n\nTask.WaitAll(TaskList.ToArray());	0
20139724	20139519	Multiple roles in Controller action	[Authorize(Roles = "admin,userRole")]	0
13411648	13411613	How to perform addition in a Linq query	var total = query.Sum(x => x.hours);	0
30542003	30540994	Find and Modify with MongoDB C#	var collection = database.GetCollection<BsonDocument>("product");\nvar filter = new BsonDocument();\nvar update = Builders<BsonDocument>.Update.Inc("UseCount", 1);\nvar sort = new FindOneAndUpdateOptions<BsonDocument>\n{\n            Sort = Builders<BsonDocument>.Sort.Ascending("UseCount")\n};\nawait collection.FindOneAndUpdateAsync(filter, update, sort);	0
23905761	23903116	Get the Date of Months Week Number	int WeekStartDay(int year, int month, int weekNo)\n{\n    DateTime monthStart = new DateTime(year, month, 1);\n\n    int monthStart_DayOfWeek = ((int)monthStart.DayOfWeek + 6) % 7;\n\n    int weekStart_DayOfMonth = 1;\n    if (1 < weekNo) {\n        weekStart_DayOfMonth += 7 - monthStart_DayOfWeek;\n    }\n    if (2 < weekNo) {\n        weekStart_DayOfMonth += 7 * (weekNo - 2);\n    }\n    return weekStart_DayOfMonth;\n}	0
9538505	9538229	Registering a type with ctor that expects runtime parameters in unityContainer	AuthService(bool initFromContainer)	0
10578838	10578310	Convert arraylist object to byte[]	List<object> list = new List<object>();\n        list.Add((byte)1);\n        list.Add((byte)0);\n        list.Add("wtf");\n        list.Add((byte)1);\n        byte[] obj = list.OfType<byte>().ToArray();\n        if(obj.Length!=list.Count)\n        {\n            //Exception, not all objects in list is 'byte'\n        }	0
2123583	2123476	Localized Attribute parameters in C#	[ValidateNonEmpty(\n        FriendlyNameKey = "CorrectlyLocalized.Description",\n        ErrorMessageKey = "CorrectlyLocalized.DescriptionValidateNonEmpty",\n        ResourceType = typeof (Messages)\n        )]\n    public string Description { get; set; }	0
27147949	27146416	C# edit property of panel using run-time generated button	private void myButton1_Click(object sender, EventArgs e)\n    {\n        Button but = (sender as Button);\n        but.BackColor = Color.Gold;\n        // this changes the color of the panel\n        but.Parent.BackColor = Color.Gold;\n        // this changes the color of the form containing the panel\n        if (but.Parent.Parent != null)\n        {\n            but.Parent.Parent.BackColor = Color.Gold;\n        }\n\n    }	0
33345194	24777252	Can I Invoke a nancy Module by myself	public class GetModelExtententionsTests\n{\n    private readonly Browser _browser;\n    public GetModelExtententionsTests()\n    {\n        this._browser = new Browser(with => {\n           with.Module<AModuleToTestExtensionMethodsWith>();\n           with.ViewFactory<TestingViewFactory>();\n        });\n    }\n\n    [Fact]\n    public void Can_get_the_model_and_read_the_values()\n    {\n       var response = this._browser.Get("/testingViewFactory");\n       var model = response.GetModel<ViewFactoryTestModel>();\n       Assert.Equal("A value", model.AString);\n    }\n}	0
4489114	4489001	Watin : Get Row Count from table	table.TableRows.Count;	0
12577348	12576979	how to send email with alternate views either plain text or HTml templates.?	AlternateView plainView = AlternateView.CreateAlternateViewFromString(plainEmail, null, "text/html");	0
27656137	25562092	How to set limited number of files upload in asp.net multiple file upload?	function ValidateFile2(){\n    var fileCount = document.getElementById('FileUpload2').files.length;\n    if(fileCount > 10) // Selected images with in 10 count\n    {\n       alert("Please select only 10 images..!!!");\n       return false;\n    }\n    else if(fileCount <= 0) // Selected atleast 1 image check\n    {\n       alert("Please select atleat 1 image..!!!");\n       return false;\n    }\n\n    return true;  // Good to go\n}	0
22976905	22976840	How to pass data from callback function to MainPage(another class) in Windows Phone 8	var frame = Window.Current as Frame;\n\nif (frame == null)\n{\n    return; //?\n}\n\nvar mainPage = frame.Content as MainPage;\n\nif (mainPage == null)\n{\n    return; //?\n}\n\nmainPage.updateImage(byteArray);	0
19848265	19848047	Get Remote Host IP in Web API Self-Hosted Using Owin	OwinContext owinContext = (OwinContext)webapiHttpRequestMessage.Properties["MS_OwinContext"];\nstring ipaddress = owinContext.Request.RemoteIpAddress;	0
459136	459126	C#: How do you control the current item index that displays in a ComboBox?	this.comboBox1.SelectedIndex = 0;	0
27917889	27917643	Delete last line of file, when using the data to draw a chart c#	while (!reader.EndOfStream)\n        {\n            var line = reader.ReadLine();\n            if (line.StartsWith("Count")) \n              break;\n            /....\n        }	0
12912351	12912277	Change cell values in excel files and copy the changes to a new column using c#	Excel.Application xlApp;\n    Excel.Workbook xlWorkBook;\n    Excel.Worksheet xlWorkSheet;\n    object misValue = System.Reflection.Missing.Value;\n    xlApp = new Excel.Application();\n    xlWorkBook = xlApp.Workbooks.Open(ExcelFile, misValue, misValue, misValue, misValue, misValue, misValue, misValue, misValue, misValue, misValue, misValue, misValue, misValue, misValue);\n    xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);\n\n\n\nMicrosoft.Office.Interop.Excel.Range range = xlWorkSheet.Cells.SpecialCells(\n                Microsoft.Office.Interop.Excel.XlCellType.xlCellTypeLastCell, Type.Missing);\n\n        string value = string.Empty;\n        for (int Loop = 1; Loop <= range.Row; Loop++)\n        {\n            value = Convert.ToString(xlWorkSheet.Range["A" + Loop, "A" + Loop].get_Value(misValue));\n            xlWorkSheet.Range["B" + Loop, "B" + Loop].set_Value(misValue, value.Remove(8, 3));\n        }	0
19417452	19225594	Detecting bold, underline text and headings in word document with openxml sdk in c#	foreach (Run run in body.Descendants<Run>())\n{\n   RunProperties props = run.Descendants<RunProperties>();\n   if(props.Descendants<Bold>().First() != null) \n   {\n      //then do something\n   }\n\n   text += run.Text;\n   text += "<br />";                                              \n}	0
16646839	16643476	how to insert formula in word using vsto?	_wordApplication.ActiveWindow.ActivePane.View.ShowFieldCodes = true;\ntry\n{\n    _wordApplication.Selection.InsertFormula("=1");                      \n    _wordApplication.Selection.MoveLeft(WdUnits.wdCharacter, 1);\n    _wordApplication.Selection.TypeText("+");\n    var field =_wordApplication.ActiveDocument.Fields.Add(_wordApplication.Selection.Range,   Microsoft.Office.Interop.Word.WdFieldType.wdFieldEmpty, "PAGE", true);\n    field.Update();\n\n}           \nfinally\n{\n  _wordApplication.ActiveWindow.ActivePane.View.ShowFieldCodes = false;\n}	0
15866810	15866780	How to find duplicate items in list<>?	var duplicates = list.GroupBy(a => a).SelectMany(ab => ab.Skip(1).Take(1)).ToList();	0
18861722	18861618	Get a control inside another control	protected void Register_Click(object sender, EventArgs e)\n{\n    LoginView1.FindControl("LoginPanel").Visible = false;\n    LoginView1.FindControl("RegPanel").Visible = true;\n}	0
7690501	7690482	Parameter Action<T1, T2, T3> in which T3 can be optional	public delegate void MyDelegate(IEnumerable<string> param1, string param2, int param3 = 1);	0
7751298	7751197	how does one list all the finite sequences of a given alphabet in c#	this.listBox1.Items.Add(YourFunction(this.textBox1.Text));	0
23578656	23578489	how to create .net application with database for my client	SqlCeConnection conn = \n     new SqlCeConnection(@"Data Source=|DataDirectory|\dbJournal.sdf");\nconn.Open();	0
5342460	5342375	c# regex email validation	public bool IsValid(string emailaddress)\n{\n    try\n    {\n        MailAddress m = new MailAddress(emailaddress);\n\n        return true;\n    }\n    catch (FormatException)\n    {\n        return false;\n    }\n}	0
10517485	10517357	asp sitemap for a folder	web.config	0
8177902	8177864	How to exclude NULL blocks from XML using LINQ-to-XML?	var tutorials = from tutorial in xmlDoc.Root.Elements("Tutorial")\n                select new\n                {\n                    Author = (string)tutorial.Element("Author"),\n                    Title = (string)tutorial.Element("Title"),\n                    Date = (DateTime)tutorial.Element("Date"),\n                };	0
6673496	6645432	Input String was Not in a Correct Format	private void buttonaddcompany_Click(object sender, EventArgs e)\n{\n    string MyConString = "SERVER=localhost;" + "DATABASE=payroll;" + "UID=root;" + "PASSWORD=admin;";\n    MySqlConnection connection = new MySqlConnection(MyConString);\n    MySqlCommand command = connection.CreateCommand();\n    command.Connection = connection;\n    using (MySqlConnection conn = new MySqlConnection(MyConString))\n    {\n        connection.Open();\n        using (MySqlCommand com = connection.CreateCommand())\n        {\n            command.CommandText = "insert into company(company_name, /* other fields here , */ company_country_zipcode) values(?company_name, 'company_other_names', /* other hardcoded fields here , */ 'company_country_zipcode')";\n            command.Parameters.Add(new MySqlParameter("?company_name", SqlDbType.VarChar));\n            command.Parameters["?company_name"].Value = addcompname.Text;\n            command.ExecuteNonQuery();\n            MessageBox.Show("Data Saved");\n        }\n    }\n}	0
863338	863207	Wpf - Receiving property value change notification for properties of a framework element	DependencyPropertyDescriptor desc = DependencyPropertyDescriptor.FromProperty(FrameworkElement.TagProperty, typeof(FrameworkElement));\ndesc.AddValueChanged(someObject, someEventHandler);	0
14772048	14771837	Counting data in ACCESS database?	using (OleDbConnection con = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0; Data Source=C:\\Test.mdb"))\n        using (OleDbCommand Command = new OleDbCommand(" SELECT count (CustomerId) from Customer as total", con))\n        {\n            con.Open();\n            OleDbDataReader DB_Reader = Command.ExecuteReader();\n            if (DB_Reader.HasRows)\n            {\n                DB_Reader.Read();\n                int id = DB_Reader.GetInt32(0);\n            }\n        }	0
1207438	1207404	How to pass a null variable to a SQL Stored Procedure from C#.net code	SqlParameters[1] = new SqlParameter("Date1", SqlDbType.SqlDateTime);\nSqlParameters[1].Value = DBNull.Value;\nSqlParameters[1].Direction = ParameterDirection.Input;	0
1310852	1310812	How can I find all the members of a Properties.Resources in C#	foreach (PropertyInfo property in typeof(Properties.Resources).GetProperties\n    (BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic))\n{\n    Console.WriteLine("{0}: {1}", property.Name, property.GetValue(null, null));\n}	0
4071709	4071693	Wrap Serialized Data to a higher level XML tag	XmlWriter writer = // Your writer\nXmlSerializer ser = new XmlSerializer(typeof(DateTime));\nwriter.WriteStartElement("message");\nser.Serialize(writer,DateTime.Now);\nwriter.WriteEndElement();	0
8318792	8314815	MonoTouch.Dialog: How to set limit of number of characters for EntryElement	class MyEntryElement : EntryElement {\n\n    public MyEntryElement (string c, string p, string v) : base (c, p, v)\n    {\n        MaxLength = -1;\n    }\n\n    public int MaxLength { get; set; }\n\n    static NSString cellKey = new NSString ("MyEntryElement");      \n    protected override NSString CellKey { \n        get { return cellKey; }\n    }\n\n    protected override UITextField CreateTextField (RectangleF frame)\n    {\n        UITextField tf = base.CreateTextField (frame);\n        tf.ShouldChangeCharacters += delegate (UITextField textField, NSRange range, string replacementString) {\n            if (MaxLength == -1)\n                return true;\n\n            return textField.Text.Length + replacementString.Length - range.Length <= MaxLength;\n        };\n        return tf;\n    }\n}	0
3021366	3021299	XML serialization query	using System.Collections.Generic;\nusing System.IO;\nusing System.Xml.Serialization;\n\n[XmlRoot("instance")]\npublic class AnimalInstance {\n    [XmlElement("dog")]\n    public Dog Dog { get; set; }\n}\n\npublic class Dog {\n    [XmlArray("items")]\n    [XmlArrayItem("item")]\n    public List<Item> Items = new List<Item>();\n}\n\npublic class Item {\n    [XmlElement("label")]\n    public string Label { get; set; }\n}\n\nclass Program {\n    static void Main(params string[] args) {\n        string xml = @"<instance>\n<dog>\n    <items>\n        <item>\n            <label>Spaniel</label>\n        </item>\n    </items>\n</dog>\n</instance>";\n\n        XmlSerializer xmlSerializer = new XmlSerializer(typeof(AnimalInstance));\n        AnimalInstance instance = (AnimalInstance)xmlSerializer.Deserialize(new StringReader(xml));\n    }\n}	0
15152158	15138165	How to set TextBox cursor position without SelectionStart	// save current cursor position and selection \n        int start = textBox.SelectionStart;\n        int length = textBox.SelectionLength;\n\n        Point point = new Point();\n        User32.GetCaretPos(out point);\n\n        // update text\n        textBox.Text = value;\n\n        // restore cursor position and selection\n        textBox.Select(start, length);\n        User32.SetCaretPos(point.X, point.Y);	0
26463794	26463527	MS Chart Y Axis not staring from 0 Hours [RangeBar]	DateTime minDate = new DateTime(0, 0, 0, 0, 0, 0);\nDateTime maxDate = minDate.AddHours(24);\nchChart.ChartAreas[0].AxisY.Minimum = minDate.ToOADate();\nchChart.ChartAreas[0].AxisY.Maximum = maxDate.ToOADate();	0
3396826	3396769	Matching the last sub-pattern in a pattern	resultString = Regex.Match(subjectString, @"\w*.\w*$", RegexOptions.Multiline).Groups[1].Value;	0
28298839	28298612	Empty Xml Document response from Api	string url = "http://www.omdbapi.com/?i=tt2231253&plot=short&r=xml";\n WebClient wc = new WebClient();\n XDocument doc = XDocument.Parse(wc.DownloadString(url));\n Console.WriteLine(doc);	0
10040147	10040097	Create table and insert rows based on multiple select statements in SQL Server 2008	DECLARE @TEMPRECORDFORCOUNT TABLE(totalemployeecount int,activeemployeecount int,inactiveemployeecount int,deptwiseemployeecount int,activeemployeecount int)\n\ninsert into @TEMPRECORDFORCOUNT\n(\ntotalemployeecount \n,activeemployeecount \n,inactiveemployeecount \n,deptwiseemployeecount \n,activeemployeecount \n)\nvalues\n(\n@totalemployeecount ,\n@activeemployeecount ,\n@inactiveemployeecount ,\n@deptwiseemployeecount ,\n@activeemployeecount ,\n)\n\nSELECT * FROM @TEMPRECORDFORCOUNT\n;	0
10879400	10878727	Invalid length for a Base-64 char array while decryption 	public static string decodeSTROnUrl(string thisDecode)\n    {\n        return Decrypt(thisDecode);\n    }	0
21633230	21632670	How would I translate following T-SQL statement To Linq	var results = from p in iwof.DateSnippet\n          group p by p.DepartmentId into g\n          select new { DepartmentId = g.Key, MaxFromDate = g.Max(fromdate) };	0
17890316	17890225	Regex to match partial string verification	static readonly Regex rxProductKey = new Regex( @"^..3..-...G.-..K..-M.6..-.R...$" , RegexOptions.IgnoreCase ) ;\n\npublic bool IsValidProductKey( string key )\n{\n  bool isValid = key != null && rxProductKey.IsMatch( key ) ;\n  return isValid ;\n}	0
2447418	2447390	automapper - how to map object list	class Thing {\n    public int ThingId { get; set; }\n    public string ThingName { get; set; }\n    public string UnnecessaryProp {get;set;}\n}\n\nclass ThingViewModel {\n    public int ThingId { get; set; }\n    public string ThingName { get; set; }\n}\n\nclass MyView {\n    public IEnumerable<ThingViewModel> Things {get;set;}\n}	0
19030017	19029947	XAML - Bind combobox in DataTemplate to a collection?	ItemsSource="{Binding TemplatesHeader, RelativeSource={RelativeSource AncestorType={x:Type Window}}}"\n\npublic ObservableCollection<TemplateHeaderFooter> TemplatesHeader\n{\n  get{return templatesHeader;}\n}	0
29293333	29293282	Can you call a second constructor without an overload method	public JsonQuery(string worksheet)\n {\n    SmartsheetQuery smartsheetQuery = new SmartsheetQuery();\n    jObject = JObject.Parse(smartsheetQuery.getJsonAsString(worksheet));    \n }	0
28803674	28796143	scaffolding views from controllers (model already exists)	1. right click on the action name\n2. click on Add view\n3. check mark on "Create a strongly typed view"\n4. select your "Model class" from drop down\n5. select list/as you need from "scaffold template" dropdown\n6. click on add button	0
11455945	11455928	Moq, how to match 2 arguments?	mock\n  .Setup(foo => foo.DoSomething(It.IsAny<string>(), It.IsAny<AccountType>()))\n  .Returns(true);	0
29859342	29024050	C#: Upload Photo To Twitter From Unity	Dictionary<string, string> parameters = new Dictionary<string, string>();\nstring encoded64ImageData = ImageToBase64( imageData );\nparameters.Add("media_data", encoded64ImageData );\n\n// Add data to the form to post.\nWWWForm form = new WWWForm();\nform.AddField( "media_data", encoded64ImageData );\n\n// HTTP header\nDictionary<string, string> headers = new Dictionary<string, string>();\nstring url = UploadMediaURL;\nstring auth = GetHeaderWithAccessToken("POST", url, consumerKey, consumerSecret, accessToken, parameters);\nheaders.Add( "Authorization", auth );\nheaders.Add( "Content-Transfer-Encoding", "base64" );\n\nWWW web = new WWW(url, form.data, headers);\nyield return web;	0
18865547	18865080	Add Datagridview Rows to Datatable when Checkbox is Checked in C#	DataTable tbl = ((DataTable)dataGridView1.DataSource).Clone();//Clone structure first\nvar rows = dataGridView1.Rows.OfType<DataGridViewRow>()\n                        .Where(r=>Convert.ToBoolean(r.Cells["yourCheckBoxColumn"].Value))\n                        .Select(r=>((DataRowView)r.DataBoundItem).Row);\nforeach(var row in rows)\n   tbl.ImportRow(row);	0
492963	492700	How to split a string while preserving line endings?	string[] lines =  Regex.Split(tbIn.Text, @"(?<=\r\n)(?!$)");	0
1138278	1138132	Getting MainWindowHandle of a process in C#	private void Form1_Load(object sender, EventArgs e)\n{\n\n    Process p = new Process();\n    p.StartInfo.FileName = "iexplore.exe";\n    p.StartInfo.Arguments = "about:blank";\n    p.Start();\n\n    Process p2 = new Process();\n    p2.StartInfo.FileName = "iexplore.exe";\n    p2.StartInfo.Arguments = "about:blank";\n    p2.Start();\n\n    try\n    {\n        if (FindWindow("iexplore.exe", 2) == p2.MainWindowHandle)\n        {\n            MessageBox.Show("OK");\n        }\n    }\n    catch (Exception ex)\n    {\n        MessageBox.Show("Failed: Process not OK!");\n    }    \n}\n\n\nprivate IntPtr FindWindow(string title, int index)\n{\n    List<Process> l = new List<Process>();\n\n    Process[] tempProcesses;\n    tempProcesses = Process.GetProcesses();\n    foreach (Process proc in tempProcesses)\n    {\n    if (proc.MainWindowTitle == title)\n    {\n    l.Add(proc);\n    }\n    }\n\n    if (l.Count > index) return l[index].MainWindowHandle;\n    return (IntPtr)0;\n}	0
2452774	2452663	Autocomplete a textbox in c#	AutoCompleteStringCollection autoCompleteList = \n                                            new AutoCompleteStringCollection();\n/* copy your datacolumn in to autoCompleteList iteratively here */\ntxtBox.AutoCompleteMode = AutoCompleteMode.SuggestAppend; /* or just Suggest */\ntxtBox.AutoCompleteCustomSource = autoCompleteList;	0
14243140	14235513	Trouble with LINQ: Reading objects from database, getting exceptions	private EntityRef<Department> _department;\n[Association(Name = "FK_Person_PersonDepartment", IsForeignKey = true,\n   Storage = "_department", ThisKey = "personDepartmentID", OtherKey = "departmentID")]\npublic Department Department\n{\n  get { return _department.Entity; }\n  set { _department.Entity = value; }\n}	0
9886214	9886056	Check all CheckBoxes in GridView	function CheckAll()\n{   \n    var updateButtons = jQuery('#<%=gvGridViewId.ClientID%> input[type=checkbox]');\n\n    updateButtons.each( function() {\n            // use this line to change the status if check to uncheck and vice versa\n            //  or make it as you like with similar function\n        jQuery(this).attr("checked", !this.checked);\n    });     \n}	0
1833060	1833054	How can I format a nullable DateTime with ToString()?	Console.WriteLine(dt2 != null ? dt2.Value.ToString("yyyy-MM-dd hh:mm:ss") : "n/a");	0
10199100	10199029	Protecting a sensitive value (password) when using XML serialization?	public class LogonInfo\n{\n    [XmlIgnore]\n    public string Password { get; set; }\n\n    public string EncPassword {\n    {\n        get\n        {\n            return Encrypt(Password);\n        }\n        set\n        {\n            Password = Decrypt(value);\n        }\n    }\n\n    // TODO: add Encrypt and Decrypt methods\n}	0
19304269	19304046	Linq2XML Syntax for adding to an array	var allQuotes = responseElement.Elements("quotes").Elements("quote").ToArray();\n\nquotes = new Quotes[]\n  {\n     new Quote\n     {\n         ask = (string)allQuotes[0].Element("ask")\n     },\n     new Quote\n     {\n         ask = (string)allQuotes[1].Element("ask")\n     },\n     new Quote\n     {\n         ask = (string)allQuotes[2].Element("ask")\n     }, ...\n    // happy guessing what the last index will be..\n  }	0
10150335	10150290	The same rows in LinkedList<LinkedList>	var ranodGenerator = new Random();	0
32846585	32846312	Empty file when sending an email with Attachment	// ...\nimagem.Save(imagemStream, ImageFormat.Jpeg);\nimagemStream.Position = 0;\nreturn imagemStream;	0
31253050	31252551	Handling extra spaces when deserializing XML values to enums	public class Foo\n{\n    [XmlIgnore]\n    public MyEnum myEnum { get; set; }\n\n    [XmlElement("Bar")]\n    [EditorBrowsable(EditorBrowsableState.Never)]\n    public string _myEnum\n    {\n        get { return myEnum.ToString(); }\n        set { myEnum = (MyEnum)Enum.Parse(typeof(MyEnum), value.Trim()); }\n    }\n}	0
3884837	3884811	Implementing IComparable<> in a sealed struct for comparison in a generic function	int result1 = Comparer<int>.Default.Compare(1, 2);\n                         // the Default comparer defaults\n                         // to IComparable<T>.CompareTo\n\nint result2 = new SomeTypeComparer().Compare(FuncUnderTest(), SomeType.Empty);	0
20915162	20915126	Sending mails from an SMTP server	System.Net.Mail.MailMessage message = new System.Net.Mail.MailMessage();\nmessage.To.Add("luckyperson@online.microsoft.com");\nmessage.Subject = "This is the Subject line";\nmessage.From = new System.Net.Mail.MailAddress("yourmailuser@yourhost.com",25);\nmessage.Body = "This is the message body";\nSystem.Net.Mail.SmtpClient smtp = new System.Net.Mail.SmtpClient("yoursmtphost");\n// if you need user/pass login\nclient.Credentials = new NetworkCredential("username","password");\nsmtp.Send(message);	0
13821863	13821252	How to Split string into words in c#	// This is the input string.\n        string input = "price+10*discount-30";\n\n        var matches = Regex.Matches(input, @"([a-z]+)", RegexOptions.IgnoreCase | RegexOptions.Multiline);\n        foreach (var match in matches)\n        {\n            Console.WriteLine(match);\n        }\n        Console.ReadLine();	0
23145853	23145368	How to call sibling objects from a foreign thread	public class ControlClassD\n{\n    public class WrapperEventArgs: EventArgs { public object Arg { get; set; } }\n    public event EventHandler<WrapperEventArgs> WrapperEvent = delegate { };\n\n    private 3rdPartyEventSource _3rdPartyEventSource = new 3rdPartyEventSource();\n\n    public ControlClassD()\n    {\n        var dispatcher = Dispatcher.CurrentDispatcher;\n\n        _3rdPartyEventSource.NewEvent += obj =>\n              dispatcher.BeginInvoke(new Action(() => \n                  this.WrapperEvent(this, new WrapperEventArgs { Arg = obj })));\n\n        this.WrapperEvent += ControlClassD_WrapperEventHandler;\n\n        _3rdPartyEventSource.StartMakingEventsWhenSomethingHappens();\n    }\n\n    private void ControlClassD_WrapperEventHandler(\n        object sender, WrapperEventArgs args)\n    {\n        InstanceOfControlClassA.doSomethingWith(args.Arg);\n        InstanceOfControlClassB.doSomethingWith(args.Arg);\n        InstanceOfControlClassC.doSomethingWith(args.Arg);\n    }\n}	0
8457205	8457197	How to write a text file from a .NET DataGridView control cell values?	for (int row = 0; row < count; row++)\n    {\n        int colCount = dgv.Rows[row].Cells.Count; \n        for ( int col = 0; col < colCount; col++)  \n        {\n            objWriter.WriteLine(dgv.Rows[row].Cells[col].Value.ToString());\n\n        }\n        // record seperator could be written here.\n    }	0
24603154	24603102	Making text to bold in rich text box in windows forms	richTextBox1.SelectionFont = new Font(richTextBox1.Font.FontFamily, Font.Size, FontStyle.Bold);	0
23747121	23746829	How to access or modify dynamically created button	var button = uniformgridMinesweeper.Children.OfType<Button>()\n    .FirstOrDefault(button => button.Name == "_5_5");	0
22192277	22128054	Loading Assemblies with referenced dll's	AppDomain.CurrentDomain.AssemblyResolve	0
4021337	4021285	How can I replace each new line with a auto-incremented number?	string[] lines = ...\n\nstring newText = string.Concat(lines.Select(\n                     (line, index) => string.Format("{0}. {1}", index, line)));	0
23334266	23334195	Replace number in double quotes with string empty	String s="<span id=\"1\">1 </span>ABC<br><span id=\"2\">2...";\nRegex re=new Regex("id=\"[0-9]+\"");\ns=re.Replace(s, "");	0
12705940	12705874	UTC string to DateTime exception	2012-10-03T10:41:22.9884010+01:00	0
13567727	13566868	how to execute sql select statement in c#	da2.SelectCommand.Parameters.Add("@DoctorCode", SqlDbType.Int).Value = Convert.ToInt32(comboBox2.SelectedValue);\n        da2.SelectCommand.Parameters.Add("@month", SqlDbType.Int).Value = comboBox1.SelectedValue;\n        da2.SelectCommand.Parameters.Add("@year", SqlDbType.Int).Value = textBox2.Text;	0
12165443	12150358	Mapping DateTime from/to SubProperty DateTime	public class AModel { \n    DateTime DateFrom { get;set; } \n    DateTime DateThru { get;set; } \n}   \npublic class BModel { \n    ModelDateCollection DateFrom { get;set; } \n    ModelDateCollection DateThru { get;set; } \n}   \npublic class ModelDateCollection { \n    DateTime Date { get;set; } \n    String Display { get; } // Example Readonly for Date Display \n    DateTime FirstOfMonth { get; } // Another Example to extend Complex Class \n}	0
32411955	32411832	how to remove specific sub collections in XML using C#	foreach (XmlNode subCollection in xml.SelectNodes(\n "//Collection[@name='CORALL']/SubCollection[Column[@name='EX_ID' and starts-with(., 'h')] and Column[@name='AMT'   and . = '0.00']]"))\n{\n    // SubCollection.Collection.RemoveChild(SubCollection)\n    subCollection.ParentNode.RemoveChild(subCollection);\n}	0
32434854	32434677	Traverse files in sftp and store to azure blob	Step 1. Get list of SFTP locations\nStep 2. Init Azure Blob Storage Connection\nStep 3. Init SFTP\nStep 4. Iterate Files in SFTP\nStep 5. Store the file into Blob Storage\nStep 6. Close SFTP connection\nStep 7. Close Azure Blob Storage	0
28341914	28215267	How to "transaction" a IO operation and a database execution?	using (connectionDb)\n{\n    connectionDb.Open();\n    using (var ts = new System.Transactions.TransactionScope())\n    {\n        try\n        {\n            File.Copy(sourceFileName, destFileName, overwrite);\n            connectionDb.ExecuteNonQuery();\n            ts.Complete();\n        }\n        catch (Exception)\n        {\n            throw;\n        }\n        finally\n        { }\n    }\n}	0
4487092	4486941	How to check wether a domain name exists in asp.net with C#?	var server = Dns.Resolve("www.stackoverflow.com");	0
5317347	5311900	Filling an arraylist from a datareader	SqlConnection Conn = new SqlConnection(MyConnectionString);\n    Conn.Open();\n\n    SqlDataAdapter Adapter = new SqlDataAdapter("Select * from Employees", Conn);\n\n    DataTable Employees = new DataTable();\n\n    Adapter.Fill(Employees);\n\n    GridView1.DataSource = Employees;\n    GridView1.DataBind();	0
10908983	10906422	how can a password-protected PDF file be opened programmatically?	public static void unprotectPdf(string input, string output)\n{\n    bool passwordProtected = PdfDocument.IsPasswordProtected(input);\n    if (passwordProtected)\n    {\n        string password = null; // retrieve the password somehow\n\n? ?     using (PdfDocument doc = new PdfDocument(input, password))\n? ?     {\n? ? ? ?     // clear both passwords in order\n            // to produce unprotected document\n? ? ? ?     doc.OwnerPassword = "";\n? ? ? ?     doc.UserPassword = "";\n\n? ? ? ?     doc.Save(output);\n        }\n    }\n    else\n    {\n        // no decryption is required\n        File.Copy(input, output, true);\n    }\n}	0
4055765	4055716	Convert a Byte Array to String in Silverlight?	string text = UTF8Encoding.UTF8.GetString(yourByteArray, 0, yourByteArray.Length);	0
11822519	9795986	Get width of element of auto width	private void stk_main_SizeChanged(object sender, SizeChangedEventArgs e)\n{\n    double yourWidthNow = e.NewSize.Width;\n}	0
7409016	7408350	Debugging an XNA application	graphics = new GraphicsDeviceManager(this);     // "this" being your Game class\ngraphics.PreferredBackBufferWidth = 1024;\ngraphics.PreferredBackBufferHeight = 768;\ngraphics.IsFullScreen = false;\ngraphics.ApplyChanges();	0
13289519	13289422	Return multiple rows from a select new using linq	var DRows = from inputRow in inputTable.AsEnumerable()\n                 where inputRow.D == 'some value'\n                 select new outputRow(inputRow, *delegateToProcessor*)\n\nvar ERows = from inputRow in inputTable.AsEnumerable()\n                 where inputRow.E == 'some value'\n                 select new outputRow(inputRow, *delegateToProcessor*)\n\nvar FRows = from inputRow in inputTable.AsEnumerable()\n                 where inputRow.F == 'some value'\n                 select new outputRow(inputRow, *delegateToProcessor*)\n\nreturn DRows.Union(ERows).Union(FRows);	0
34454093	34450270	How do I properly choose assemblies from referenced NuGet packages?	List<IPackageAssemblyReference> assemblyReferences =\n    GetCompatibleItems(package.AssemblyReferences).ToList();\n\nstatic IEnumerable<T> GetCompatibleItems<T>(FrameworkName targetFramework, IEnumerable<T> items) where T : IFrameworkTargetable\n{\n        IEnumerable<T> compatibleItems;\n        if (VersionUtility.TryGetCompatibleItems(targetFramework, items, out compatibleItems))\n        {\n                return compatibleItems;\n        }\n        return Enumerable.Empty<T>();\n}	0
8747661	8747584	How to get path of project from test project?	var execPath = AppDomain.CurrentDomain.BaseDirectory;	0
20244380	20147839	Deserialize DateTime? Json	DateTime dt = new DateTime(long ticks);	0
10380166	472906	Converting a string to byte-array without using an encoding (byte-by-byte)	static byte[] GetBytes(string str)\n{\n    byte[] bytes = new byte[str.Length * sizeof(char)];\n    System.Buffer.BlockCopy(str.ToCharArray(), 0, bytes, 0, bytes.Length);\n    return bytes;\n}\n\nstatic string GetString(byte[] bytes)\n{\n    char[] chars = new char[bytes.Length / sizeof(char)];\n    System.Buffer.BlockCopy(bytes, 0, chars, 0, bytes.Length);\n    return new string(chars);\n}	0
23578561	23578513	How to implement singleton design pattern in C#?	public sealed class Singleton\n{\n     private static readonly Singleton _instance = new Singleton();\n}	0
33504852	33440438	how to hide / collapse title bar in a UWP app?	ApplicationViewTitleBar formattableTitleBar = ApplicationView.GetForCurrentView().TitleBar;\nformattableTitleBar.ButtonBackgroundColor = Colors.Transparent;\nCoreApplicationViewTitleBar coreTitleBar = CoreApplication.GetCurrentView().TitleBar;\ncoreTitleBar.ExtendViewIntoTitleBar = true;	0
25574619	25574211	Creating a specific type of object chosen from a set of types obtained through reflection	List<object> parms = new List<object>();\nparms.Add(property1);\nparms.Add(property2);\n\nObjectHandle objHandle = Activator.CreateInstance("assemblyName", "className", false, null, null, parms.ToArray(), null, null );\n\nobject workingObject = objHandle.Unwrap();	0
2959979	2959948	Determining if a set of coordinates are within the same area	d = acos(sin(lat1).sin(lat2)+cos(lat1).cos(lat2).cos(long2??ong1)).R	0
24347140	24346695	how do I set the name of a system.timer dynamically	using System;\nusing System.Collections.Generic;\nusing System.Threading;\n\nnamespace StackOverFlowConsole3\n{\n\n   public class NamedTimer : System.Timers.Timer\n   {\n      public readonly string name;\n\n      public NamedTimer(string name)\n      {\n         this.name = name;\n      }\n   }\n\n   class Program\n   {\n      static void Main()\n      {\n         for (int i = 1; i <= 10; i++)\n         {\n            var timer = new NamedTimer(i.ToString());\n            timer.Interval = i * 1000;\n            timer.Elapsed += Main_Tick;\n            timer.AutoReset = false;\n            timer.Start();\n         }\n         Thread.Sleep(11000);\n      }\n\n      static void Main_Tick(object sender, EventArgs args)\n      {\n         NamedTimer timer = sender as NamedTimer;\n         Console.WriteLine(timer.name);\n      }\n   }\n}	0
8298150	8296790	Custom Paging in ASP.Net	//This is the method to bind the gridview to the data.\nprivate void LoadGridview()\n{\n    List<MyObject> MyObjectList = MyObject.FillMyList();\n    if (MyObjectList != null && MyObjectList.Count > 0)\n    {\n        this.GridView1.DataSource = MyObjectList;\n        this.GridView1.DataBind();\n    }\n}\n\n//When the index changes\nprotected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)\n{\n    //Changes the page\n    this.GridView1.PageIndex = e.NewPageIndex;\n    LoadGridview();\n}\nprotected void Page_Load(object sender, EventArgs e)\n{\n    //When the page loads\n    LoadGridview();\n}	0
24297195	24297076	C# How split a string containing numbers in array	string test = "1Hello World  2I'm a newbie 33The sun is big 176The cat is black";\n\nRegex regexObj = new Regex(@"(\d+)([^0-9]+)", RegexOptions.IgnoreCase);\nMatch match = regexObj.Match(test);\nwhile (match.Success) \n{\n  string numPart = match.Group[1].Value;\n  string strPart = match.Group[2].Value;\n  match = match.NextMatch();\n}	0
6228186	6198092	Unable retrieve records from SQLite database for smart device application	sql_con = new SQLiteConnection("Data Source=DBfolder/emp.db;Version=3;");	0
1163781	1163761	Capture screenshot of active window?	ScreenCapture sc = new ScreenCapture();\n// capture entire screen, and save it to a file\nImage img = sc.CaptureScreen();\n// display image in a Picture control named imageDisplay\nthis.imageDisplay.Image = img;\n// capture this window, and save it\nsc.CaptureWindowToFile(this.Handle,"C:\\temp2.gif",ImageFormat.Gif);	0
22475575	22475505	Create a folder in C# project dynamically	string projectPath = Directory.GetParent(Directory.GetCurrentDirectory()).Parent.FullName;\n string folderName = Path.Combine(projectPath, "Top-Level Folder");\n System.IO.Directory.CreateDirectory(folderName);	0
13418296	8198096	How to check if a jpeg image file is actually a valid image before trying to load?	grep -P '^......JFIF' ./'raccoon paint.jpeg'	0
19198590	19198163	A code to obtain each 8x8 block form a 2d array C#	List<Image> splitImages(int blockX, int blockY, Image img)\n{\n    List<Image> res = new List<Image>();\n    for (int i = 0; i < blockX; i++)\n    {\n        for (int j = 0; j < blockY; j++)\n        {\n            Bitmap bmp = new Bitmap(img.Width / blockX, img.Height / blockY);\n            Graphics grp = Graphics.FromImage(bmp);\n            grp.DrawImage(img, new Rectangle(0, 0, bmp.Width, bmp.Height), new Rectangle(i * bmp.Width, j * bmp.Height, bmp.Width, bmp.Height), GraphicsUnit.Pixel);\n            res.Add(bmp);\n        }\n    }\n    return res;\n}\n\nprivate void testButton_Click_1(object sender, EventArgs e)\n{\n    // Test for 4x4 Blocks\n    List<Image> imgs = splitImages(4, 4, pictureBox1.Image);\n    pictureBox2.Image = imgs[0];\n    pictureBox3.Image = imgs[1];\n    pictureBox4.Image = imgs[2];\n    pictureBox5.Image = imgs[3];\n}	0
478944	478805	How to optimize this SQL Query (from C#)	static void RetrieveMultipleResults(SqlConnection connection)\n{\n    using (connection)\n    {\n        SqlCommand command = new SqlCommand(\n          "SELECT CategoryID, CategoryName FROM dbo.Categories;" +\n          "SELECT EmployeeID, LastName FROM dbo.Employees",\n          connection);\n        connection.Open();\n\n        SqlDataReader reader = command.ExecuteReader();\n\n        while (reader.HasRows)\n        {\n            Console.WriteLine("\t{0}\t{1}", reader.GetName(0),\n                reader.GetName(1));\n\n            while (reader.Read())\n            {\n                Console.WriteLine("\t{0}\t{1}", reader.GetInt32(0),\n                    reader.GetString(1));\n            }\n            reader.NextResult();\n        }\n    }\n}	0
14796199	14794400	Making an application run on startup	this.menu_startup.Click += (s, ea) =>\n    {\n        RegistryKey rkApp = Registry.CurrentUser.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true);\n        string appPath = Application.ExecutablePath.ToString();\n\n        this.menu_startup.Checked = (rkApp.GetValue(this.regKey) == null);\n\n        if (rkApp.GetValue(this.regKey) == null)\n        {\n            rkApp.SetValue(this.regKey, appPath);\n        }\n        else\n        {\n            rkApp.DeleteValue(this.regKey, false);\n        } \n    };	0
9956098	9955961	How to unbox a box to an ICollection with an unknown type?	foreach (string property in propertyList)\n{\n    PropertyInfo pinfo = record.GetType().GetProperty(property);\n    var recordProperty = pinfo.GetValue(record, null);\n}	0
771522	768641	Asynchronous WebRequest with POST-parameters in .NET Compact Framework	((HttpWebRequest)rqst).AllowWriteStreamBuffering = true;	0
13733389	13733369	How to "subtract 1" from a flags-type enum?	NodeLevel newLevel = (NodeLevel) ((int)currentLevel / 2);	0
22634073	22631537	WPF Code Behind: DataGridTextColumn shows Column headers but not data from xmlprovider with xpath	// loading xml for grid\nXmlDocument doc = new XmlDocument();\ndoc.Load(_file_location_); // (it does find the xml)\n\n// setting the xml provider\nXmlDataProvider _xmlDataProvider = new XmlDataProvider();\n_xmlDataProvider.Document = doc;\n_xmlDataProvider.XPath = @"/ShipData/Draught/Sensor";\n\n// Setting the datacontext (updated code)\nBinding binding = new Binding();\nbinding.Source = _xmlDataProvider;\nMDataGrid.SetBinding(DataGrid.ItemsSourceProperty, binding);\n\n// Creating the column Sensor (as an example) and create a new binding for xpath\nvar dataGridTextColumn = new DataGridTextColumn();\n\nBinding bindingSensor = new Binding();\nbindingSensor.XPath = "@Name";\ndataGridTextColumn.Binding = bindingSensor;\n\ndataGridTextColumn.Header = "Sensor";\n\n// other repeating columns (bis+man ...) omitted for this example\n\n// adding the column to the datagrid\nMDataGrid.Columns.Add(dataGridTextColumn);	0
27433780	27415652	Get eastern time in c# without converting local time	-1 * (sourceOffset - destOffset)	0
5747451	5747401	How to replace value in list at same collection location	List<string> animals = new List<string>();\nanimals.Add("cat");\nanimals.Add("dog");\nanimals.Add("bird");\n\nanimals.RemoveAt(2);\nanimals.Insert(2, "snail");	0
1950158	1950107	.net 2.0 c# retrieving a value from xml	XmlDocument doc = new XmlDocument();\n    using (XmlTextReader tr = new XmlTextReader(new StringReader(xmlString)))\n    {\n        tr.Namespaces = false;\n        doc.Load(tr);\n    }\n    string woeId = doc.GetElementsByTagName("woeid")[0].InnerText;	0
4140797	4140770	Having trouble importing C# interface into Python	import clr\nclr.AddReference('MyInterfaces')\n\nfrom Company.Shared.MyInterfaces import IDevice	0
4661296	4661256	How can I create a windows service that listens to a directory and then sftp's it to a local directory	System.IO.FileSystemWatcher	0
19026401	19026352	How to change 1 to 00001?	string value = String.Format("{0:D5}", number);	0
27399466	27399413	Extracting Xml Elements from Outerxml type	string reason = (string)xml.Element("field1").Element("field2").Attribute("reason");	0
1329928	1329842	How can I shorten List<List<KeyValuePair<string, string>>>?	namespace Application\n{\n    using MyList = List<List<KeyValuePair<string, string>>>;\n\n    public class Sample\n    {\n        void Foo()\n        {\n            var list = new MyList();\n        }\n    }\n}	0
22859361	22859146	Load checked datagridview row to another datagridview in another form	foreach (DataGridViewRow row in YourDgvMain.Rows)\n{\n  if ((bool)row.Cells[0].Value == true)\n  {\n    YourOtherDgv.Rows.add(row);\n  }\n}	0
24827590	24827496	Get values between string in C#	var string = "%2%,%12%,%115%+%55%";\nvar values = string.replace("%", "").replace("+", "").split(',');	0
10533174	10531164	Excel Comment truncated during reading	bool read = true;\n                    string finalText="";\n                    int j = 1;\n                    int lengthMax = 200;\n\n\n                    while(read)\n                    {\n                        string textnya = comment.Shape.TextFrame.Characters(j, lengthMax).Text;\n                        finalText = finalText+textnya;\n                        if (textnya.Length < lengthMax)\n                        {\n                            read = false;\n                        }\n                        else\n                        {\n                            j = j + lengthMax;\n                        }\n\n                    }\n\n                    MessageBox.show(finalText);	0
12617921	12617690	Entity Framework Insert object with related object	public void AddComment()\n  {\n       var ctx = new WallContext();\n\n        User user = new User() { UserID = 1 };  \n\n        ctx.Users.Attach(user);\n\n        Comment comment = new Comment() { CommentContent = "This is a comment", CommentCreationTime = DateTime.Now, User = user };\n\n        comments = new CommentsRepository(ctx);\n\n        comments.AddComment(comment);\n        ctx.SaveChanges();\n   }	0
2573206	2573172	XML serializer filename	public class TestSerialize\n{\n    public string Test1;\n    public int Test2;\n}\n\nclass Program\n{      \n    [STAThread]\n    static void Main()\n    {\n        var serializer = new XmlSerializer(typeof(TestSerialize));\n        using (XmlWriter writer = XmlWriter.Create(Guid.NewGuid() + ".xml"))\n        {                \n            serializer.Serialize(writer, new TestSerialize() { Test1 = "hello", Test2 = 5 });\n        }\n\n        Console.ReadLine();\n    }\n}	0
21759214	21758725	I got success to get a new facebook access token for long time 60 days . How can i test/check that it is for 60 days?	GET /debug_token?input_token={input-token}&access_token={access-token}	0
7675256	7674923	Reading a PVOID in c#, how many bits should I read?	byte [] ptr_bytes = rdr.ReadBytes(System.IntPtr.Size);	0
3050943	840813	How to use WebBrowser control DocumentCompleted event in C#?	private void webBrowser_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)\n{\n    string url = e.Url.ToString();\n    if (!(url.StartsWith("http://") || url.StartsWith("https://")))\n    {\n            // in AJAX\n    }\n\n    if (e.Url.AbsolutePath != this.webBrowser.Url.AbsolutePath)\n    {\n            // IFRAME \n    }\n    else\n    {\n            // REAL DOCUMENT COMPLETE\n    }\n}	0
13056987	11564021	'auto contrast' text color in a gridview?	private Color GetContrastedColor(Color colorToContrast) {\n\n        var yiq = ((colorToContrast.R * 299) + (\n            colorToContrast.G * 587) + (\n            colorToContrast.B * 114)) / 1000;\n\n        return (yiq >= 128) ? Color.FromArgb(40, 40, 40) : Color.WhiteSmoke;\n    }	0
12189369	12154166	creating header again when printing table with multiple pages	thead { display:table-header-group }	0
14375589	14375483	Extract all strings between [ text1 ] [text2] tags	string str = "Select * from Table Where [PARAM1] = [PARAM2] ...";\nstring[] Array = str.Split().Where(r=> r.StartsWith("[") && r.EndsWith("]"))\n                    .Select(r=> r.Trim('[',']'))\n                    .ToArray();	0
8961114	8961093	How can I do an outer join to more than two tables in LINQ?	var results =\n    from j in table.GetAll()\n    join s in refTableStatuses.GetAll() on j.Status equals s.Key2\n         into statuses\n    from s in statuses.DefaultIfEmpty()\n    join t in refTableTypes.GetAll() on j.Type equals t.Key2\n         into types\n    from t in types\n    select new Job\n    {\n        Key1 = j.Key1,\n        Key2 = j.Key2,\n        Title = j.Title,\n        Status = s == null ? null : s.Title, // value from Ref (Status) s\n        Type = t == null ? null : t.Title    // value from Ref (Type) t\n    };	0
12049113	12048926	How to map related objects with a custom name for the foreign key property, like PostId instead of Post_Id	protected override void OnModelCreating(DbModelBuilder modelBuilder)\n{\n  modelBuilder.Entity<Comment>()\n    .HasRequired(t => t.Post)\n    .WithMany(t => t.Comments)\n    .Map(m => m.MapKey("PostId"));\n}	0
7999245	7999196	How to round decimal for 2 decimal places	decimal.Truncate(<number> * 100) / 100;	0
4597375	4597337	Adding a row to a TableLayoutPanel in C# Windows Form	RowStyles.Add()	0
23519265	23518534	Linq query to order list by occurences of foreign key in another list	model.NewSubtitles = (from Profile in _ProfileRepo.GetAll()\n                  join downloads in _DownloadRepo.GetAll() on Profile.UserId equals downloads.UserId\n                 group downloads by Profile into p\n                  orderby p.Count() descending\n                  select new {p.Key.UserId , p.Key.UserName , p.Count()).Take(5).ToList();	0
24367916	24367817	How to handle long running process using TPL	TaskCreationOptions.LongRunning	0
11111335	11111254	How do I handle countries that use multiple currencies in .NET?	NumberFormatInfo LocalFormat = (NumberFormatInfo)NumberFormatInfo.CurrentInfo.Clone();\nLocalFormat.CurrencySymbol = "???";\n\ndecimal money = 100;\nConsole.WriteLine(money.ToString("c", LocalFormat));	0
11541622	11541519	sending integer value in c# over network	BitConverter.GetBytes(integer);	0
19608110	19608068	Write file at a specific value and line	var data2 = File.ReadAllLines("itemdata.txt");\n\n//use linq if you want, it just an example fo understandin\nForeach (var dataline in data2 ) \n{\n   if (dataline.Contains("3343"))\n       dataline = "item_begin weapon 3343 item_type=weapon" //of course you can use the split, it just an example\n}\n\nFile.WriteAllLines("itemdata.txt", data2);	0
821438	821347	How to selectively underline strings in RichTextBox?	int start = 0;\n        for (int i = 0; i < contactsListView.SelectedItems.Count; i++)\n        {\n            if (contactsTextBox.TextLength != 0) contactsTextBox.Text += "; ";\n            start = contactsTextBox.TextLength;\n            contactsTextBox.Text += contactsListView.SelectedItems[i].Text +" " + contactsListView.SelectedItems[i].SubItems[1].Text + " [" + contactsListView.SelectedItems[i].SubItems[2].Text + "]";\n        }\n\n\n        this.contactsTextBox.Text += " ";\n        this.contactsTextBox.SelectionStart = 0;\n        this.contactsTextBox.SelectionLength = this.contactsTextBox.Text.Length-1;\n        contactsTextBox.SelectionFont = new Font(contactsTextBox.SelectionFont, FontStyle.Underline);\n        this.contactsTextBox.SelectionLength = 0;	0
17531319	17522965	How to add a watermark to a PDF file?	Rectangle pagesize = reader.GetCropBox(pageIndex);\nif (pagesize == null)\n    pagesize = reader.GetMediaBox(pageIndex);\nimg.SetAbsolutePosition(\n    pagesize.GetLeft(),\n    pagesize.GetBottom());	0
24224412	24224201	Adding data to ListBox from non-UI thread with Asynchronous method WP8.1	this.frame.Navigate(typeof(ShowResultsPage), details);	0
23758556	23758395	Getting MemberExpression, expecting ConstantExpression	.Where(j => j.Driver.Chatiness == 5)	0
26005962	26002683	using entity framework in classlibrary	PM> Install-Package EntityFramework -Version 6.0.0	0
30850465	30850197	getting keyboard input in winform listbox	private void listBox1_KeyPress(object sender, KeyPressEventArgs e)\n    {\n        string letter = "";\n        //letter = ProcessKey(e.KeyChar);\n        //or\n        letter = e.KeyChar.ToString();\n    }\n\n    private string ProcessKey(char key)\n    {\n        return key.ToString();\n    }	0
21950030	21949388	How to get SCHEMA.TABLES from another database?	declare @sql nvarchar(max);\nset @sql = N'select cast(''master'' as sysname) as db_name, name collate Latin1_General_CI_AI, object_id, schema_id, cast(1 as int) as database_id  from master.sys.tables ';\n\nselect @sql = @sql + N' union all select ' + quotename(name,'''')+ ', name collate Latin1_General_CI_AI, object_id, schema_id, ' + cast(database_id as nvarchar(10)) + N' from ' + quotename(name) + N'.sys.tables'\nfrom sys.databases where database_id > 1\nand state = 0\nand user_access = 0;\n\nexec sp_executesql @sql;	0
5856558	5856531	How to open a particular directory and SELECT a particular file there using C#	explorer.exe /select, filename	0
21708185	21707709	Return a class of List objects from a wcf service and assign it on the Client	New var as wcfserviceReferenceInstance.object	0
11658530	11516702	How to correctly load a WF4 workflow from XAML?	var dynamicActivity = ActivityXamlServices.Load(stream) as DynamicActivity;\nWorkflowInvoker.Invoke(dynamicActivity);	0
18758316	18757888	Calculate duration between first login and last logout from a set of records in datatable	dt.GroupBy(l => new {l.EmpId, l.Login.Date},\n    (key, g)=> new {\n             EmpId = key.EmpId,\n             Name = g.First().Name,\n             Login = g.Min(d => d.Login),\n             Logout = g.Max(d => d.Logout),\n             Duration = g.Min(d => d.Login) - g.Max(d => d.Logout)\n     });	0
11199639	4726053	Setting FlashVars of AxShockwaveFlash	axShockwaveFlash1.FlashVars = "auto_play=true&channel=adventuretimed&start_volume=25";\naxShockwaveFlash1.Movie = "http://www.justin.tv/widgets/live_embed_player.swf";	0
2693711	2692024	dynamically updating a datagrid from a XML file c# 3.5	FileSystemWatcher incoming = new FileSystemWatcher();\n    incoming.Path = @"c:\locationDirectory\";\n    incoming.NotifyFilter = NotifyFilters.LastAccess | \n                            NotifyFilters.LastWrite | \n                            NotifyFilters.FileName;\n    incoming.Filter = "file.xml";\n\n    incoming.Changed += new FileSystemEventHandler(OnChanged);\n\n    incoming.EnableRaisingEvents = true;	0
15062398	15062369	Can I define a method which take 1 or N string values as arguments	public bool CheckMyStringValues(params string[] strings)	0
24037825	24037684	How to evalute string of IP address in c#	String[] ip = { @"\10.4.1.2\Camera_save", @"\10.4.5.2\Camera_save" };\nString[] result = ip.Select(x => x.Split('.')[2]).ToArray();	0
642728	642604	C# regex to match a string which has a delimiter	(.*?) (start) ((?:(?:.*?) ;)+ (?:.*?) end fun)	0
33537056	33536476	Binding visibility of a control depending on the state of a string attribute in my viewmodel	Visibility="{qc:MultiBinding '$P0==$P1 ? Visibility.Visible : Visibility.Collapsed', P0={Binding CurrentTool}, P1={Binding brush}}"	0
30658673	30658510	Getting line of text after specific string in C#	var d = File.ReadAllLines(filePath);\n            var t = d.Where(g => g.Contains("Message"));\n            string[] splited;\n            foreach (var item in t)\n            {\n                splited = item.Split(new string[] { "Message=" }, StringSplitOptions.None);\n                Console.WriteLine(splited[1]);\n            }	0
10106459	10105728	DLL in platform builder	Directory.GetFiles()	0
13992475	13992429	Adding controls to TableLayoutPanel dynamically during runtime	Table.Controls.Add(new Label() { Text = "Type:", Anchor = AnchorStyles.Left, AutoSize = true }, 0, 0);\nTable.Controls.Add(new ComboBox() { Dock = DockStyle.Fill }, 0, 1);	0
10747965	10747918	Setting a generic type parameter from a method parameter	public class foo\n{\n    public void SomeMethod(Type type)\n    {\n        var methodInfo = this.GetType().GetMethod("SomeGenericMethod");\n        var method = methodInfo.MakeGenericMethod(new[] { type });\n        method.Invoke(this, null);\n    }\n\n    public void SomeGenericMethod<T>()\n    {\n        Debug.WriteLine(typeof(T).FullName);\n    }\n}\n\nclass Program\n{\n    static void Main(string[] args)\n    {\n        var foo = new foo();\n        foo.SomeMethod(typeof(string));\n        foo.SomeMethod(typeof(foo));\n    }\n}	0
10414707	2024273	Convert a two digit year to a four digit year	int fourDigitYear = CultureInfo.CurrentCulture.Calendar.ToFourDigitYear(twoDigitYear)	0
12088371	12088195	Reading data from Oracle DB using .Net is 10 times faster than using Java	stmt = conn.createStatement(java.sql.ResultSet.TYPE_FORWARD_ONLY, java.sql.ResultSet.CONCUR_READ_ONLY);\nstmt.setFetchSize(Integer.MIN_VALUE);	0
10083312	10070764	syntax for late attendance query	SELECT\n  E.EMPNAME\n  ISNULL(SUM(CASE WHEN A.TIMEIN > '08:00:00' THEN 1 ELSE 0 END), 0) AS LATE_ATTENDANCE\nFROM\n dbo.MASTEREMPLOYEE E\n LEFT JOIN dbo.viewATTENDANCE A ON A.EMPLOYEEID = E.EMPLOYEEID	0
11069307	11069222	How can get Child Nodes's List from parent Node's Attribute in C# xmldocument	var name = "Title";\nXDocument doc = XDocument.Load(path);\nvar selectors = (from elements in doc.Elements("Database").Elements("Table")\n                where elements.Attribute("name").Value == name\n                select elements).FirstOrDefault();\nvar list = selectors.Elements("Column").ToList();\nvar id = list[0];\nvar title = list[1];	0
11053267	11052958	Parse xml elements and their attributes in LINQ	...\nXNamespace xmlns = "Mytest/v1.0";\nvar eleSTAT = from node in xDoc.Descendants(xmlns + "STAT")\n...	0
401782	401740	Is there anyway to speed up SQL Server Management Objects traversal of a existing database?	Server server = new Server();\n\n// Force IsSystemObject to be returned by default.\nserver.SetDefaultInitFields(typeof(StoredProcedure), "IsSystemObject");\n\nStoredProcedureCollection storedProcedures = server.Databases["AdventureWorks"].StoredProcedures;\n\nforeach (StoredProcedure sp in storedProcedures) {\n    if (!sp.IsSystemObject) {\n        // We only want user stored procedures\n    }\n}	0
15257096	15256622	how can closed the TAB page by click?	private void closeTab_Click(object sender, EventArgs e) {\n  if (tabControl1.SelectedTab != null) {\n    tabControl1.SelectedTab.Dispose();\n  }\n}	0
16002513	16002480	Remove spaces in the string array	lines = lines.Select(l => String.Join(" ", l.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries))).ToArray();	0
2199549	2199516	linq to sql -get data from a table related to another	public static Document[] GetFavouriteDocumentsForProject(int projectId)\n{\n    using (var db = new MyContext())\n    {\n        return\n            (from favourite in db.FavouriteDocuments\n            where favourite.ProjectID == projectId\n            select favourite.Document).ToArray();\n    }\n}	0
12840449	12821896	Windows Forms Chart - Add A Value Marker	StripLine stripLine = new StripLine();\n// highlight a strip of 8 hours in the X axis\nstripLine.StripWidth = 8;\nstripLine.StripWidthType = DateTimeIntervalType.Hours;\nstripLine.BackColor = System.Drawing.Color.PapayaWhip;\nstripLine.BorderColor = System.Drawing.Color.LightSeaGreen;\nstripLine.BorderWidth = 2;\n// start the highlighting 7 hours in (from 07:00 to 15:00)\nstripLine.IntervalOffset = 7;\nstripLine.IntervalOffsetType = DateTimeIntervalType.Hours;\n// repeat this strip every 1 day\nstripLine.Interval = 1;\nstripLine.IntervalType = DateTimeIntervalType.Days;\nthis.TopOfBookChart.ChartAreas[0].AxisX.StripLines.Add(stripLine);	0
8593104	8593047	C# RegularExpressions Match	string regexPattern = @"<param\svalue=""(?<paramVal>[^""]*)""";\nstring stuffImLookingFor = Regex.Match(input, regexPattern).Groups("paramVal").Value;	0
25681180	25679732	List 'Except' comparison - ignore case	List<string> except = list1.Except(list2, StringComparer.OrdinalIgnoreCase).ToList();	0
13624750	13604359	Define XmlElement from class name	Type type = list.Items.First().GetType();\n  string root = type.Name + "s";\n\n  XmlElementAttribute myAttribute = new XmlElementAttribute();\n  myAttribute.ElementName = type.Name;\n\n  XmlAttributes attribs = new XmlAttributes();\n  attribs.XmlElements.Add(myAttribute);\n\n  XmlAttributeOverrides myOverride = new XmlAttributeOverrides();\n\n   myOverride.Add(typeof(ObjectList), "Items", attribs);\n\n   XmlWriter xmlw = XmlWriter.Create(fileName);\n   XmlSerializer writer = new XmlSerializer(\n                typeof(ObjectList), \n                myOverride, \n                new Type[] { type }, \n                null,\n                null);	0
2551900	2551881	Override default behavior of SPACE key in .net WinForms ListView	private void listView1_KeyDown(object sender, KeyEventArgs e) {\n  if (e.KeyData == Keys.Space) {\n    listView1.FocusedItem.Selected = !listView1.FocusedItem.Selected;\n    e.Handled = e.SuppressKeyPress = true;\n  }\n}	0
7295520	7295504	How can i get a part of an image and use it as a separate image?	// Create a Bitmap object from a file.\nBitmap myBitmap = new Bitmap("Grapes.jpg");\n\n// Clone a portion of the Bitmap object.\nRectangle cloneRect = new Rectangle(0, 0, 100, 100);\nSystem.Drawing.Imaging.PixelFormat format =\n    myBitmap.PixelFormat;\nBitmap cloneBitmap = myBitmap.Clone(cloneRect, format);\n\n// Draw the cloned portion of the Bitmap object.\ne.Graphics.DrawImage(cloneBitmap, 0, 0);	0
16674882	16674649	Converter not found? XamlParseException: Cannot find a Resource with the Name/Key StringTruncator	Text="{Binding BrowserViewModel.PageTitle, Converter={app:StringTruncator}}"	0
8501698	8444998	Multi-touch screen and WPF listbox	private void TreePreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)\n{\n    _startPoint = e.GetPosition(null);\n    _checkDragDrop = true;\n}\nprivate void TempTreeMouseMove(object sender, MouseEventArgs e)\n{\n    if (e.LeftButton == MouseButtonState.Pressed)\n    {\n        var mousePos = e.GetPosition(null);\n        var diff = _startPoint - mousePos;\n        if (_checkDragDrop)\n        {\n            if (Math.Abs(diff.X) > SystemParameters.MinimumHorizontalDragDistance || Math.Abs(diff.Y) > SystemParameters.MinimumVerticalDragDistance)\n            {\n                _checkDragDrop = false;\n                .\n                .\n                .\n                DragDropEffects val = DragDrop.DoDragDrop(DragSourceList, dragData, DragDropEffects.Move);\n\n            }\n        }\n    }\n}	0
3624738	3624687	How to get ushort data in C#, A909 for 41104?	String.Format("{0:X}", 41104);	0
4681441	4680747	Replace double quotes in json string with empty string	var str = '"STATUS_MESSAGE": {"statusMessage":" "some "bad" value"   ", "addTime" :"1294872330"}"';\nstr = str.replace(/("statusMessage"\s*:\s*")(.+?)("\s*,\s*"addTime)/, function(m0,m1,m2,m3) { return m1 + m2.replace(/"/g,'') + m3; });\n\n//now str == "STATUS_MESSAGE": {"statusMessage":" some bad value   ", "addTime" :"1294872330"}"	0
2927312	2921491	How to set an error message from EditorPart when ApplyChanges returns false?	string _errorMessage;\n\npublic override bool ApplyChanges()\n{\n try\n {\n    // save properties\n    return true;\n }\n catch(Exception ex)\n {\n    _errorMessage = ex.Message; // is there any similar property I can fill?\n    return false;\n }\n}\n\nprotected override OnPreRender(EventArgs e)\n{\n  if (!string.IsNullOrEmpty(_errorText))\n  {\n    this.Zone.ErrorText = string.Format("{0}<br />{1}", this.Zone.ErrorText,\n                           _errorText);\n  }      \n  base.OnPreRender(e);\n}	0
1242944	1239808	creating an object with user's selections in UI, and displaying it back	DataTable dtbl = new DataTable();\n\n    if (ViewState["dtbl"] == null)\n    {\n        DataColumn PID = new DataColumn();//Adding column When adding item first time\n        dtbl.Columns.Add(PID);\n        DataColumn PName = new DataColumn();\n        dtbl.Columns.Add(PName);\n    }\n    else\n    {\n        dtbl = (DataTable)ViewState["dtbl"];\n    }\n\n    DataRow dr = dtbl.NewRow();\n    dr["PID"] = "1";\n    dr["PName"] = "product Name";\n    dtbl.Rows.Add(dr);\n    ViewState.Add("dtbl", dtbl);\n\n    yourGridView.DataSource = dtbl.DefaultView;\n    yourGridView.DataBind();	0
22676397	22675864	Convert a bitmap with white and black areas to a list of cartesian position using C#	private void GetPixel_Example(PaintEventArgs e)\n{\n  // Create a Bitmap object from an image file.\n  Bitmap myBitmap = new Bitmap("Grapes.jpg");\n\n  // Get the color of a pixel within myBitmap.\n  Color pixelColor = myBitmap.GetPixel(50, 50);\n\n  // Fill a rectangle with pixelColor.\n  SolidBrush pixelBrush = new SolidBrush(pixelColor);\n  e.Graphics.FillRectangle(pixelBrush, 0, 0, 100, 100);\n}	0
13315832	13315510	Find Entities with NHibernate from other Object	NHibernate.Criterion.Example	0
4327634	4327359	How to cache items within a filterAttribute	filterContext.HttpContext.Cache	0
19369225	19328928	can we redirect user from webview to metro application?	void webView_LoadCompleted(object sender, NavigationEventArgs e)\n    {\n        if (e.Uri.AbsoluteUri.Contains("finished.html"))\n        {\n            this.Frame.Navigate(typeof(MainPage));\n        }\n    }	0
18462518	18462152	String comparison with German letter ?	string str1="Andreas Gra??l";\nstring str2="Andreas Grassl";\nConsole.WriteLine(string.Equals(str1,str2));  //False\nConsole.WriteLine(string.Equals(str1,str2,StringComparison.CurrentCulture));  //True	0
7220330	7093815	Deleting a row from database and gridview in wpf	int unitTypeId = (this.grdUnitTypes.SelectedItem as UnitType).ID;\n            ConfirmWindowResult result = Helpers.ShowConfirm(this, SR.GlobalMessages.AreYouSureToDelete, SR.GlobalMessages.Warning);\n            if (result == ConfirmWindowResult.Yes)\n            {\n                using (AccountingEntities cntx = new AccountingEntities())\n                {\n                    try\n                    {\n                        cntx.UnitTypes.DeleteObject(cntx.UnitTypes.First(x => x.ID == unitTypeId));\n                        cntx.SaveChanges();\n                        dataPager.Source = cntx.UnitTypes.ToList();\n                        MessageBox.Show("Success");\n                    }\n                    catch (Exception ex)\n                    {\n                        MessageBox.Show("Error");\n                    }\n                    finally\n                    {\n                        cntx.Dispose();\n                    }\n                }\n            }	0
21806731	21806704	How to get POST data inside a C# WebMethod?	[WebMethod]\n[ScriptMethod(ResponseFormat = ResponseFormat.Json)]\npublic static string GetClienteById(int id)	0
5863814	5863786	Filestream only reading the first 4 characters of the file	fs.Read()	0
22492493	22492128	How can I obtain a list of images/files with a compression type of LZW.	Dim directory As New IO.DirectoryInfo("D:\TestDir\")\nDim filelist As IO.FileInfo() = directory.GetFiles("*.LZW")\n\n\nFor Each file as IO.FileInfo In filelist\n    <convert>\nNext	0
1385140	1385006	How to query a workflow instance for its execution state	IEnumerable<BookmarkInfo> bookMarks = workflowInstance.GetAllBookmarks();	0
13381716	11237702	How to Write to app.config in setup project and use it in the program	string path = Application.ExecutablePath;\nConfiguration config = ConfigurationManager.OpenExeConfiguration(path);	0
10522593	10522458	How to determine if ping reply has reached its timeout?	reply.Status	0
12707916	12707813	Set image coordinates programatically	// Create Image Element\nImage myImage = new Image();\nmyImage.Width = 200;\n\n// Create source\nBitmapImage myBitmapImage = new BitmapImage();\n\n// BitmapImage.UriSource must be in a BeginInit/EndInit block\nmyBitmapImage.BeginInit();\nmyBitmapImage.UriSource = new Uri(@"C:\Documents and Settings\All Users\Documents\My Pictures\Sample Pictures\Water Lilies.jpg");\n\n// To save significant application memory, set the DecodePixelWidth or   \n// DecodePixelHeight of the BitmapImage value of the image source to the desired  \n// height or width of the rendered image. If you don't do this, the application will  \n// cache the image as though it were rendered as its normal size rather then just  \n// the size that is displayed. \n// Note: In order to preserve aspect ratio, set DecodePixelWidth \n// or DecodePixelHeight but not both.\nmyBitmapImage.DecodePixelWidth = 200;\nmyBitmapImage.EndInit();\n//set image source\nmyImage.Source = myBitmapImage;	0
22456887	22456462	How do I force a Task to stop?	Thread.Abort	0
9401746	9401721	How do I serialize an object with a string value that contains an ampersand?	"\u0160"	0
33486193	33485643	VSCODE snippet for creating new C# class with namespace declaration	"Namespace and class": {\n    "prefix": "namespaceAndClass",\n    "body": [\n        "namespace $1",\n        "{",\n        "   class $2",\n        "   {",\n        "",\n        "   }",\n        "}",\n    ],\n    "description": "Create a namespace block with a class"\n }	0
19130427	19130325	How to set Image Web Control into Bitmap in ASP.NET?	Bitmap bitmap = new Bitmap(Server.MapPath(imgLoader.ImageUrl));	0
34473333	34473281	embedded images sent via outlook with html body are not shown on smartphones	oAttach = oAttachs.Add(itm.ToString)\noAttach.PropertyAccessor.SetProperty "http://schemas.microsoft.com/mapi/proptag/0x3712001F", "backlog.png'	0
1918265	1918244	How can I access an object property set within an initializer?	...\n.Select( u => {\n    var rc = u.Reviews.Count(...);\n    var hyc = ...;\n    ...\n    return new User() { /*now reference precomputed vars rc, hyc, ...*/ };})\n...	0
9308332	9308073	how to assign linq result to multidimensional array	//this generates an array of (up to 4) objects of an anonymous type\nvar query = (from b in db.FourBodyImages\n                     where b.Status == true\n                     orderby b.CreaedDate descending\n                     select new { b.BodyImage, b.Description, b.HeaderName }\n                   ).Take(4).ToArray();\n\n//no need for count, we can use the array's length\nif (query.Length < 4)\n{\n   //i have no idea about your requirements, \n   //but if we have less than 4 images - panic\n   throw new InvalidOperationException()\n}\n\n//no need for the "for-if", that's an anti-patern\nimgBody1.ImageUrl = "FourBodyImages/" + query[0].BodyImage;\nimgBody2.ImageUrl = "FourBodyImages/" + query[1].BodyImage;\nimgBody3.ImageUrl = "FourBodyImages/" + query[2].BodyImage;\nimgBody4.ImageUrl = "FourBodyImages/" + query[3].BodyImage;	0
7228849	7228808	Xml Parser in C#	class Program\n{\n    static void Main()\n    {\n        var doc = XDocument.Load("test.xml");\n        var key = doc\n            .Descendants("setting")\n            .Descendants("key")\n            .FirstOrDefault(x => x.Attribute("name").Value == "ankit");\n        if (key != null)\n        {\n            key.Attribute("value").Value = "yes";\n        }\n        doc.Save("new.xml");\n    }\n}	0
1140475	1140220	What is the most efficient way to compare/sort items from two arrays?	var allItems = (new [] {"Table", "Chair", "TV", "Fireplace", "Bed"});\nvar hasItems = (new [] {"Table", "Chair"});\n\nvar hasList = hasItems.ToList();\nvar needsList = allItems.Except(hasItems).ToList();	0
10765277	10527358	ISupportIncrementalLoading only fires once	private async Task<LoadMoreItemsResult> LoadDataAsync(uint count)\n{\n  Task task = Task.Delay( 1 );\n  await task;\n\n  for (int i = 0; i < count; i++)\n  {\n    Add(new MyData { Title = string.Format("Item: {0}, {1}", i, System.DateTime.Now) });\n  }\n\n  return new LoadMoreItemsResult {Count = count};\n}	0
8598088	8598057	How to properly set sessions in HttpContext?	public class MyHandler : IHttpHandler, IRequireSessionState\n{\n   public bool IsReusable { get { return false; } }\n\n   public void ProcessRequest(HttpContext ctx)\n   {\n       // your code here\n   }\n}	0
5648405	5648347	How to open an excel document using c#	System.Diagnostics.Process.Start("myFile.xls");	0
34461423	34461377	Make a phone call In Windows 10 mobile	private void TelephoneButton_Click(object sender, RoutedEventArgs e)\n{\n    Windows.ApplicationModel.Calls.PhoneCallManager.ShowPhoneCallUI("+380442308888", "The Name goes here");\n}	0
9458794	9458724	How do I convert from long value to KB string format	long memory = 210957130;\nConsole.WriteLine("{0:N0} K", memory / 1024);\nConsole.WriteLine(string.Format(new CultureInfo("en-US"), "{0:N0} K", memory / 1024));	0
8797659	8797646	Create ListBox DataTemplate in C#	DataTemplate template = new DataTemplate();\nFrameworkElementFactory factory =\n  new FrameworkElementFactory(typeof(StackPanel));\ntemplate.VisualTree = factory;\nFrameworkElementFactory childFactory =\n  new FrameworkElementFactory(typeof(Image));\nchildFactory.SetBinding(Image.SourceProperty, new Binding("Machine.Thumbnail"));\nchildFactory.SetValue(Image.WidthProperty, 170.0);    \nchildFactory.SetValue(Image.HeightProperty, 170.0);\nfactory.AppendChild(childFactory);\nchildFactory = new FrameworkElementFactory(typeof(Label));\nchildFactory.SetBinding(Label.ContentProperty,\n  new Binding("Machine.Descriiption"));\nchildFactory.SetValue(Label.WidthProperty, 170.0);\nchildFactory.SetValue(Label.HorizontalAlignmentProperty,\n  HorizontalAlignment.Center);\nfactory.AppendChild(childFactory);	0
25387807	25382863	webHttpBinding with certificate	netsh http add sslcert ipport=0.0.0.0:8000 certhash=000...a5e6 appid={001-...-FEFF}	0
2449037	2443739	How can I have a (semi) transparent background in GTK Sharp?	gtk_window_set_opacity(window, 0.5);	0
23330944	23330901	Connect to SQL Server CE Database online	Data Layer	0
4159914	4159866	Help with Linq expression to return a list of strings based on field count	var topComments = from comment in Comments\n                  group comment by comment.Category into grp\n                  orderby grp.Count() descending\n                  select grp.Key;\n\nvar topFive = topComments.Take(5);	0
26506041	26505498	transfer data from one page to another page in C# ASP.NET	String s = Request.QueryString["field1"];	0
7743409	7743341	Parsing a string to an array in C#	NameValueCollection values = HttpUtility.ParseQueryString("section[]=100&section[]=200&section[]=300&section[]=400");\nstring[] result = values["section[]"].Split(',');\n// at this stage \n// result[0] = "100"\n// result[1] = "200"\n// result[2] = "300"\n// result[3] = "400"	0
10970618	10967786	How to encode and decode Broken Chinese/Unicode characters?	using System.Text;\nusing System.Windows.Forms;\n\nnamespace Demo\n{\n    class Program\n    {\n        static void Main(string[] args)\n        {\n            string s = "???????????????"; // Unicode\n            Encoding Windows1252 = Encoding.GetEncoding("Windows-1252");\n            Encoding Utf8 = Encoding.UTF8;\n            byte[] utf8Bytes = Utf8.GetBytes(s); // Unicode -> UTF-8\n            string badDecode = Windows1252.GetString(utf8Bytes); // Mis-decode as Latin1\n            MessageBox.Show(badDecode,"Mis-decoded");  // Shows your garbage string.\n            string goodDecode = Utf8.GetString(utf8Bytes); // Correctly decode as UTF-8\n            MessageBox.Show(goodDecode, "Correctly decoded");\n\n            // Recovering from bad decode...\n            byte[] originalBytes = Windows1252.GetBytes(badDecode);\n            goodDecode = Utf8.GetString(originalBytes);\n            MessageBox.Show(goodDecode, "Re-decoded");\n        }\n    }\n}	0
17276735	17276011	select custom number of datas from sql table using datagrid input	declare @Stuff as Table ( Name VarChar(10), Number Int )\ninsert into @Stuff ( Name, Number ) values ( 'data1', 4 ), ( 'data2', 3 ), ( 'data3', 2 )\n\n; with Repeat ( Name, Number, Counter ) as (\n  select Name, Number, 1\n    from @Stuff\n    where Number > 0\n  union all\n  select Name, Number, Counter + 1\n    from Repeat\n    where Counter < Number\n  )\nselect Name\n  from Repeat\n  order by Name, Counter\n  option ( maxrecursion 0 )	0
7211836	7210051	Catching exceptions which may be thrown from a Subscription OnNext Action	public static IObservable<T> IgnoreObserverExceptions<T, TException>(\n                                this IObservable<T> source\n                               ) where TException : Exception\n{\n    return Observable.CreateWithDisposable<T>(\n        o => source.Subscribe(\n            v => { try { o.OnNext(v); }\n                   catch (TException) { }\n            },\n            ex => o.OnError(ex),\n            () => o.OnCompleted()\n            ));\n}	0
7532907	7532775	Adding a new column at the start of an excel table in an excel	Worksheet sheet = (Worksheet) workBookIn.Sheets[1]; // Worksheet indexes are one based\n\nRange rng = sheet.get_Range("A1", Missing.Value);\n\nrng.EntireColumn.Insert(XlInsertShiftDirection.xlShiftToRight,\n                        XlInsertFormatOrigin.xlFormatFromRightOrBelow);	0
12647129	12647025	linq select from dictionary	var dictionary = MyDC.SomeTable\n               .Where(...)\n               .GroupBy(...)\n               .ToDictionary(x => x.Key, x=> x.Count());\n\nvar result = new  MyCountModel\n               {\n                  CountSomeByte1 = dictionary[1],\n                  CountSomeByte2 = dictionary[2],\n                  ....\n                  CountSomeByte6 = dictionary[6]\n                });	0
5487743	5487667	Mash a list together from some properties and a bit of logic	var result = allItems.Select(\n    item=>\n    item.Prop1==item.Prop2\n       ? item.Prop1\n       : String.Format("{0}-{1}",\n          item.Prop1, item.Prop2)\n);	0
5884046	5883972	how to retrieve checkboxlist values for from table for the given particular ID 	var vehicle = Vehicles.Where(v => v.VehicleId == 1).FirstOrDefault(); // replace 1 by the Id of the vehicle you want.	0
31468224	31314245	A timeout occured after 30000ms selecting a server using CompositeServerSelector	new MongoClient("mongodb://username:password@ds011111.mongolab.com:11111/db-name")	0
21730350	21730101	Proper way to delay code execution in a background worker	var cancel = new CancellationTokenSource();\nApp.OnShutdown += (s,e) => cancel.Cancel();\nawait Task.Delay(1000,cancel.Token);	0
3752951	3752305	Declaring Func<in T, out Result> dynamically	linqClass.OrderBy(GetSortExpression(sortstr));\n\n\npublic static Expression<Func<T,object>> GetSortExpression<T>(string sortExpressionStr)\n    {\n        var param = Expression.Parameter(typeof(T), "x");\n        var sortExpression = Expression.Lambda<Func<T, object>>(Expression.Property(param, sortExpressionStr), param);\n        return sortExpression;\n    }	0
672549	672539	How to move data from one listview to another in C#?	ListViewItem itemClone;\nListView.ListViewItemCollection coll = listView1.Items;\nforeach (ListViewItem item in coll)\n{\nitemClone = item.Clone() as ListViewItem;\nlistView1.Items.Remove(item);\nlistView2.Items.Add(itemClone);\n}	0
16182851	16182763	Default Path Of C# Installation	string path = AppDomain.CurrentDomain.BaseDirectory;	0
22233249	22230875	Java XML XPath Parser to C#	XmlTextReader reader = new XmlTextReader(URL);\n\nXPathDocument doc = new XPathDocument(reader);\nXPathNavigator nav = doc.CreateNavigator();\n\nList<string> hourly = new List<string>();\n\nforeach(XPathNavigator node in (XPathNodeIterator) nav.Evaluate("/dwml/data/time-layout[3]/start-valid-time/text()"))\n{\n    hourly.Add(node.Value);\n}	0
19699500	19699318	How do I write this Hex Gradient in Codebehind?	LinearGradientBrush gradient = new LinearGradientBrush();\n    gradient.StartPoint = new Point( 0.5, 0 );\n    gradient.EndPoint = new Point( 0.5, 1 );\n\n    gradient.GradientStops.Add(new GradientStop(Colors.Black, 0));\n    gradient.GradientStops.Add(new GradientStop(Color.FromArgb(100,69,87,186), 1));\n\n\n    whatevercontrolyougot.Fill = gradient;	0
2315682	2308312	C#: How to order arrays in a predefined custom order by only the first 4 digits?	public class Comparer : IComparer<string>\n{\n\n    private Dictionary<string, int> _order;\n\n    public Comparer()\n    {\n        List<string> list = new List<string>()\n        {\n            "CS01",\n            "CS58",\n            "CS11"\n        };\n\n        _order = new Dictionary<string, int>();\n        for (int i = 0; i < list.Count; i++)\n        {\n            _order.Add(list[i], i);\n        }\n    }\n\n    public int Compare(string x, string y)\n    {\n        if (x.Length < 4 || y.Length < 4)\n            return x.CompareTo(y);\n\n        string xPrefix = x.Substring(0, 4);\n        string yPrefix = y.Substring(0, 4);\n\n        int xSequence;\n        int ySequence;\n        if (_order.TryGetValue(xPrefix, out xSequence)\n            && _order.TryGetValue(yPrefix, out ySequence))\n        {\n            return xSequence.CompareTo(ySequence);\n        }\n        else\n        {\n            return x.CompareTo(y);\n        }\n    }\n}	0
5192113	5166546	P4.NET - How to list user's workspaces?	using (var p4 = new P4Connection())\n            {\n                p4.Connect();\n                var longName = WindowsIdentity.GetCurrent().Name;\n                var shortname = longName.Substring(longName.IndexOf("\\") + 1);\n                var records = p4.Run("clients", "-u", shortname);\n\n                cmbBoxPerforceWorkspaceLocation.Items.Clear();\n\n                foreach (P4Record record in records.Records)\n                {\n                    cmbBoxPerforceWorkspaceLocation.Items.Add(record["client"]);\n                }\n            }	0
12249723	9622610	c# split and revers sentence with two languages	var result = Sentence\n   .Split(' ')\n   .Reverse()\n   .Select(w => IsHebrew(w) ? w : new String(w.Reverse().ToArray())\n   .Join(" ")	0
9681547	9669695	Accessing a hyperfileSQL data via #	string connectionString = @"Provider=PCSOFT.HFSQL;Initial Catalog=C:\MyDataFolder";\nstring sql = @"SELECT * FROM MyTable"; //MyTable = The .FIC file\n\nDataTable table = new DataTable();\n\nusing (OleDbConnection connection = new OleDbConnection(connectionString))\n{\n       using (OleDbDataAdapter adapter = new OleDbDataAdapter(sql, connection))\n       {\n              adapter.Fill(table); //Fill the table with the extracted data\n       }\n}\n\ngridControl1.DataSource = table; //Set the DataSource of my grid control	0
11368417	11368370	How to know if MS Windows has alive red or internet connection?	Ping pingSender = new Ping ();\n        PingOptions options = new PingOptions ();\n\n        // Use the default Ttl value which is 128,\n        // but change the fragmentation behavior.\n        options.DontFragment = true;\n\n        // Create a buffer of 32 bytes of data to be transmitted.\n        string data = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";\n        byte[] buffer = Encoding.ASCII.GetBytes (data);\n        int timeout = 120;\n        PingReply reply = pingSender.Send ("www.google.com", timeout, buffer, options);\n        if (reply.Status == IPStatus.Success)\n        {\n            Console.WriteLine ("Address: {0}", reply.Address.ToString ());\n            Console.WriteLine ("RoundTrip time: {0}", reply.RoundtripTime);\n            Console.WriteLine ("Time to live: {0}", reply.Options.Ttl);\n            Console.WriteLine ("Don't fragment: {0}", reply.Options.DontFragment);\n            Console.WriteLine ("Buffer size: {0}", reply.Buffer.Length);\n        }	0
10473101	10473011	Gridview sorting with bound fields	dt.DefaultView.Sort = e.SortExpression + " ASC";\n  gv.DataSource = dt;\n  gv.DataBind();	0
8083254	8083183	C#: finding class fields in a List	int index = myList.FindIndex(x => x.var1 == 20);	0
6407979	6387845	StringBuilder Field in a Structure Cannot Be Marshaled Properly	[DllImport("ftapi.dll", EntryPoint = "ft_showdir", CallingConvention = CallingConvention.Cdecl)]\nprivate static extern Int32 ft_showdir(ref ft_admission admis, ref ft_shwpar par, ref ft_fileinfo[] buf, int bufsize, ref ft_err errorinfo, ref ft_options options);	0
33412001	33403110	How to deserialize this XML document?	public class Data\n{\n    [XmlElement("Hotspot")]\n    public List<Hotspot> Hotspot;\n\n    [XmlIgnore]\n    public Data XmlData;\n\n    public void Deserialize()\n    {\n        XmlSerializer deserializer = new XmlSerializer(typeof(Data));\n        TextReader reader = new StreamReader(@"XMLFile1.xml");\n        object obj = deserializer.Deserialize(reader);\n\n        XmlData = (Data)obj;\n        reader.Close();\n    }\n}\n\npublic class Hotspot\n{\n    [XmlElement("Properties")]\n    public List<Properties> Properties = new List<Properties>();\n}\n\npublic class Properties\n{\n    public float xPos;\n    public float yPos;\n\n    [XmlElement("alpha")]\n    public float alphaValue;\n}	0
1385796	1385382	Implementing IXmlSerializable on a collection object	public void ReadXml(System.Xml.XmlReader reader)\n    {\n        reader.Read();\n        this.C = reader.ReadElementString();\n        this.D = reader.ReadElementString();\n        reader.Read();\n    }	0
1046097	1046056	Having Multiple Outputs for a single action	domain.com/blogs/list/\ndomain.com/blogs/list/xml\ndomain.com/blogs/list/atom	0
9859633	9859554	Grouping the name in the manner of years and months from a list	foreach item in YourList  \n{  \n   print item.dob.year; // this will return year in integer format\n   print item.dob.month; // this will return month in integer format\n   print item.dob; // this will return DoB as dateformat, do whatever formating you want \n   print item.name; // this will return Name as String  \n}	0
4932106	4932068	How to match two array and keep the matched value into a new array using c#?	var matchingValues = arrayA.Intersect(arrayB).ToArray();	0
8414121	8413919	Returning to last ActionResult after HttpPost request	[HttpPost]\npublic ActionResult Foo(string returnUrl)\n{\n    .... do something\n    return Redirect(returnUrl);\n}	0
4788704	4788675	IEqualityComparer string value within object	if (Model.myObjects.Any(o => o.name == "thisobject"))\n{\n}	0
633254	633245	SQL escape with sqlite in C#	SQLiteCommand cmd = _connection.CreateCommand();\ncmd.CommandType = CommandType.Text;\ncmd.CommandText = "SELECT * FROM MyTable WHERE MyColumn = @parameter";\ncmd.Parameters.Add( new SQLiteParameter( "@parameter", textfield ) );\nSQLiteDataReader reader = cmd.ExecuteReader();	0
8559037	8540134	Changing the function of a button click?	Bool bln = true;\n\nprivate void button2_Click(object sender, EventArgs e)\n{\n    if(bln)\n       text1();\n    else\n       text2();\n\n    bln = !bln;\n}\n\nprivate void text1()\n{\n   // Whatever\n}\n\nprivate void text2()\n{\n   // Whatever\n}	0
8275455	8275406	new at lambda as parameters	public MemberViewModel GetSingle( Expression<Func<Member,bool>> whereCondition )\n{\n    var member = this.MemberRepository.GetSingle( whereCondition );\n    if (member != null)\n    {\n        return new MemberViewModel( member );\n       // or however you map from member to its view model\n    }\n    return null;\n}	0
9888141	9887996	How to convert a string to securestring explicitly	var secure = new SecureString();\nforeach (char c in textbox1.Text)\n{\n    secure.AppendChar(c);\n}	0
23359219	23359043	How to get data from database in listbox using List<> in as.net MVC	YourEntity db = new YourEntity();\n\nvar data = (from m in db.Models\n             select m.Name);\n\nList<string> list = data.ToList<string>();	0
29982379	29982022	How to assign roles from helper class,MVC5	public static string smclientadmin \n{ \n  get { return "SMClientAdmin"; } \n}	0
22162864	22162605	How to order list based on another list	public class Foo {\n    public int ID { get; set; }\n    public int? Order { get; set; }\n\n    public Foo(int id, int? order) {\n        ID = id;\n        Order = order;\n    }\n}\n\nstatic void Main(string[] args) {\n\n    var ListT = new List<int> {1090,1089};\n    var ListTOrder = ListT.Select((x, index) => new { Item = x, Index = index }).ToDictionary(x => x.Item, x => x.Index);\n\n    List<Foo> ListB = new List<Foo> {\n        new Foo(1089, 1),\n        new Foo(1089, 3),\n        new Foo(1089, 4),\n        new Foo(1089, null),                \n        new Foo(1090, 1),\n        new Foo(1090, 3),\n        new Foo(1090, 4)\n    };\n\n    ListB = ListB.OrderBy(x => ListTOrder[x.ID]).ThenBy(x => x.Order).ToList();\n}	0
9395574	9395515	How to make the 'Are you sure you want to navigate away from this page' warning message in browser?	function goodbye(e) {\n    if(!e) e = window.event;\n    //e.cancelBubble is supported by IE - this will kill the bubbling process.\n    e.cancelBubble = true;\n    e.returnValue = 'You sure you want to leave?'; //This is displayed on the dialog\n\n    //e.stopPropagation works in Firefox.\n    if (e.stopPropagation) {\n        e.stopPropagation();\n        e.preventDefault();\n    }\n}\nwindow.onbeforeunload=goodbye;	0
29828336	29749190	Unzip file uploaded to Azure Web Apps using C#	public void UploadZipToAzure()
\n        {
\n            byte[] projectFile = File.ReadAllBytes(@"C:\YourZipFile.zip");
\n
\n            String Url = "https://YourAzureWebAppName.scm.azurewebsites.net/api/zip/site/wwwroot/";
\n            WebRequest request = WebRequest.Create(Url);
\n
\n            request.ContentType = "application/x-zip-compressed";
\n            request.Method = "PUT";
\n            //Your Azure FTP deployment credentials here
\n            request.Credentials = new NetworkCredential("UserName - Azure's FTP deployment server name", "Password - Azure's FTP deployment server password");
\n
\n            Stream requestStream = request.GetRequestStream();
\n            requestStream.Write(projectFile, 0, projectFile.Length);
\n            requestStream.Close();
\n
\n            WebResponse response = request.GetResponse();
\n        }	0
29333105	29327856	How to insert data into a mongodb collection using the c# 2.0 driver?	static async void DoSomethingAsync()\n{\n    const string connectionString = "mongodb://localhost:27017";\n\n    // Create a MongoClient object by using the connection string\n    var client = new MongoClient(connectionString);\n\n    //Use the MongoClient to access the server\n    var database = client.GetDatabase("test");\n\n    //get mongodb collection\n    var collection = database.GetCollection<Entity>("entities");\n    await collection.InsertOneAsync(new Entity { Name = "Jack" });\n}	0
22633989	22554649	listbox display manipulation --highlight first 3 items(not selected row)	SqlConnection myConnection = new SqlConnection("Data Source=.;Initial Catalog=db_myDB;Integrated Security=true");\n            SqlDataReader myReader=null;\n\n            int i = 0;\n\n            myConnection.Open();\n\n\n\n             myReader = new SqlCommand("select  countryname from dbo.countries", myConnection).ExecuteReader();\n\n                while (myReader.Read())\n                {\n\n                    ListBoxItem li = new ListBoxItem();\n                    li.Content = myReader.GetString(0);\n                    listBox1.Items.Add(li);\n\n                    if(i<3)\n                    li.Background = Brushes.Blue;\n\n                    i++;\n                }\n\n              myConnection.Close();	0
25860285	25860253	MySQL - Return Incorrect UTF8 characters	charset=utf8	0
17298259	17297987	Null values from Columns	bool threeBool = !string.IsNullOrEmpty(read["Income3"].ToString());\n\n  lblInc3.Visible = threeBool ;\n  txtInc3.Visible = threeBool ;\n  lblInc3.Text = threeBool  ? read["Income3"].ToString() : string.empty;\n\n\n  bool fourBool = !string.IsNullOrEmpty(read["Income4"].ToString());\n\n  lblInc4.Visible = fourBool ;\n  txtInc4.Visible = fourBool ;\n  lblInc4.Text = fourBool ? read["Income4"].ToString() : string.empty;	0
20210096	20209896	how to store the Kannada in SQL Server 2005	CREATE TABLE dbo.nammakannada\n    ( language NVARCHAR(50)\n    , unicodeDa NVARCHAR(200)\n    )\n\n    INSERT INTO dbo.nammakannada (language, unicodeDa)\n    VALUES\n     ('English', N'my example')\n    , ('Kannada', N'? ????? ?????? .')\n\n    SELECT * FROM dbo.nammakannada;\n    GO	0
12245984	12245560	Find index of closing bracket in string list	//Give it index of first bracket you want\n        int myStartingIndex = 0;\n        string s = "[ sfafa sf [fasfasfas ] [ test ] ]";\n        int firstClosedIndex = s.IndexOf("]", myStartingIndex + 1);\n        int firstOpenedIndex = s.IndexOf("[", myStartingIndex + 1);\n        while (firstOpenedIndex < firstClosedIndex)\n        {\n            firstClosedIndex = s.IndexOf("]", firstClosedIndex + 1);\n            firstOpenedIndex = s.IndexOf("[", firstOpenedIndex + 1);\n\n            //Break if there is no any opened bracket\n            //index before closing index\n            if (firstOpenedIndex == -1)\n            {\n                break;\n            }\n        }\n\n        Console.WriteLine("Required index is {0}", firstClosedIndex);	0
21223634	21223495	Maximize windows in every Xth minute	public partial class TimerForm : Form\n{\n    Timer timer = new Timer();\n    Label label = new Label();\n\n    public TimerForm ()\n    {\n        InitializeComponent();\n\n        timer.Tick += new EventHandler(timer_Tick); // Everytime timer ticks, timer_Tick will be called\n        timer.Interval = (1000) * (1);              // Timer will tick evert second\n        timer.Enabled = true;                       // Enable the timer\n        timer.Start();                              // Start the timer\n    }\n\n    void timer_Tick(object sender, EventArgs e)\n    {\n\n          //HERE you check if five minutes have passed or whatever you like!\n\n          //Then you do this on your window.\n          this.WindowState = FormWindowState.Maximized;\n    }\n}	0
10419128	10418949	Casting an interface to another interface that it does not inherit	IFirstInterface first = new InterfaceImplementation();\n\nif( first is ISecondInterface )\n  // typecast since the second interface is legit, then call it's method 2\n  ((ISecondInterface)first).Method2();	0
28465498	28465409	calculate sum of list properties excluding min and max value with linq	list.OrderBy(item => item.Score)\n    .Skip(1)\n    .Reverse()\n    .Skip(1)\n    .Sum(item => item.Score);	0
31103077	31102902	Unit test to check uniqueness of 1 million generated strings	Distinct()	0
7519577	7519544	read exe file as binary file in c#	byte[] buffer = File.ReadAllBytes(@"c:\1.exe");\nstring base64Encoded = Convert.ToBase64String(buffer);\n// TODO: do something with the bas64 encoded string\n\nbuffer = Convert.FromBase64String(base64Encoded);\nFile.WriteAllBytes(@"c:\2.exe", buffer);	0
19939632	19939556	How to to get value of a xml node without the child nodes values appended?	string xml = "<rootNode><node1><node11>v1</node11></node1></rootNode>";\nXDocument xDocument = XDocument.Parse(xml);\nXElement xmlElement = xDocument.Element("node11");\nstring value = xmlElement.Value; // v1	0
1402992	1402984	How can I have many threads that need to know the next ID to process and then increment that number safely?	private static int value;\npublic static int Value\n{\n    get { return Interlocked.Increment(ref value); }\n}	0
16470939	16470916	Installing a windows service without a set up project	installutil.exe	0
18491004	18490599	Parsing Json rest api response in C#	JObject joResponse = JObject.Parse(response);                   \nJObject ojObject = (JObject)joResponse["response"];\nJArray array= (JArray)ojObject ["chats"];\nint id = Convert.ToInt32(array[0].toString());	0
16918863	16917853	How to export listbox items into XML file	XElement element = new XElement("Items");\nforeach (var item in listBox1.Items)\n{\n  element.Add(new XElement("Name", item));\n}\nXDocument document = new XDocument();\ndocument.Add(element);\ndocument.Save("items.xml",SaveOptions.DisableFormatting); //create items.xml file in bin folder	0
32589144	32560463	How to poll webapi request in the background without interrupting user experience?	if (_timer == null)\n    {\n        _timer = new Timer();\n        _timer.Elapsed += _timer_Elapsed;\n        _timer.Interval = (1000 * 60) * 5; // 5 ;\n        _timer.Start();\n    }	0
12779129	12779030	Add row to HTML Table at Run-time in ASP.Net	var row = new HtmlTableRow();\nvar cell = new HtmlTableCell() { InnerText = "Test" };\nrow.Cells.Add(cell);\ntable1.Rows.Add(row);	0
17089429	17089257	How do I replace all strings found with a regular expression with itself concatenated with another string?	var path = @"C:\some\file\path.xml";\nvar result = Regex.Replace(path, @"(C:\\)(.*)", "$1new_root\\$2");	0
25227083	25227056	How can I add an item from a listBox into a textBox	private void listBox1_MouseDoubleClick(object sender, MouseEventArgs e)\n{\n    if(listBox1.SelectedItem != null)\n    {\n        textBox2.Text = listBox1.SelectedItem.ToString();\n    }\n}	0
9941798	9940912	Strange ToolStripButton click to open an OpenFileDialog behavior	private void toolStripButton1_Click(object sender, EventArgs e)\n{\n    toolStripButton1.Enabled = false;\n    openFileDialog1.ShowDialog();\n    toolStripButton1.Enabled = true;\n}	0
32955011	32954421	How to add several OldDbParameters with values to a single OleDbCommand?	FPDBCmd.ConvertNamedParametersToPositionalParameters();\nFPDBCmd.ExecuteNonQuery();	0
15731827	15731789	Save image from the web into my Public/images/items folder?	Server.MapPath(@"\Public\images\items\" + item.Name + ".png")	0
3415964	3415878	Adding variable to string in ASP.net	SqlCommand cmd = new SqlCommand("SELECT COUNT(*) FROM tblUsers WHERE username = @user");\ncmd.Parameters.AddWithValue("@user",  username);	0
13523960	13523934	C#: Interface implementation	var order = (IOrder)order;\norder.GetExistingOrder();	0
8198231	8198081	Query tabels to sort sums across rows and count based on a value in LINQ	group by user.UserID\nselect new\n{\n   User = user.UserID\n   TotGradeCount = workRew.Grade.Sum()\n   Graders = workRew.Grade.Count()\n}	0
8292590	8291986	How to skip some column while exporting Grid view in excel?	//  add the header row to the table\n            if (gv.HeaderRow != null)\n            {\n                TableRow tr = new TableRow();\n\n                foreach (DataControlFieldHeaderCell c in gv.HeaderRow.Cells)\n                {\n                    if (c.Text != "&nbsp;") {\n                        tr.Cells.Add(new TableCell() { Text = c.Text});\n                    }\n                }\n\n                PrepareControlForExport(tr);\n                table.Rows.Add(tr);\n            }	0
3600742	3600091	How to pass XML from C# to a stored procedure in SQL Server 2008?	declare @MyXML xml\n\nset @MyXML = '<booksdetail> \n                  <isbn_13>700001048</isbn_13> \n                  <isbn_10>01048B</isbn_10> \n                  <Image_URL>http://www.landt.com/Books/large/00/70100048.jpg</Image_URL> \n                  <title>QUICK AND FLUPKE</title> \n                  <Description> PRANKS AND JOKES QUICK AND FLUPKE - CATASTROPHE QUICK AND FLUPKE </Description> \n              </booksdetail>'\n\nselect Book.detail.value('(isbn_13/text())[1]','varchar(100)') as isbn_13, \n       Book.detail.value('(isbn_10/text())[1]','varchar(100)') as isbn_10, \n       Book.detail.value('(Image_URL/text())[1]','varchar(100)') as Image_URL, \n       Book.detail.value('(title/text())[1]','varchar(100)') as title, \n       Book.detail.value('(Description/text())[1]','varchar(100)') as Description\n    from @MyXML.nodes('/booksdetail') as Book(detail)	0
19337407	19337171	Change label color based on user input	protected void Button1_Click(object sender, EventArgs e)\n    {\n        if (Int32.Parse(txttemp.Text.Trim()) >= 15)\n        {\n            lblans.Text = "Hot";\n            lblans.ForeColor = System.Drawing.Color.Red;\n        } \n        else \n        {\n            lblans.Text = "Cold";\n            lblans.ForeColor = System.Drawing.Color.Blue;\n        }\n    }	0
27637720	27637647	Return an object built from various models, web api, EntityFramework 6	public IEnumerable<TraqIndexDTO> GetTraqIndex()\n{\n    var traqIndex = db.Brand.ToList().Select(b => new TraqIndexDTO()\n                    {\n                        BrandName = b.BrandName,\n                        CategoryScores = getCatgoryScoresByBrandId(b.BrandId).ToList()\n                    }).ToList();\n\n    return traqIndex;\n}	0
11634355	11633709	Capturing IP address of web stream with StreamReader returning too much data	public static String GetIP()\n{\n    String ip = \n        HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];\n\n    if (string.IsNullOrEmpty(ip))\n    {\n        ip = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];\n    }\n\n    return ip;\n}	0
21773927	19834379	How to Check the CheckEdit from Access Database?	Gender.Checked = reader.GetBoolean(1);	0
24470179	24470139	Create a 6 digit sequence number in c#	yourNumber.ToString("D6")	0
1904917	1904905	splitting sentences using regex	using System.Text.RegularExpressions;\nstring[] parts = Regex.Split(mytext, "\.\n|\. "); \n# or "\.\s" if you're not picky about it matching tabs, etc.	0
2761695	2761667	Livevalidation clientside validation - can you control the position of the validation messages?	span .LV_validation_message {\n    // properties\n}	0
4676448	4676430	Radio Buttons in ASP.NET	protected void rbList_SelectedIndexChanged(object sender, EventArgs e)\n{\n    if (rbList.Items[0].Selected)\n    {\n        lblHeader.Text = "You selected first option";\n    }\n}	0
26066380	26066328	c# TrimEnd -1 removes last character plus preceding characters if they are repeating	str.Substring(0, str.Length - 1);	0
33259265	33258399	Code Optimization: Create a method for recurring procedures	private void listViewItem_Group_Selected(object sender, RoutedEventArgs e)\n        {\n            ListViewItem lv = sender as ListViewItem;\n            DockPanel dockpanel = (lv.Content) as DockPanel;\n            Label label = (dockpanel.Children[1]) as Label;\n            label_Position.Content = label.Content.ToString();\n            SetDataGridItems(label.Content.ToString());\n\n        }	0
28469013	28468989	How to hide GridView Coumn[1]?	protected void GridView_RowDataBound(object sender, GridViewRowEventArgs e)\n{\n    e.Row.Cells[1].Visible = false;\n}	0
13525059	13525016	Assigning the whole array values to another variable in c#?	for (int i = 0; i < length; i++)\n{\n    arr1[i] = Convert.ToByte(Tag_uid.Substring(2 * i, 2), 16);\n}\n\nbyte[][] CommandPacket = new byte[9][];\n\nCommandPacket[0] = arr1;	0
19861264	19860914	Dynamic Methods with Expression Trees: Simple property assignment fails	var block = Expression.Block(\n               Expression.Assign(\n                   Expression.Property(personParam, "Name"),\n                   Expression.Constant("Joe Bloggs")));	0
25489817	25489767	How to insert a new item into IEnumerable<class>	private static nameSpace.BigClass.Class1 Request(JObject request)\n{\n  nameSpace.BigClass.Class1 bigRequest = new BigClass.Class1();\n  var internalList = new List<BigClass.Class1.SegmentClass1>();\n  internalList.Add(new SegmentClass1\n        {\n            attrib1 = request.GetValue("attrib1").Value<DateTime>(),\n            attrib2 = request.GetValue("attrib2").Value<string>(),\n            attrib3 = request.GetValue("attrib3").Value<string>()\n        });\n  bigRequest.Segments = internalList;\n  return bigRequest\n}	0
28791742	28791690	How to show the values of each controls when I return to the page?	string firstName = "Jeff";\nstring lastName = "Smith";\nstring city = "Seattle";\nSession["FirstName"] = firstName;\nSession["LastName"] = lastName;\nSession["City"] = city;	0
25653314	25652977	How to validate a date of birth with a date of deceased textboxes using Jquery.ui.datepicker.css	DateTime dob=DateTime.Parse(txtDOB.Text); //consider using an overloaded method to account for different date formats.\nDateTime dod=DateTime.Parse(txtDOD.Text); //consider using an overloaded method to account for different date formats.\nif(dob>dod)\n{\n    //provide error message to the client\n}	0
6663151	6663056	Index of Child XElement	e.ElementsBeforeSelf().Count()	0
16099312	16099024	Inputting a text file, adding text to each line, writing to a new file C#	Console.WriteLine("Please enter the path to the input file:");\nstring inp = Console.ReadLine();\nConsole.WriteLine("Please enter the name of the new file:");\nstring otp = Console.ReadLine();\n\nSystem.Text.StringBuilder sb = new System.Text.StringBuilder();\nstring inputLines = System.IO.File.ReadAllLines(inp);\n for (int i = 0; i < inputLines.Length; i++)\n     sb.Append("Some Text" + inputLines[i] + Environment.NewLine);\n\nFile.WriteAllText(otp, sb.ToString())	0
17667035	17666924	Combining Properties	FirstName = reader.GetString(reader.GetOrdinal("FirstName")));  \nLastName = reader.GetString(reader.GetOrdinal("LastName")));	0
3227821	3177753	Partially protected interface but without abstract class	public class MyRootClass : IOne, ITwo\n{\n    private IInterfaceToImplement internalData = new MyConcreteClass();\n\n    public int FunctionOne() { return this.internalData.FunctionOne(); }\n\n    public double FunctionTwo() { return this.internalData.FunctionTwo(); }\n}	0
2638962	2637711	Moq, a translator and an expression	mockGet.Setup(mock => mock.Get(It.IsAny<Expression<Func<TEnterpriseObject, bool>>>())).Returns(\n            (Expression<Func<TEnterpriseObject, bool>> expression) =>\n                {\n                    var items = new List<TEnterpriseObject>();\n                    var translator =\n                        (IEntityTranslator<TEntity, TEnterpriseObject>)\n                        ObjectFactory.GetInstance(typeof (IEntityTranslator<TEntity, TEnterpriseObject>));\n                    fakeList.ForEach(fake => items.Add(translator.ToEnterpriseObject(fake)));\n                    var filtered = items.AsQueryable().Where(expression);\n                    var results = new List<TEntity>();\n                    filtered.ToList().ForEach(item => results.Add(translator.ToEntity(item)));\n                    return results.AsQueryable();\n                });	0
29775885	29775506	How get type of property in CodeProperty ? T4	CodeTypeRef codeTypeRef = property.Type;\ncodeTypeRef.AsString // here we get type of property	0
28960826	28185796	forcing to ignore some url parameters	//by specifying a messageName, you can do overloading with webmethods\n[WebMethod (MessageName = "listOfStudentsDefault")]  \n[ScriptMethod(UseHttpGet=true)]\npublic string listOfStudents(int class, string appLang)\n{\n    // code here...\n}\n\n[WebMethod (MessageName = "listOfStudents")]  \n[ScriptMethod(UseHttpGet=true)]\npublic string listOfStudents(int class)\n{\n    return listOfStudents(class, "ar");\n}	0
1556977	1556952	C# - Returning an Enum? from a static extension method	public static T? ToEnumSafe<T>(this string s) where T : struct\n{\n    return (IsEnum<T>(s) ? (T?)Enum.Parse(typeof(T), s) : null);\n}	0
31065691	31043444	Entity Framework many to many duplicate value in join table when updating entity	model.ExecuteSqlCommand("DELETE FROM SlaveMasters WHERE Master_Id = " + Id);\nSlaves = new EntityHashSet<Slave>(slaves.Select(s => model.Slaves.CreateOrFind(s)));	0
4915280	4915172	How-To MultiTarget Both SilverLight 4 and WPF Application?	#if SILVERLIGHT	0
3769828	3769770	Clear Console Buffer	while(Console.KeyAvailable) \n{\n    Console.ReadKey(false);\n}\nConsole.ReadKey();	0
19034307	19033403	javaScript with ASP	string str = "function counter() { \n    var q = Number(document.getElementById(\"TextBox1\").value); \n    var i = Number(document.getElementById(\"Text1\").innerHTML); \n    if (i < q) { i += 1; document.getElementById(\"Text1\").innerHTML = i; \n    setTimeout(function(){counter();}, 10);  } }";\nClientScript.RegisterClientScriptBlock(this.GetType(), "counter", str, true);\nButton1.Attributes.Add("onclick", "counter(); return false;");	0
2961887	2959485	Recursion in Unity and Dispose pattern implementation	protected override void Dispose(bool disposing)\n    {\n        if (_bDisposed)\n            return;\n\n        if ( disposing )\n        {\n            _context.Dispose();\n        }\n        _bDisposed = true;\n\n        base.Dispose(disposing);\n    }\n\n    private bool _bDisposed;	0
15963266	15962823	Print a XPS file from a byte stream	// Create the printer server and print queue objects\nLocalPrintServer localPrintServer = new LocalPrintServer();\nPrintQueue defaultPrintQueue = LocalPrintServer.GetDefaultPrintQueue();\n\n// Call AddJob\nPrintSystemJobInfo myPrintJob = defaultPrintQueue.AddJob();\n\n// Write a Byte buffer to the JobStream and close the stream\nStream myStream = myPrintJob.JobStream;\nByte[] myByteBuffer = UnicodeEncoding.Unicode.GetBytes("This is a test string for the print job stream.");\nmyStream.Write(myByteBuffer, 0, myByteBuffer.Length);\nmyStream.Close();	0
11514983	11463648	Saving data to database using linq	private void btnCreate_Click(object sender, EventArgs e)\n    {\n        using (testEntities Setupctx = new testEntities())\n        {\n            string[] stations = StationNameList();\n            station creStation = new station();\n            creStation.Station1 = txtStation.Text;\n            creStation.Seats = cbSeats.SelectedItem.ToString();\n            if (stations.Contains(txtStation.Text))\n            {\n                MessageBox.Show("This Station is already been created. Please enter a new Station.");\n            }\n            else\n            {\n                Setupctx.stations.AddObject(creStation);\n                Setupctx.SaveChanges();\n                txtStation.Text = "";\n                cbSeats.SelectedIndex = -1;\n                MessageBox.Show("New Station Has Been Created.");\n            }\n        }\n    }	0
13158554	13158467	How to convert a string variable to a char variable with a strict length?	var result = new string('a',30).ToCharArray();	0
640323	640307	How can you throttle a long-running command-line EXE to avoid pegging the CPU?	Thread.Priority	0
1283020	1283008	ASP.NET Profiles - Add a profile to an existing user	var profile = ProfileBase.Create(username);\nprofile.SetPropertyValue("MyGuid", aGuid);\nprofile.SetPropertyValue("MyString", aString);\n// etc\nprofile.Save()	0
12149559	12148918	Is Converting a Path To A Shape Possible?	Path path = (Path)x;\nGeometry geometry = path.Data;\nif (geometry is EllipseGeometry)\n{\n    ...\n}\nelse if (geometry is LineGeometry)\n{\n    ...\n}\n...	0
16272903	16272085	Displaying Date in Windows Store apps regarding Language	CultureInfo.CurrentCulture.DateTimeFormat.GetDayName(loadedDate.DayOfWeek)	0
4231113	4231091	Linq to XML: Returning attributes from Children of the same name and Parents of the same name	var rowNames = from i in xmlDoc.Descendants("rowSet")\n               where (string)i.Attribute("name") == "name"\n               from r in i.Descendants("row")\n               select (string)r.Attribute("name");	0
3441962	3441944	Literal character in C#	string[] parts = line.Split("....", 2, StringSplitOptions.None);	0
32137689	32135888	How to unsubscribe from a loaded event in a derived control?	public class MyFormGrid : Grid\n{\n    ...\n    public MyFormGrid()\n    {\n        Loaded += MyGrid_Loaded;\n    }\n    ...\n    private void MyGrid_Loaded(object sender, RoutedEventArgs e)\n    {\n        Loaded -= MyGrid_Loaded;\n        ...\n    }\n}	0
19624501	18826447	How to determine if printer is xps ? c#	Microsoft XPS Document Writer	0
20419296	20419164	Regular Expression to devide string to many strings with special delimiter	string input = "Hello ,[1]Please Help[1]me resolving this[1]regex issue[1], Thank You.";\nvar parts = Regex.Matches(input, @"(.+?)(\[1\]|$)").Cast<Match>()\n            .Select(m => m.Groups[1])\n            .Select(m => new { m.Index, m.Length, m.Value })\n            .ToList();	0
30459325	30459162	How to send parameter to a function in Master.cs from a content page	public string sortOrder\n{\n      get\n      {\n           if (!string.IsNullOrEmpty(Convert.ToString(ViewState["sortOrder"])) && Convert.ToString(ViewState["sortOrder"]) == "Desc")\n           {\n                ViewState["sortOrder"] = "Asc";\n           }\n           else\n           {\n                ViewState["sortOrder"] = "Desc";\n           }\n\n           return Convert.ToString(ViewState["sortOrder"]);\n      }\n      set\n      {\n           ViewState["sortOrder"] = value;\n      }\n}	0
16529945	16529659	Finding and Filtering XML Data	XDocument X = XDocument.Load(@"XMLFileLocation");\nvar CDsIn1985 = X.Element("CATALOG").Elements("CD").Where(E => E.Element("YEAR").Value == "1985");\n\nforeach (var item in CDsIn1985)\n{\n     Console.WriteLine(String.Format("Title : {0}, Artist : {1}", item.Element("TITLE").Value, item.Element("ARTIST").Value));\n}	0
8661126	8661084	add picturebox in windowsform c#	PictureBox pic = new Picturebox();\nthis.Controls.Add(pic);	0
4554725	4554224	Setting string values to Viso shapedata	propCell.FormulaForceU = "\"asd\"";	0
18216837	18216775	How can I change an 2D array to a 2D list and then back to a 2D array again?	List<List<int>> lists = arrays.Select(inner=>inner.ToList()).ToList();\n\nint[][] arrays = lists.Select(inner=>inner.ToArray()).ToArray();	0
8909689	8876112	Using WeakEventManager with a static event	void OnCompositionTargetRendering(object sender, EventArgs e)\n{\n    this.DeliverEvent(null, e);\n}	0
27444186	27444151	how to get two (or more) controls to share the same event handler	DoSomething()	0
20948628	20946436	Register your app as Photo Editor	Rich Media Extensibility	0
2165749	2165229	A confusion about value types	struct S { \n    public int x; \n    public override string ToString() { return "Hello!" + x; } \n}\n...\nS s = new S();\ns.x = 0x00112233;\ns.ToString();	0
13165824	13165769	Take a range of values from collection	var result = fields.SkipWhile(s => !s.Contains("TableStart"))\n                   .Skip(1)\n                   .TakeWhile(s => !s.Contains("TableEnd"))\n                   .ToList();	0
26014258	26014230	Get XML attribute Values by its Descendants	XNamespace ns = "http://www.w3.org/2001/XMLSchema-instance";\nvar query = from c in xmlFile.Descendants(ns + "LineStatus") select c;	0
16020124	16019933	C# match substring with optional parameters	"01\\+\\s*(?<1>[.0-9A-Za-z]*)\\s*02\\+\\s*(?<2>[.0-9]*)(\\s*03\\+\\s*(?<3>[.0-9]*)\\s*)?"\n                                                       ^                              ^^	0
10899398	10898957	Chrome shows comma instead of decimal point	protected override void InitializeCulture()\n{\n    this.Culture = "en-US";\n    this.UICulture = "en-US";\n    base.InitializeCulture();\n}	0
29880609	29873152	Unity Game Engine Crashing When Trying To Update The Vertex Positions Of A Mesh In Real Time Using A Script	for (float i = 0f; i<1f; i=+0.05f) {	0
1770814	1770747	C# Define begin of day of a date in another timezone	var zone = TimeZoneInfo.GetSystemTimeZones().First(tz => tz.StandardName == DesiredTimeZoneName);\nDebug.WriteLine(new DateTimeOffset(DateTime.UtcNow.Date.Ticks, zone.BaseUtcOffset).ToUniversalTime());	0
4709039	4708998	How to write a Lucene.Net RAMDirectory back to disk?	public static void Copy(Lucene.Net.Store.Directory src, Lucene.Net.Store.Directory dest, bool closeDirSrc)	0
21420239	21419626	Fail to build Azure Cloud Service	Microsoft.WindowsAzure.Plugins.Connect.Refresh.*	0
1565699	1558323	Background color for Tabcontrol in c# windows application	TaskBarRef.tabControl1.TabPages[e.Index].BackColor = BackBrush.Color;	0
6434987	6434787	Sort by $natural in MongoDB with the official c# driver	collection.Insert(new BsonDocument("x", 1));\ncollection.Insert(new BsonDocument("x", 2));\ncollection.Insert(new BsonDocument("x", 3));\n\nforeach (var document in collection.FindAll()\n    .SetSortOrder(SortBy.Descending("$natural"))) \n{\n    Console.WriteLine(document.ToJson());\n}	0
11471759	11471267	variable name with a white space	AutoGenerateColumns="True"	0
25580167	25580137	Get content of Current Button	private void Button_Click(object sender, RoutedEventArgs e)\n{\n    Button obj = (Button)sender;\n    MessageBox.Show(obj.Content.ToString());\n}	0
23829951	23829331	Performing code in background without UI in windows phone 8 (via custom URI)	OnNavigatedTo(NavigationEventArgs e)	0
14110246	14110212	Reading specific XML elements from XML file	var xmlStr = File.ReadAllText("fileName.xml");\n\n\n    var str = XElement.Parse(xmlStr);\n\n    var result = str.Elements("word").\nWhere(x => x.Element("category").Value.Equals("verb")).ToList();\n\n    Console.WriteLine(result);	0
17735282	17735211	Is there a Lambda Else condition?	foreach (Shape shape in shapefile.Where(x=>IgnoreField==null || IngoreValue==null || x.GetMetadata(IgnoreField) != IgnoreValue))	0
17748665	17748344	Unit Testing Timed Removal of Dictionary Value	[Test]\nvoid Should_remove_...()\n{\n    MockTimer timer = new MockTimer();    \n\n    MyCache cache = new MyCache(timer);\n    DateTime expiredAt = DateTime.Now.Add(..);\n    cache.Add("key", "value", expiredAt);\n\n    timer.SetTime(expiredAt);\n\n    Assert.That(cache, Is.Empty)\n}	0
18553018	18552966	Infinite loop that will run based on a time	private void InitLoop(bool runLoop)\n{\n    try\n    {\n        myTimer.Elapsed += myTimer_Elapsed;\n        myTimer.Interval = 2000;\n        myTimer.Enabled = true;\n        myTimer.Start();\n    }\n    catch (Exception f)\n    {\n        //handle the exception \n    }\n}	0
13620323	13620153	filter XML elements and edit their values, ASP.NET	int id = 2;\nXDocument xdoc = XDocument.Load(filepath);\nXElement student = xdoc.Descendants("student")\n        .Where(s => (int)s.Element("id") == id)\n        .SingleOrDefault();\n\nif (student == null)\n{\n    student = new XElement("student",\n                        new XElement("id", id),\n                        new XElement("first_name"),\n                        new XElement("last_name")); // add other elements here\n    xdoc.Root.Add(student);\n}\n\nstudent.Element("first_name").Value = TextBox_firstname.Text;\nstudent.Element("last_name").Value = TextBox_lastname.Text;\n// set other values here          \n\nxdoc.Save(filepath);	0
19477489	19476343	WPF: Binging TextBox + Datagrid	private string _translation;\npublic string Translation \n{ \n     get\n     {\n          return _translation;\n     } \n     set\n     {\n         _translation = value;\n        RaisePropertyChanged("Translation");\n     }\n\n}	0
14519533	14394310	Generate a test XML from XML Schema programmatically	public static void Main(string[] args)\n        {\n            using (var stream = new MemoryStream(File.ReadAllBytes("schema.xsd")))\n            {\n                var schema = XmlSchema.Read(XmlReader.Create(stream ), null);\n                var gen = new XmlSampleGenerator(schema, new XmlQualifiedName("rootElement"));\n                gen.WriteXml(XmlWriter.Create(@"c:\temp\autogen.xml"));\n                Console.WriteLine("Autogenerated file is here : c:\temp\autogen.xml");\n            }            \n        }	0
13114670	13114616	provide a non-trivial setter for an interface property, but not a getter	// Player.cs\n\nprivate Color _colorPainted;\n\npublic class Player : Monobehaviour, IColor {\n    // ...\n    public Color colorPainted {\n        get { return _colorPainted; }\n        set {\n            _colorPainted = value;\n            // some other code\n        }\n     // ...\n    }\n}	0
7899920	7899835	C#: recursive search in two different data structures	//pseudocode\n\n    String name;\n    bool condition = true;\n\n    while(condition)\n    {\n        if(ExistInFirstDataStructure(name))\n        {\n           //increment name\n        }\n        else\n        {\n           if(ExistInDeletedDataStructure(String name))\n           {\n               //increment name\n           }\n           else\n           {\n               condition = false;\n           }\n\n        }\n    }\n\n\n    bool ExistInFirstDataStructure(String name)\n    {\n\n    }\n\n    bool ExistInDeletedDataStructure(String name)\n    {\n\n    }	0
6175892	6174975	how to check whether gridview's row is selected or not in c#.net windows application	private void dataGridView_SelectionChanged(object sender, EventArgs e)\n{\n    // Update the text of TextBox controls.\n    textBox1.Text = dataGridView.SelectedRows[0].Cells[1].Value.ToString();\n    textBox2.Text = dataGridView.SelectedRows[0].Cells[2].Value.ToString();\n    ....\n}	0
4235942	4235924	How to handle a syntax error in an Access INSERT statement and a .NET DataGridView control?	using (var conn = new OleDbConnection(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=mydatabase.accdb"))\nusing (var command = new OleDbCommand(@"INSERT INTO IndicadorProyecto (idProyecto, idMes, meta, real) VALUES(?, ?, ?, ?") {\n    command.Parameters.AddWithValue("a", idProyecto);\n    command.Parameters.AddWithValue("b", idMes);\n    command.Parameters.AddWithValue("c", meta);\n    command.Parameters.AddWithValue("d", real);\n\n    conn.Open();\n    command.ExecuteNonQuery();\n}	0
28052985	28051670	How to rename dynamically file name	// Get files\n            DirectoryInfo di = new DirectoryInfo (@"c:\my\path");\n            var files = di.GetFiles();\n\n            // Loop through files\n            foreach (var file in files) \n            {\n                // Read file\n                string content = File.ReadAllText (file.FullName);\n\n                // Split text (add as many separators as you want, I'm using\n                // whitespace just like in your example)\n                string[] numbers = content.Split (' ');\n\n                // First number is numbers[0]\n                // Last number is numbers[numbers.Length - 1]\n\n                // Rename file\n                File.Move(file.FullName, string.Format("Nr{0}-{1}.txt", numbers[0], numbers[numbers.Length - 1]));\n            }	0
5811181	5803974	How to test a WCF Webservice with JMeter?	Steps:\n1. Import WSDL into soap\n2. Create a default request for the method\n3. Set the request view to RAW, and copy into JMeter	0
11578658	11577618	How to remove textblock dynamically in wpf	public partial class Window2 : Window\n{\n    int margin = 200;\n    TextBlock DynamicLine;\n    public Window2()\n    {\n        this.InitializeComponent();\n\n        for (int i = 1; i <= 5; i++)\n        {\n            DynamicLine = new TextBlock();\n            DynamicLine.Name = "lbl_DynamicLine" + i;\n            RegisterName(DynamicLine.Name, DynamicLine);\n            DynamicLine.Width = 600;\n            DynamicLine.Height = 20;\n            DynamicLine.Text =i+"Dynamic TextBlock";\n            DynamicLine.Margin = new Thickness(50, margin, 0, 0);\n            margin = margin + 20;\n\n            LayoutRoot.Children.Add(DynamicLine);             \n\n        }\n\n        for (int i = 1; i <= 5; i++)\n        {\n            DynamicLine = (TextBlock)this.FindName("lbl_DynamicLine" + i);\n            LayoutRoot.Children.Remove(DynamicLine);\n        }\n\n    }\n}	0
6058015	6057906	How to throw an exception during debugging session in VS2010	Debug.Assert(false);	0
16033517	16033291	Building SQL IN statement from listbox control	string InPartQuery = string.Join(",", lstSalesGroup.Items\n                                          .Cast<ListItem>()\n                                          .Where(t => t.Selected)\n                                          .Select(r => "'" + r.Value + "'"));	0
18837917	18837391	Parse XML File for a number and display in textbox	var dict = XDocument.Load(fname)\n            .Descendants("field")\n            .ToDictionary(f => f.Attribute("name").Value, \n                          f => f.Attribute("value").Value);\n\nfirstNumberTextBox.Text = dict["first_number"];\nsecondNumberTextBox.Text = dict["second_number"];	0
31299422	31298500	Select row in asp.net	GridViewRow row = GridView1.Rows[previouslySavedIndex];	0
10228197	10228117	Order 1,2,10,11 instead 1,10,11,2	string[] files = {\n  "2.html",\n  "10.html",\n  "1.html"\n};\n\nfiles =\n  files.OrderBy(s => Int32.Parse(s.Substring(0, s.IndexOf('.'))))\n  .ToArray();	0
14794198	14794188	How can I create anonymous method in a lambda expression using C# like I can in VB.NET?	myArray.Select(a => {\n    ...\n});	0
7051109	7040130	How to obtain the ListItem inside a CheckBoxList which triggered the postback?	var selectedItem = CheckBoxList1.SelectedItem;	0
15335808	15291235	Enterprise Library Validation Ruleset issue for nested objects	public class Person\n{\n    [ObjectValidator]\n    [ObjectValidator("A", Ruleset = "A")]\n    public Address Address  { get; set; }\n}\n\npublic class Address  \n{\n    [StringLengthValidator(0, 32, MessageTemplate = "Invalid value '{0}' for {1}, Max length:{5}")]\n    public string Address1 { get; set; }\n\n    [StringLengthValidator(0, 32, MessageTemplate = "Invalid value '{0}' for {1}, Max length:{5}", Ruleset = "A")]\n    public string Address2 { get; set; }\n}	0
32851053	32850855	Parse a malformed HTML with HtmlAgilityPack	var web = new HtmlAgilityPack.HtmlWeb();\nvar doc = web.Load("http://anossaoficina.com/index.php?option=com_content&view=category&layout=blog&id=78&Itemid=474");\n\nvar DescritionShort = doc.DocumentNode\n                      .SelectSingleNode("//div[@class='item column-1']//p[2]")\n                      .NextSibling.InnerText;	0
5801812	5801667	Use of pointer like structure in C#	public class ReferenceString\n{\n    public String Value { get; set; }\n}	0
4740851	4740752	How do I log into a site with WebClient?	private class CookieAwareWebClient : WebClient\n{\n    public CookieAwareWebClient()\n        : this(new CookieContainer())\n    { }\n    public CookieAwareWebClient(CookieContainer c)\n    {\n        this.CookieContainer = c;\n    }\n    public CookieContainer CookieContainer { get; set; }\n\n    protected override WebRequest GetWebRequest(Uri address)\n    {\n        WebRequest request = base.GetWebRequest(address);\n\n        var castRequest = request as HttpWebRequest;\n        if (castRequest != null)\n        {\n            castRequest.CookieContainer = this.CookieContainer;\n        }\n\n        return request;\n    }\n}	0
28872206	28871890	How to get callbackurl from twilio API against a twilio number	var result = client.GetIncomingPhoneNumber("PHxxxxxxxxxxxxxxxxxxxxxxx");\nif (result.RestException == null)\n{\n    Console.WriteLine(result.VoiceUrl);\n    Console.WriteLine(result.SmsUrl);\n    Console.WriteLine(result.StatusCallback);\n}	0
3310026	1847972	How can I detect the Flowdirection RightToLeft or LeftToRight automatically in WPF	public bool IsArabic(string strCompare)\n{\n  char[] chars = strCompare.ToCharArray();\n  foreach (char ch in chars)\n    if (ch >= '\u0627' && ch <= '\u0649') return true;\n  return false;\n}	0
11350960	11350542	traversing relation to relation in odata	var q = from cpuid in Computers\n     where cpuid.DnsHostName == "xyz"\n     select new {\n         ITManagers = cpuid.TechnicalProductsHosted\n             .Select (x => x.ResponsibleUser.Manager.Name)\n     };	0
15770846	15769189	Make an Async/Await db call within a Task?	public bool ProcessMessage(string message)\n{\n  var returnValue = GetReturnValue();\n\n  Task.Run(async () => {\n    //do some things with the message\n    await UpdateDatabaseAsync();\n    await SendRepliesOverNetworkAsync();\n  });\n\n  return returnValue;\n}	0
9677561	9663278	Faster Method to Making DataGridViewRow's non-Visible	DataSet ds = new DataSet();\nds.Tables[0].DefaultView.RowFilter = "YourBooleanColumn = 1";\n\nDataView dv = new DataView();\ndv.RowFilter = "YourBooleanColumn = 1";\n\nDataTable dt = new DataTable();\ndt.RowFilter.DefaultView.RowFilter = "YourBooleanColumn = 1";	0
15348937	15333893	Failed to read nested customized Listbox value in Datagrid WPF	for (int i=0;i<dataGrid1.Items.Count;i++) \n{\n\n    // get control which represents the data\n    var control = dataGrid1.ItemContainerGenerator.ContainerFromItem(dataGrid1.Items[i]);\n    DependencyObject obj = control\n\n    // inside that control there is somewhere the ListBox so run down the visualtree till you find the damn ListBox\n    for(;!(obj is ListBox);\n        obj = VisualTreeHelper.GetChild(obj, 0));\n\n    ListBox listBox = obj as ListBox;\n    if(listBox != null)\n    {\n      // get the selected values from ListBox\n      var selectedItems = listBox.SelectedItems;\n      foreach(var selectedItem in selecteditems)\n      {\n         Console.WriteLine("I am a selected item: " + selectedItem.ToString());\n      }\n    } \n}	0
4454996	4439010	How to get the difference between 2 int arrays as a percentage	for(int i=0;i<arr1.length;i++)\n{\n  if(arr1[i] == arr2[i])\n  count++;\n}\ndouble percentage = (float)count / (float)arr1.length * 100;	0
1086169	1086154	Best way to break a string on the last dot on C#	string s = "a.b.c.d";\n    int i = s.LastIndexOf('.');\n    string lhs = i < 0 ? s : s.Substring(0,i),\n        rhs = i < 0 ? "" : s.Substring(i+1);	0
31251164	31249918	C# Using .Contains on a RadComboboxItem searching for a string	protected void rcbProgram_SelectedIndexChanged(object sender, RadComboBoxSelectedIndexChangedEventArgs e)\n    {\n        **List<String> _selectedItems = new List<String>();\n        foreach (RadComboBoxItem i in rcbProgram.CheckedItems)\n        {\n            _selectedItems.Add(i.Value);\n        }**\n\n\n        rcbPartGroup.DataSource = db.tblPartStyles.Where(c=>_selectedItems.Contains(c.Program)).Select(c => c.PartGroup).Distinct();\n        rcbPartGroup.DataBind();\n\n    }	0
21299060	21275423	How To make a Layer Only select able In ArcMap through API	private void MakeOnlySelectableLayer(IFeatureLayer stationFeatureLayer)\n{\n    var Focusmap = ArcMap.Document.FocusMap;\n\n    for (int i = 0; i < Focusmap.LayerCount; i++)\n    {\n        if (Focusmap.get_Layer(i) is IFeatureLayer)\n        {\n            IFeatureLayer layer = (IFeatureLayer)Focusmap.get_Layer(i);\n            if (stationFeatureLayer != null && !stationFeatureLayer.Equals(layer))\n            {\n              layer.Selectable = false;\n            }\n\n\n        }\n     }\n }	0
26306706	26305973	How to return the derived type from base method	class Program\n{\n    static void Main(string[] args)\n    {\n        Dog dog = new Dog().Color("Red").Paw(4);\n        Bird bird = new Bird().Color("Blue").Wing(1);\n    }\n}\n\npublic abstract class Animal\n{\n    private string color = "";\n    public Animal Color(string _color)\n    {\n        color = _color;\n        return this;\n    }\n}\n\npublic abstract class ChainingAnimal<T> : Animal\n    where T : Animal\n{\n    public T Color(string _color)\n    {\n        return (T)base.Color(_color);\n    }\n}\n\npublic class Dog : ChainingAnimal<Dog>\n{\n    private int pawNumber = 0;\n    public Dog Paw(int _pawNumber)\n    {\n        pawNumber = _pawNumber;\n        return this;\n    }\n}\n\npublic class Bird : ChainingAnimal<Bird>\n{\n    private int wingNumber = 0;\n    public Bird Wing(int _wingNumber)\n    {\n        wingNumber = _wingNumber;\n        return this;\n    }\n}	0
7418367	7418340	Regex to search and replace a character in a string C#	var result = str.Replace(",", string.Empty);	0
10203030	10202987	In C# how to collect stack trace of program crash	[STAThread]\n    static void Main()\n    {\n    AppDomain currentDomain = default(AppDomain);\n    currentDomain = AppDomain.CurrentDomain;\n    // Handler for unhandled exceptions.\n    currentDomain.UnhandledException += GlobalUnhandledExceptionHandler;\n    // Handler for exceptions in threads behind forms.\n    System.Windows.Forms.Application.ThreadException += GlobalThreadExceptionHandler;\n    ...\n    }\n\nprivate static void GlobalUnhandledExceptionHandler(object sender, UnhandledExceptionEventArgs e)\n{\n   Exception ex = default(Exception);\n   ex = (Exception)e.ExceptionObject;\n   ILog log = LogManager.GetLogger(typeof(Program));\n   log.Error(ex.Message + "\n" + ex.StackTrace);\n}\n\nprivate static void GlobalThreadExceptionHandler(object sender, System.Threading.ThreadExceptionEventArgs e)\n{\n   Exception ex = default(Exception);\n   ex = e.Exception;\n   ILog log = LogManager.GetLogger(typeof(Program)); //Log4NET\n   log.Error(ex.Message + "\n" + ex.StackTrace);\n}	0
31276538	31276315	WPF Custom control property set via XAML in own tag	private TextBlock displayControl;\n\npublic TextBlock DisplayControl {\n    get { return displayControl; }\n    set { displayControl = value; }\n}	0
6065416	6064652	Call javascript on page from ASP.Net User Control Event	ScriptManager.RegisterStartupScript(UP1, UP1.GetType(), "alertHi", "alert('hi');", true);	0
6329152	6328970	Storing data from SQL queries into my own data structures	using (var connection = new SqlConnection("....{connection string}..."))\nusing (var selectCommand = connection.CreateCommand())\n{\n    selectCommand.CommandText = "SELECT whatever FROM wherever";\n    //...command parameters setup here if necessary\n\n    using (var reader = selectCommand.ExecuteReader(CommandBehavior.CloseConnection))\n    {\n        while (reader.Read())\n        {\n            //process data here\n            int whateverId = (int)reader["IdColumn"];\n            string whateverName = (string)reader["NameColumn"];\n\n            //and so on, you get the idea...\n        }\n    }\n}	0
10941814	10747261	Add a GET parameter to a POST request with RestSharp	var client = new RestClient("http://localhost");\nvar request = new RestRequest("resource?auth_token={authToken}", Method.POST);\nrequest.AddParameter("auth_token", "1234", ParameterType.UrlSegment);    \nrequest.AddBody(json);\nvar response = client.Execute(request);	0
26804392	26804374	Convert Enum to string in c#	Language.EN.ToString();	0
30209016	30208560	Iterate through checkboxes, send email and loop	MailMessage mail_client = new MailMessage();\n int index = 0\n  foreach (string email in chkbox)\n   {\n   mail_client.To.Add(chkbox[index]);  \n    index++;\n   }\n\nmail_client.From = new MailAddress("");\nmail_client.Subject = subject;\nmail_client.IsBodyHtml = true;\nmail_client.Body = body;\n\nsmtp.Host = "";\nsmtp.Port = ;\nsmtp.UseDefaultCredentials = true;\nsmtp.Send(mail_client);	0
20271788	20271716	Combine a string-array with the remove- and split-function, to only one line of code?	string[] result = content.Split('|').Select((r, i) => \n                        new { Value = i == 0 ? r.Remove(0, 4) : r, Index = i })\n                        .Select(r => r.Value)\n                        .ToArray();	0
23324472	23324455	C# how to write a generic method	public interface ICommonInterface\n{\n   // declare your properties here\n   // and don't forget to implement this interface in your classes\n}\n\nprivate void UpdateMeta<T>(T obj)\n       where T : ICommonInterface\n{\n    obj.meta1 = DateTime.Now;\n    obj.meta2 = "acb";\n    obj.meta3 = 123;\n    obj.meta4 = "foo";\n}	0
19952646	19952558	Ling query to get all values from between two dates	public IEnumerable<DateTime> test(DateTime dt, DateTime dt2)\n{\n    // check if dt is smaller (or the same) as dt2 and code this out or throw error\n\n    // replace dates with actual class / code\n    List<DateTime> dates = new List<DateTime>();\n\n    return dates.Where(d => d >= dt && d <= dt2);\n}	0
32181643	32165286	Set a readoly/InitOnly member field using Linq Expressions	Expression.Assign	0
10766877	10766072	How to group the same values in a sequence with LINQ?	var list = new List<int> { 10, 1, 1, 5, 25, 45, 45, 45, 40, 100, 1, 1, 2, 2, 3 };\n        List<int> result = list.Where((x, index) =>\n        {\n            return index == 0 || x != list.ElementAt(index - 1) ? true : false;\n        }).ToList();	0
29392360	29341818	Finding LDAP domain name on a (virtual) server	using (DirectoryEntry rootDSE = new DirectoryEntry("LDAP://RootDSE"))\n{\n    result = (rootDSE.Properties["dnsHostName"].Value ?? "").ToString();\n    if (result != "") return result;\n}	0
15634126	15634014	How to swap Hashtable's key with Value	using System;\nusing System.Collections;\n\nclass Program\n{\n  static void Main()\n  {\n      Hashtable hsTbl = new Hashtable();\n\n      hsTbl.Add(1, "Suhas");\n      hsTbl.Add(2, "Madhuri");\n      hsTbl.Add(3, "Om"); \n\n      DictionaryEntry[] entries = new DictionaryEntry[hsTbl.Count];\n      hsTbl.CopyTo(entries, 0);\n      hsTbl.Clear();\n\n      foreach(DictionaryEntry de in entries) hsTbl.Add(de.Value, de.Key);\n\n      // check it worked\n\n      foreach(DictionaryEntry de in hsTbl)\n      {\n         Console.WriteLine("{0} : {1}", de.Key, de.Value);\n      }\n  }\n}	0
11120992	11120939	How to remove entries in a list starting from nth position?	List<T>.RemoveRange	0
36367	36350	How to pass a single object[] to a params object[]	Foo((object)new object[]{ (object)"1", (object)"2" }));	0
28252930	28252564	Convert a List of objects to a byte array in c#	public static byte[] StructureArrayToByteArray(ChangedByte[] objs)\n{\n    int structSize = Marshal.SizeOf(typeof(ChangedByte));\n    int len = objs.Length * structSize;\n    byte[] arr = new byte[len];\n    IntPtr ptr = Marshal.AllocHGlobal(len);\n    for (int i = 0; i < objs.Length; i++ ) {\n        Marshal.StructureToPtr(objs[i], ptr + i*structSize, true);\n    }\n    Marshal.Copy(ptr, arr, 0, len);\n    Marshal.FreeHGlobal(ptr);\n    return arr;\n}	0
25768107	25762942	How to get week of the month when selecting a date in datetimepicker?	private void dateTimePicker1_ValueChanged(object sender, EventArgs e)\n{\n   txtweek.Text=  (1+(dateTimePicker1.Value.Day / 7)).ToString("0");\n}	0
10950075	10939678	Infopath 2007 Repeating Table Nulls	int EmailID = rdr.GetOrdinal("EmailID");\n\nThen when using GetString:\n\nif (!(rdr.IsDBNull(14)))\n{\n     EmpNewData.SelectSingleNode("/my:myFields/my:Emp/my:EmpData/my:email", NamespaceManager).SetValue(rdr.GetString(EmailID));\n}\nelse\n{\n     EmpNewData.SelectSingleNode("/my:myFields/my:Emp/my:EmpData/my:email", NamespaceManager).SetValue("No Email");\n}	0
6310586	6310377	WCF Web API How to Add Argument to Every Endpoint	public class StatusKillerMessageHandler : DelegatingChannel {\n    public StatusKillerMessageHandler(HttpMessageChannel innerChannel)\n        : base(innerChannel) {\n    }\n\n    protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) {\n\n        bool suppressStatusCode = (request.RequestUri.AbsoluteUri.ToLower().Contains("suppress=true"));\n\n        return base.SendAsync(request, cancellationToken).ContinueWith<HttpResponseMessage>(task => {\n\n                   var response = task.Result;\n                   if (suppressStatusCode) {\n                        response.StatusCode = HttpStatusCode.OK;\n                   }\n                   return response;\n                });\n    }\n}	0
26051084	26034252	Unity static variable on every screen	public static class Test\n {\n     private static int x;\n\n\n     public static int foo()\n     {\n         return x;\n     }\n }	0
22443570	22443312	C# - XML reading outside of tags/elements	var xdoc = XDocument.Load("1.xml");\nvar text = xdoc.Root.Element("something").NextNode as XText;\n\nif (text != null)\n{\n    Console.WriteLine(text.Value);\n}	0
7732575	7732304	how can i convert this member table query into linq	from v in visits\njoin m in members on v.member_id equals m.member_id\nwhere v.visit_Date >= startDate && v.visit_Date <= endDate\ngroup m by new {  m.member_firstname, m.member_lastname, m.member_id } into g\norderby g.Count()\nselect new\n{\n   count = g.Count(),\n   member_firstname = g.Key.member_firstname, \n   member_lastname = = g.Key.member_lastname,\n   member_id = = g.Key.member_id,\n}	0
26799743	26799368	Difference in Arrays	int[] arr1 = new int[] { 1, 2, 3, 4, 5, 6, 7, 8 };\nint[] arr2 = new int[] { 2, 4, 6 };\n\n// copy the content of arr1 into a temporary List\nList<int> temp = new List<int>(arr1);\n// kick-out unneeded elements from temporary List\nforeach (int toRemove in arr2) temp.Remove(toRemove);\n\n// it's done\nint[] result = temp.ToArray();	0
5868804	5868783	Solve a cross-threading Exception in WinForms	// you can define a delegate with the signature you want\npublic delegate void UpdateControlsDelegate();\n\npublic void SomeMethod()\n{\n    //this method is executed by the background worker\n    InvokeUpdateControls();\n}\n\npublic void InvokeUpdateControls()\n{\n    if (this.InvokeRequired)\n    {\n        this.Invoke(new UpdateControlsDelegate(UpdateControls));\n    }\n    else\n    {\n        UpdateControls();\n    }\n}\n\nprivate void UpdateControls()\n{\n    // update your controls here\n}	0
22199580	22198913	Getting property value from model in view using Razor without new object declaration	...\nselect new CityViewModel {\nCity = _City;\n};	0
21577449	21554614	Delete all One to Many associated items - Telerik OpenAccess ORM	dbContext.Delete(User.Investments);\ndbContext.SaveChanges();	0
21115858	21115725	Merging Razor with Jquery for autocomplete function	source: @Html.Raw(Json.Encode(@ViewBag.Items));	0
10454807	10454595	Loading PictureBox Image From Database	// your code first here..\n\nvar da = new SqlDataAdapter(cmd);\nvar ds = new DataSet();\nda.Fill(ds, "Images");\nint count = ds.Tables["Images"].Rows.Count;\n\nif (count > 0)\n{ \n    var data = (Byte[])(ds.Tables["Images"].Rows[count - 1]["Image"]);\n    var stream = new MemoryStream(data);\n    pictureBox1.Image= Image.FromStream(sream);\n}	0
9688962	9688771	Resizing a user control	protected override void OnResize(EventArgs e) {\n  using (GraphicsPath gp = new GraphicsPath()) {\n    gp.AddEllipse(this.ClientRectangle);\n    this.Region = new Region(gp);\n  }\n\n  base.OnResize(e);\n}	0
10964214	10963756	Get DER-encoded public key	AsymmetricKeyParameter asymmetricKeyParameter = PublicKeyFactory.CreateKey(req.PublicKey);\n        RsaKeyParameters key = (RsaKeyParameters) asymmetricKeyParameter;	0
33867011	33866909	Required attribute for selectlist	[Required(ErrorMessage = "Your reason for contacting is required.")]\npublic int CustomerLocationID { get; set; }\n\nHtml.DropDownListFor(model => model.CustomerLocationID,Model.CustomerLocations)\n\n@Html.ValidationMessageFor(m => m.CustomerLocations)	0
4953078	4952602	How to reuse where clauses in Linq To Sql queries	var filter = CompiledQuery.Compile(\n    (DatabaseDataContext dc, Record record, string term) =>\n        record.Field1.ToLower().Contains(term) ||\n        record.Field2.ToLower().Contains(term) ||\n        record.Field3.ToLower().Contains(term)\n);\n\nvar results = from record in DataContext.Records\n              where filter(DataContext, record, term)\n              select record;	0
6289861	5964272	Use Moq to verify if list within object is changed properly	_mockedView.SetupAllProperties();	0
11036172	11035833	setting com control's TYPEATTR in C#	[System.Runtime.InteropServices.TypeLibType(TypeLibTypeFlags.FControl)]	0
20598188	20597573	How to make text to be located in the middle of that cell in the Excel?	Microsoft.Office.Interop.Excel.Range RangeYour= workSheet1.Range["B3:I3"];\n          //  rngcompphon.Merge();\n          //  rngcompphon.ShrinkToFit = true;\n            rngcompphon.VerticalAlignment = Microsoft.Office.Interop.Excel.XlHAlign.xlHAlignCenter;\n            rngcompphon.HorizontalAlignment = Microsoft.Office.Interop.Excel.XlHAlign.xlHAlignCenter;\n           // rngcompphon.Font.Bold = true;	0
19402053	19401485	TabControl with browser	Browser.DocumentText = title;	0
17444230	17443490	Google Webmaster SiteVerificatoin with DotNetOpenOauth	WebRequest request = WebRequest.Create("https://www.googleapis.com/siteVerification/v1/token?access_token=" + Uri.EscapeDataString(authState.AccessToken));\nstring path = HostingEnvironment.MapPath(@"~/App_Data/SiteVerificatoin.json"); \n\n\nMemoryStream ms = new MemoryStream();\nFileStream fileStreem = new FileStream(path, FileMode.Open, FileAccess.Read);\nbyte[] bytes = new byte[fileStreem.Length];\nfileStreem.Read(bytes, 0, (int)fileStreem.Length);\nms.Write(bytes, 0, (int)fileStreem.Length);\n\nrequest.ContentType = "application/json";\nrequest.Method = "POST";\nrequest.ContentLength = ms.Length;\nms.Seek(0, SeekOrigin.Begin);\nusing (Stream requestStream = request.GetRequestStream())\n{\n     ms.CopyTo(requestStream);\n}         \n\nWebResponse response = request.GetResponse();	0
25171720	25168617	toTitleCase to ignore ordinals in C#	string input =  System.Globalization.CultureInfo.CurrentCulture.TextInfo.ToTitleCase("hello there, this is the 1st");\nstring result = System.Text.RegularExpressions.Regex.Replace(input, "([0-9]st)|([0-9]th)|([0-9]rd)|([0-9]nd)", new System.Text.RegularExpressions.MatchEvaluator((m) =>\n{\n    return m.Captures[0].Value.ToLower();\n}), System.Text.RegularExpressions.RegexOptions.IgnoreCase);	0
12956098	12956034	Convert nested foreach-loops with 3 levels to recurrence with n levels	internal static void CreateLevel(LevelObject levelObject) {\n    foreach (var l in levelObject.LevelObjects) {\n        CreateLevel(l);\n        AddEntities(l);\n    }\n}	0
2451375	2451256	Custom XML Serialization, how to write custom root element?	var MemoryStream ms;\nvar customRoot = dataObject as XmlRootAttribute;\nvar xml = new XmlSerializer(dataObject.GetType(), customRoot);\nxml.Serialize(ms, dataObject);	0
7220688	7220637	Print 3 records per page to PDF	string[] collection = { "vivek", "kashyap", "viral", "darshit", "arpit", "sameer", "vanraj" };\n\nPdfDocument pdfDoc = new PdfDocument();\n\nint records = collection.Length;\nint perpage = 3;\nint pages = (int)Math.Ceiling((double)records / (double)perpage);\n\nint idx = 0;\n\nfor (int p = 0; p < pages; p++)\n{\n\n    PdfPage pdfPage = new PdfPage();\n    pdfPage.Size = PageSize.Letter;\n    pdfDoc.Pages.Add(pdfPage);\n    XFont NormalFont = new XFont("Helvetica", 10, XFontStyle.Regular);\n    using (var pdfGfx = XGraphics.FromPdfPage(pdfPage))\n    {\n        for (int i = 0,next = 100; i < perpage; i++)\n        {\n            if ((idx + i) >= records.length) break;\n            pdfGfx.DrawString("Name : " + collection[idx  + i].ToString(), NormalFont,\n                XBrushes.Black, 55, next, XStringFormats.Default);\n\n            next += 20;\n        }\n    }\n\n    idx += perpage;\n\n}	0
2771326	2739856	Show different sub-sets of a view model's properties in an edit view	EditorFor/EditorForModel	0
17361990	17361509	can't manually update a mysql database containing text fields with c#	string cmdText = "UPDATE words SET word = @word WHERE id = @id";\nusing(MySqlConnection cn = new MySqlConnection(constring))\nusing(MySqlCommand cmd = new MySqlCommand(cmdText, cn))\n{\n    cn.Open();\n    cmd.Parameters.AddWithValue("@word", edtWord.Text);\n    cmd.Parameters.AddWithValue("@id", current_id);\n    cmd.ExecuteNonQuery();\n}	0
11904230	11903084	Convert ListBoxItem to Image	var listBoxItem = listBox.ItemContainerGenerator.ContainerFromIndex(0) as ListBoxItem;\n            RenderOptions.SetBitmapScalingMode(image, BitmapScalingMode.HighQuality);\n            RenderTargetBitmap renderTargetBitmap = new RenderTargetBitmap((int)listBoxItem.ActualWidth,\n                                                                           (int)listBoxItem.ActualHeight, 96, 96,\n                                                                           PixelFormats.Pbgra32);\n            renderTargetBitmap.Render(listBoxItem);\n            image.Source = renderTargetBitmap;\n            image.Width = listBoxItem.ActualWidth;\n            image.Height = listBoxItem.ActualHeight;	0
33957950	33945683	How can I disable Object control on mouse click?	public class Ball : MonoBehaviour {\n\n    Rigidbody2D body;\n    float mousePosInBlocks;\n    bool wasDropped = false;\n\n    void Start () {\n        body = GetComponent<Rigidbody2D> ();\n        body.isKinematic = true;\n    }\n\n    void Update () {\n        //Don't do anything after the ball is dropped.\n        if(wasDropped)\n            return;\n\n        if (Input.GetMouseButtonDown (0)) {\n            body.isKinematic = false;\n            wasDropped = true;\n        }\n\n        Vector3 ballPos = new Vector3 (0f, this.transform.position.y, 0f);\n        mousePosInBlocks = Camera.main.ScreenToWorldPoint(Input.mousePosition).x;\n        //not go outside from border\n        ballPos.x = Mathf.Clamp (mousePosInBlocks, -2.40f, 2.40f);\n\n        body.position = ballPos;\n    }\n}	0
33229879	33229853	DateTimePicker Date formatting value	DateTimePicker.Value.ToString("yyyyMMdd");	0
3594757	3571413	Click two new points and draw a line between those two points using mouse event	private Point p1, p2;\nList<Point> p1List = new List<Point>();\nList<Point> p2List = new List<Point>();\n\n    private void Panel1_MouseDown(object sender, MouseEventArgs e)\n    {\n        if (p1.X == 0)\n        {\n            p1.X = e.X;\n            p1.Y = e.Y;\n        }\n        else\n        {\n            p2.X = e.X;\n            p2.Y = e.Y;\n\n            p1List.Add(p1);\n            p2List.Add(p2);\n\n            Invalidate();\n            p1.X = 0;\n        }\n    }\n\n    private void Panel1_Paint(object sender, PaintEventArgs e)\n    {\n        using(var p = new Pen(Color.Blue, 4))\n        {\n            for(int x = 0; x<p1List.Count; x++){\n                e.Graphics.DrawLine(p, p1List[x], p2List[x]);\n            }\n        }\n    }	0
9403521	9403491	Storing a double with 2 digit precision	Console.WriteLine(x.ToString("F2"));	0
17008294	17008153	detect enterline when copy big text data into textbox	using System.Windows.Forms;\n\nnamespace WindowsFormsApplication1\n{\n    public class MyTextBox : TextBox \n    {\n        protected override void WndProc(ref Message m)\n        {\n            // Trap WM_PASTE:\n            if (m.Msg == 0x302 && Clipboard.ContainsText())\n            {\n                var pastText = Clipboard.GetText().Replace('\n', ' ');\n                if (pastText.Length > MaxLength)\n                {\n                    //Do Something \n                }\n                else\n                {\n                    //Do Something \n                }\n                this.SelectedText = pastText;\n                return;\n            }\n            base.WndProc(ref m);\n        }\n    }\n}	0
24474856	24474790	Display all blog articles of a specific user	int localAuthorId = ???; // assign from wherever you fetched it\n\n// simpler filter:\ndb.BlogArticles.Where(x => x.AuthorId = localAuthorId).ToList()	0
12880193	12685810	XNA - How to access a texture from .x model?	Texture2d texture = ((BasicEffect)model.Meshes[0].Effects[0]).Texture	0
3671701	3671626	placeholder for storing temp values in c# thread context	public static class ThreadLocalExample\n{\n    // There will be one Foo instance per thread.\n    // Each thread will have to initialize it's own instance.\n    [ThreadStatic]\n    private static Foo bar;\n}	0
16583259	16583106	How to get the name of List	static List<string> GatherDataPerProduct(List<Pandora.Data.DomainObject> lstdata)\n    {\n        if(lstData.value == "subjects")\n        {\n          //do whatever\n         }\n\nList<DomainObject> subjects;\nGatherDataPerProduct(subjects);	0
13747072	13746776	Unable to combine tags using TagBuilder	var label = new TagBuilder("label");\nlabel.Attributes.Add("id", "required" + id);\n//I get the id earlier fyi - not pertinent fyi for this question )\n\n// Create the Span\nvar span = new TagBuilder("span");\nspan.AddCssClass("requiredInidicator");\nspan.SetInnerText("* ");\n\n//Now combine the span's content with the label tag\nlabel.InnerHtml = span.ToString(TagRenderMode.Normal) + htmlHelper.Encode(labelText);\nreturn MvcHtmlString.Create(label.ToString(TagRenderMode.Normal));	0
11551225	11551185	Converting a string to datetime from "yyyy-MM-dd"	DateTime result = DateTime.ParseExact("2012-04-05", "yyyy-MM-dd", CultureInfo.InvariantCulture);	0
7095502	7094580	WPF GridViewColumn's DisplayMemberBinding using a Dictionary Key's Value	public class LogEntry\n{\n    public Dictionary<string, string> Stuff { get; set; }\n    public string MyOtherProperty { get; set; }\n}	0
34207913	34207522	Get Sub Directory Files and Add to String Array	localFiles.Add(f.FullName);	0
12835927	12814271	How to get changes from sharepoint 2010 client object model?	ClientContext context = new ClientContext("http://SPSite");\ncontext.Credentials = new NetworkCredential("user", "pwd", "domain");\nChangeQuery cq = new ChangeQuery(true, true); \ncq.ChangeTokenStart = new ChangeToken();\ncq.ChangeTokenStart.StringValue = "1;3;" + list.Id.ToString() + ";" + DateTime.UtcNow.AddHours(-1).Ticks.ToString() + ";-1";                 \nChangeCollection col = list.GetChanges(cq);            \ncontext.Load(col);\ncontext.ExecuteQuery();\nMessageBox.Show(col.Count.ToString());	0
13017641	13017448	Drawing a line where the mouse went	private Point _lastPoint;\n\nprotected void MouseDown(object sender, System.Windows.Forms.MouseEventArgs e)\n{\n    Graphics g = CreateGraphics();\n    g.LineTo(_lastPoint.X, _lastPoint.Y, e.X, e.Y);\n    _lastPoint = new Point(e.X, e.Y);\n}	0
4505856	4505825	Convert UTC time in UNIX time format to a readable DateTime format?	double timestamp = 1292985942;\nDateTime dateTime = new System.DateTime(1970, 1, 1, 0, 0, 0, 0);\ndateTime = dateTime.AddSeconds(timestamp);	0
26273581	26257993	How to prevent ODataConventionModelBuilder to automatically expose all derived types' metadata?	ODataConventionModelBuilder builder = new ODataConventionModelBuilder();\n\nbuilder.Namespace = "X";\n\nbuilder.ContainerName = "Y";\n\nbuilder.EntitySet("Z");\n\nbuilder.Ignore<Q>();\n\nIEdmModel edmModel = builder.GetEdmModel();	0
3747580	3654987	Upload photo to Facebook from Silverlight	byte[] photo = File.ReadAllBytes(photoPath);\n        FacebookApp app = new FacebookApp();\n        dynamic parameters = new ExpandoObject();\n        parameters.access_token = "access_token";\n        parameters.caption = "Test Photo";\n        parameters.method = "facebook.photos.upload";\n        parameters.uid = ConfigurationManager.AppSettings["UserId"];\n        var mediaObject = new FacebookMediaObject\n        {\n            FileName = "monkey.jpg",\n            ContentType = "image/jpeg",\n        };\n        mediaObject.SetValue(photo);\n        parameters.source = mediaObject;\n        app.ApiAsync((ar, state) => { \n            var postId = (string)ar.Result;\n        }, null, parameters, HttpMethod.Post);	0
7925333	7925141	Unable to call Assembly.GetName() from my Silverlight application	GetCallingAssembly().FullName	0
19428246	19427440	Split 2d string array	String.Join(";", result.Select(a => String.Join(",", a)).ToArray());	0
21407550	21407164	show search data in gridview of another page when search button click	protected void imgbtnsubmit_Click(object sender, ImageClickEventArgs e)\n    {\n        Response.Redirect(string.Format("show.aspx?loc={0}&title={1}&exp={1}", textloc.Text, txttitle.Text, dropdownlistexperience.SelectedItem));\n    }	0
5360282	5360250	How to make a simple search function in linq and EF	var found = MyContext.Users.Where(user => user.UserName.Contains(searchString));	0
2024112	2024034	How to send more than one CopyPixelOperation through CopyFromScreen?	CopyPixelOperation.CaptureBlt	0
6996214	6995144	Get number of rows updated ObjectContext.ExecuteFunction in C#	SET NOCOUNT ON	0
1792057	1792027	How to deserialze a binary file	protected GroupMgr(SerializationInfo info, StreamingContext context) {\n            Groups = (Dictionary<int, Group>) info.GetValue("Groups", typeof(Dictionary<int, Group>));\n            Linker = (Dictionary<int, int>) info.GetValue("Linker", typeof(Dictionary<int, int>));\n            }	0
6060624	5905340	NHibernate, reseting properties after accessing related object	Id(x => x.Id).GeneratedBy.GuidComb().UnsavedValue(Guid.Empty);	0
21245498	21245232	WPF - raised to the power of - Converter	public class NumberConverter : IValueConverter\n{\n\n    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)\n    {\n        //do you conversion here - "value" is the parameter you need to convert and return\n    }\n\n    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)\n    {\n        //you can optionally implement the conversion back (from scientific value to integer)\n        throw new NotImplementedException();\n    }\n}	0
13502614	13502513	How do I create an entire directory structure for a perhaps nonexistant path and file?	/// <summary>\n/// Create the folder if not existing for a full file name\n/// </summary>\n/// <param name="filename">full path of the file</param>\npublic static void CreateFolderIfNeeded(string filename) {\n  string folder = System.IO.Path.GetDirectoryName(filename);\n  if (!System.IO.Directory.Exists(folder)) {\n    System.IO.Directory.CreateDirectory(folder);\n  }\n}	0
6616187	6615748	Add one space after every two characters and add a character infront of every single character	string str1 = "3322356";\n            string str2;\n\n            str2 = String.Join(" ", \n                str1.ToCharArray().Aggregate("",\n                (result, c) => result += ((!string.IsNullOrEmpty(result) &&\n                    (result.Length + 1) % 3 == 0) ? " " : "") + c.ToString())\n                    .Split(' ').ToList().Select(\n                x => x.Length == 1 \n                    ? String.Format("{0}{1}", Int32.Parse(x) - 1, x) \n                    : x).ToArray());	0
18372604	18368099	(OAuthException - #200) (#200) Unpublished posts must be posted to a page as the page itself	string url = string.Format(\n    "https://graph.facebook.com/{0}?fields=access_token&access_token={1}",\n    pageID, user_access_token);	0
14279667	14278462	Flattening a protobufs-net contract	[ProtoContract]\npublic class NewClass\n{\n    [ProtoMember(2)]\n    public string Prop1 { get; set; \n\n    [ProtoMember(100)]\n    public string Prop2 { get; set; }\n\n    [ProtoMember(1)] // this 1 is from ProtoMember\n    private Shim ShimForSerialization { get { return new Shim(this); } }\n\n    // this disables the shim during serialiation; only Prop1 and Prop2 will\n    // be written\n    public bool ShouldSerializeShimForSerialization() { return false; }\n\n    [ProtoContract]\n    private class Shim {\n        private readonly NewClass parent;\n        public Shim(NewClass parent) {\n            this.parent = parent;\n        }\n        [ProtoMember(1)]\n        public string Prop1 {\n            get { return parent.Prop1;}\n            set { parent.Prop1 = value;}\n        }\n\n    }\n}	0
2720011	2719948	Setting the cursor position in a NumericUpDown Control	yourNumericUpDown.Select(desiredPosition,0)	0
13875857	13875362	Keyboard sequence shortcuts for menu	private void Form1_KeyDown(object sender, KeyEventArgs e)\n{\n  if (previousKeyEvent != null)\n  {\n    if (previousKeyEvent.Modifiers == Keys.Control && previousKeyEvent.KeyCode == Keys.W && e.KeyCode == Keys.O)\n    {\n      MessageBox.Show("Ctrl + W then O");\n    }\n    else\n    {\n      MessageBox.Show("Not handled");\n      previousKeyEvent = null;\n    }\n  else\n    previousKeyEvent = e;\n  }\n}	0
2391647	2391604	WPF: Access XAML objects/shapes/path declared using C#	private void Window_Loaded(object sender, RoutedEventArgs e)\n{\n    layout1.Visibility = System.Windows.Visibility.Hidden;\n}	0
9193690	9192709	Run a method before all methods of a class	public class Magic{\n\nprivate static Magic magic;\npublic static Magic Instance{\n  get\n    {\n   BaseMethod();\n    return magic;\n    }\n}\n\npublic void BaseMethod(){\n}\n\n//runs BaseMethod before being executed\npublic void Method1(){\n}\n\n//runs BaseMethod before being executed\npublic void Method2(){\n}\n}	0
6068049	6066440	Isolated Storage Application Settings Not Persisting after Application exit	IsolatedStorageSettings isoStoreSettings = IsolatedStorageSettings.ApplicationSettings;\nif (isoStoreSettings.Contains(key))\n{\n    isoStoreSettings[key] = value;\n}\nelse\n{\n    isoStoreSettings.Add(key, value);\n}\nisoStoreSettings.Save();	0
2282613	2282448	Windows 7 and Vista UAC - Programatically requesting elevation in C#	WindowsPrincipal pricipal = new WindowsPrincipal(WindowsIdentity.GetCurrent());\nbool hasAdministrativeRight = pricipal.IsInRole(WindowsBuiltInRole.Administrator);\n\nif (!hasAdministrativeRight)\n{\n    RunElevated(Application.ExecutablePath);\n    this.Close();\n    Application.Exit();\n}\n\nprivate static bool RunElevated(string fileName)\n{\n    //MessageBox.Show("Run: " + fileName);\n    ProcessStartInfo processInfo = new ProcessStartInfo();\n    processInfo.Verb = "runas";\n    processInfo.FileName = fileName;\n    try\n    {\n        Process.Start(processInfo);\n        return true;\n    }\n    catch (Win32Exception)\n    {\n        //Do nothing. Probably the user canceled the UAC window\n    }\n    return false;\n}	0
21645354	21645270	how to remove buttons created dynamically	class Form1 : Form {\n    private Button[] _textBoxes;\n\n    private void button2_Click(object sender, EventArgs e) {\n        int number = int.Parse(textBox3.Text);\n        if(_textBoxes != null) {\n            foreach(Button b in _textBoxes)\n                this.Controls.Remove(b);\n        }\n\n        _textBoxes = new Button[number];\n        int location = 136;\n\n        for (int i = 0; i < textBoxes.Length; i++) {\n            location += 81;\n            var txt = new Button();\n            _textBoxes[i] = txt;\n            txt.Name = "text" + i.ToString();\n            txt.Text = "textBox" + i.ToString();\n            txt.Location = new Point(location, 124);\n            txt.Visible = true;\n            this.Controls.Add(txt);\n        }\n    }\n}	0
26967442	26967367	Deserialize XML Document	[XmlRoot("Exclusionpolicys")]\n    public class ExclusionPolicys\n    {\n        [XmlElement("Exclusionpolicy")]\n        public List<Exclusionpolicy> Exclusionpolicy;\n    }\n\n    public class Exclusionpolicy\n    {\n\n        [XmlElement("ValuationRoutes")]\n        public List<ExcludedPolicyValuationRoutes> ValuationRoutes { get; set; }\n\n        [XmlElement("ExcludeHives")]\n        public List<ExcludedPolicyHives> ExcludedHives { get; set; }\n    }\n\n    public class ExcludedPolicyHives\n    {\n        [XmlElement("ExcludeHive")]\n        public List<ExcludedPolicyHive> ExcludedPolicyHive;\n    }\n\n    public class ExcludedPolicyValuationRoutes\n    {\n        [XmlElement("ValuationRoute")]\n        public List<ValuationRoute> ValuationRoute { get; set; }\n    }\n\n    public class ExcludedPolicyHives\n    {\n        public string Hives { get; set; }\n    }\n\n    public class ExcludedPolicyValuationRoute\n    {\n        public string ValuationRoutes { get; set; }\n    }	0
2730236	2730221	How do I add a record only if it doesn't already exist in SQL Server?	IF NOT EXISTS (SELECT * FROM Process WHERE process_name = 'xxx')\nINSERT INTO Process (process_name, Full_Name, Version) \nVALUES ('xxx', 'yyy', 'zzz')	0
5309934	5309869	How do I convert a string into a variable reference?	var ctr = myConfigurationHandler.MyConfiguration.MyService.RSController;\nAddSharedFolder(ctr.repositoryName, ctr.repositoryDomain,\n                ctr.repositoryUsername, ctr.repositoryPassword);	0
11807157	11806232	Getting Null Reference error when trying to set a picture in Telerik Gridview	private void radGridView1_CellFormatting(object sender, CellFormattingEventArgs e)\n        {\n            try\n            {\n                if (e.CellElement.ColumnInfo.HeaderText == "Picture") \n                {\n                    e.CellElement.Image = pictureBox1.Image;\n                }\n\n            }\n            catch (Exception ex)\n            {\n                MessageBox.Show(ex.Message);\n            }\n        }\n    }	0
4190926	4190915	Help with LINQ-SQL GroupBy	// Construct base query\nvar query = (from p in db.tblProCons\n             where p.IdPrimaryCity == idPrimaryCity\n             group p by new { p.IdPrimaryCity, p.IsPro, p.Description } into g\n             select new { ProCon = g.Key, NumberOfAgrees = g.Count() });\n\n// Split queries based on pro/con, and apply TOP(3)\nvar pros = query.Where(x => x.ProCon.IsPro).Take(3);\nvar cons = query.Where(x => !x.ProCon.IsPro).Take(3);\n\nresult = pros\n    .Union(cons) // Union pro/cons\n    .OrderByDescending(x => x.ProCon.IsPro) // Order #1 - Pro/Con\n    .ThenByDescending(x => x.NumberOfAgrees) // Order #2 - Number of Agree's\n    .Select(x => new ProCon // project into cut-down POCO\n            {\n                Description = x.ProCon.Description,\n                IsPro = x.ProCon.IsPro\n            }).ToList();	0
26340195	26339350	Need two different textbox's to only allow numbers 0-9 and 1 decimal place	private bool IsValidValue(string text)\n        {\n            bool isValid;\n            if (text.EndsWith("."))\n            {\n                text += "0";\n            }\n            if (Regex.IsMatch(text, @"^(\+|\-?)(((\d+)(.?)(\d+))|(\d+))$"))\n            {\n                isValid = true;\n            }\n            return isValid;\n\n        }	0
33568887	33568492	LinqToCSV format column as Text	void Main()\n{\n  ExcelPackage pck = new ExcelPackage();\n  List<Person> people = new List<Person> {\n    new Person { UserName="Cetin", Address1="A1", Telephone="012345"},\n    new Person { UserName="Timbo", Address1="A2", Telephone="023456"},\n    new Person { UserName="StackO", Address1="A3", Telephone="0 345 6789 01 23"},\n  };\n\n\n  var wsEnum = pck.Workbook.Worksheets.Add("MyPeople");\n\n  //Load the collection starting from cell A1...\n  wsEnum.Cells["A1"].LoadFromCollection(people, true, TableStyles.Medium9);\n  wsEnum.Cells[wsEnum.Dimension.Address].AutoFitColumns();\n  //...and save\n  var fi = new FileInfo(@"d:\temp\People.xlsx");\n  if (fi.Exists)\n  {\n    fi.Delete();\n  }\n  pck.SaveAs(fi);\n}\n\nclass Person\n{\n  public string UserName { get; set; }\n  public string Address1 { get; set; }\n  public string Telephone { get; set; }\n}	0
4863584	4863259	Need a asynchronous file reader without knowing the size	private void GetTheFile()\n    {\n        FileFetcher fileFetcher = new FileFetcher(Fetch);\n\n        fileFetcher.BeginInvoke(@"c:\test.yap", new AsyncCallback(AfterFetch), null);\n    }\n\n    private void AfterFetch(IAsyncResult result)\n    {\n        AsyncResult async = (AsyncResult) result;\n\n        FileFetcher fetcher = (FileFetcher)async.AsyncDelegate;\n\n        byte[] file = fetcher.EndInvoke(result);\n\n        //Do whatever you want with the file\n        MessageBox.Show(file.Length.ToString());\n    }\n\n    public byte[] Fetch(string filename)\n    {\n        return File.ReadAllBytes(filename);\n    }	0
934355	934327	Linq to SQL to append multiple records with a delimiter	DECLARE @txt varchar(max)\nSET @txt = ''\nSELECT @txt = @txt + [DocumentName] + ', '\nFROM [Documents]\nWHERE [UserID] = @UserID\n\nSELECT [ID], [Name], @txt AS [Docs]\nFROM [Users]\nWHERE [ID] = @UserID	0
5970265	5969986	need an architectural suggestion	fieldName[] = {"Field1","field2",....}\n\nString results[][] = getDBResults()  \nfor( i=0;i&ltnumCOls;i++ ) {  \n    line = fieldName[i] + ",";  \n      for(j=0; j<&ltnumRows; j++) {  \n          line += results[j][i] + ",";  \n      }\n      FILE.writeline(line[:-1]);  \n}	0
16780895	16780442	Using C#, how do I read a text file into a matrix of characters and then query that matrix? Is this even possible?	int column = 0;\nchar charToCheck = 't';\n\nbool b = File.ReadLines(filename)\n             .All(s => (s.Length > column ? s[column] : '\0') == charToCheck);	0
32917697	32659436	Disposal of Shared members in a ServicedComponent with ActivationOption.Server	Imports System.EnterpriseServices\n\n<Assembly: ApplicationName("MySender")> \n<Assembly: ApplicationActivation(ActivationOption.Server)>\n\n<ClassInterface(ClassInterfaceType.None), ProgId("MySender.Sender")> _\n<Transaction(EnterpriseServices.TransactionOption.NotSupported)> _\nPublic Class Sender\n\n    Shared Sub New\n\n        AddHandler AppDomain.CurrentDomain.ProcessExit, AddressOf MyDisposalCode\n\n    End Sub\n\n    '....\n\n    Shared Sub MyDisposalCode(sender as Object, e as EventArgs)\n\n        'My disposal code\n\n    End Sub\n\nEnd Class	0
2380311	2380288	Accessing a property in Visual Basic as opposed to C#	My.MySettings.Default.MyString	0
19199381	19198898	How to play a sound in foreground under lock screen?	PhoneApplicationService.Current.ApplicationIdleDetectionMode = IdleDetectionMode.Disabled;	0
32372179	32371973	How to replace only capturing group in Regex.Replace?	string xml = "abc def ghi blabla horse 123 jakljd alj ldkfj s;aljf kljf sdlkj flskdjflskdjlf lskjddhcn guffy";\nDictionary<string, string> substitutions = new Dictionary<string, string> \n{ \n    {@"(?<=abc\s).+(?=\sghi)", "AAA"},\n    {@"(?<=kljf\s).+(?=\sflskdjflskdjlf)", "BBB"}\n};\n\nforeach (KeyValuePair<string, string> entry in substitutions)\n{\n    xml = Regex.Replace(xml, entry.Key, entry.Value);\n    Console.WriteLine(xml);\n}	0
17501881	17501813	Numeric data type formatting after SqlDataReader	zcena1.Text = precti.GetDecimal(4).ToString().Replace(',', '.');	0
14383350	14382631	How to get the exact regions that need to be draw in OnPaint() event?	typedef struct tagPAINTSTRUCT {\n  HDC  hdc;\n  BOOL fErase;\n  RECT rcPaint;              // <=== here\n  BOOL fRestore;\n  BOOL fIncUpdate;\n  BYTE rgbReserved[32];\n} PAINTSTRUCT, *PPAINTSTRUCT;	0
1313738	1295000	.NET WinForms DataBinding - BindingList<IBindableItem> where some implementations of IBindableItem may also implement IList	public class Folder : ITreeItem\n{\n    public Folder(string name)\n    {\n        Name = name;\n        Children = new BindingList<ITreeItem>();\n    }\n\n    public string Name { get; set; }\n\n    public BindingList<ITreeItem> Children { get; private set; }\n}	0
18260115	18259190	Check if in one integer array are exactly a number of matches in c#?	int[] array1 = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25 };\nint[] array2 = { 1, 2, 3, 4, 5, 36, 77, 88, 49, 50, 51, 52, 53, 54, 55 };\n\nint numMatches = array1.Intersect(array2).Count();	0
18464782	18463678	how to loop through each node of HTML using HTMLAgilitypack and delete certain nodes?	String content = "Your Html page source as string";\n                HtmlNode.ElementsFlags.Remove("form");\n                HtmlDocument doc = new HtmlDocument();\n                doc.LoadHtml(content);\n\n                // Pass the name of the tag you want to remove \n                DeleteTagByName("tagname",doc);\n                public void DeleteTagByName(string name, HtmlDocument HtmlDocument)\n                 {\n                     HtmlDocument.DocumentNode.SelectSingleNode("//input[@name='" + name + "']").Remove();\n\n                }	0
10392320	10392285	Recognize DateTime String as valid when containing day names in C#	DateTime d;\nstring dateString = "Tuesday May 1, 2012 9:00 AM";\nreturn DateTime.TryParseExact(\n   dateString,\n   "dddd MMMM d, yyyy h:mm tt",\n   System.Globalization.CultureInfo.CurrentCulture,\n   System.Globalization.DateTimeStyles.None,\n   out d\n);	0
3769331	3765874	I need to be able to separate my select statements for EF	static readonly Expression<Func<DbUser, User>> GetUser(int uid)\n{ \n    return (g) => new User \n                  {\n                      Uid = g.uid,\n                      FirstName = g.first_name,\n                      LastName = g.last_name,\n                      BigPicUrl = g.pic_big,\n                      Birthday = g.birthday,\n                      SmallPicUrl = g.pic_small,\n                      SquarePicUrl = g.pic_square,\n                      Locale = g.locale.Trim(),\n                      IsFavorite = g.FavoriteFriends1.Any(x=>x.uid==uid),\n                      FavoriteFriendCount = g.FavoriteFriends.Count,\n                      LastWishlistUpdate = g.WishListItems\n                                            .OrderByDescending(x=>x.added)\n                                            .FirstOrDefault().added\n                  };\n}	0
4022629	4021893	Saving a Dictionary<String, Int32> in C# - Serialization?	public void Serialize(Dictionary<string, int> dictionary, Stream stream)\n{\n    BinaryWriter writer = new BinaryWriter(stream);\n    writer.Write(dictionary.Count);\n    foreach (var kvp in dictionary)\n    {\n        writer.Write(kvp.Key);\n        writer.Write(kvp.Value);\n    }\n    writer.Flush();\n}\n\npublic Dictionary<string, int> Deserialize(Stream stream)\n{\n    BinaryReader reader = new BinaryReader(stream);\n    int count = reader.ReadInt32();\n    var dictionary = new Dictionary<string,int>(count);\n    for (int n = 0; n < count; n++)\n    {\n        var key = reader.ReadString();\n        var value = reader.ReadInt32();\n        dictionary.Add(key, value);\n    }\n    return dictionary;                \n}	0
17468208	17468100	Getting repeater item checkbox values when calling command from footer	!IsPostBack	0
9357189	9357083	Playing media file from Isolated Storage in windows phone?	grid.Children.Add(media);	0
27142762	27142661	How to get the time between 2 actions for debug purposes	Stopwatch stopwatch = new Stopwatch();\nif (smiteReady && mob.Health < smitedamage)\n{\n   stopwatch.Start();\n   smite.Cast();\n}\nif (mob.Health < smitedamage + spelldamage)\n{\n   stopwatch.Stop();\n   Console.WriteLine("Time elapsed: {0}", stopwatch.Elapsed);\n   champSpell.Cast();\n}	0
27821261	16478057	asp.net User Profile: how do I add a field once the DB has Users?	var profile = ProfileBase.Create(username);\nprofile.SetPropertyValue("MyGuid", aGuid);\nprofile.SetPropertyValue("MyString", aString);\n// etc\nprofile.Save()	0
15524865	13823668	How to get rid of my "After Spacing" on open xml	SpacingBetweenLines spacing = new SpacingBetweenLines() { Line = "240", LineRule = LineSpacingRuleValues.Auto, Before = "0", After = "0" };\nParagraphProperties paragraphProperties = new ParagraphProperties();\nParagraph paragraph = new Paragraph();\n\nparagraphProperties.Append(spacing);\nparagraph.Append(paragraphProperties);	0
12023657	12023433	Combobox add rows dynamically and dropdown from SQL Server stored procedure	static public DataTable searchIt(string STR)\n{\n    string connectionString =  McFarlaneIndustriesPOSnamespace.Properties.Settings.Default.McFarlane_IndustriesConnectionString;\n    SqlConnection con = new SqlConnection(connectionString);\n    DataTable DT = new DataTable();\n    con.Open();\n    SqlCommand command = new SqlCommand("Name_of_Your_Stored_Procedure",con);\n    command.CommandType=CommandType.StoredProcedure;\n    command.Parameters.Add(new SqlParameter("@parameter_name",SqlDbType.NVarChar));\n    command.Parameters[0].Value="Your Value in this case STR";\n    SqlDataAdapter DA = new SqlDataAdapter(command);\n    DA.Fill(DT);\n    con.Close();\n    return DT;\n}	0
7157436	7157280	catch particular element from XML file	XmlDocument xml = new XmlDocument();\nxml.LoadXml(System.Web.HttpContext.Current.Server.MapPath("XmlFile.xml")); \n\nXmlNodeList xnList = xml.SelectNodes("/StudentList/student");\nforeach (XmlNode xn in xnList)\n{\n  string name= xn["name"].InnerText;\n  string Id= xn["Id"].InnerText;   \n}	0
33138878	33138762	How to use a Type variable as a Type Parameter in a loop?	foreach (Type t in Aplicables)\n{\n    filename = Path.Combine(dataDir, t.Name + "s.txt");\n    var prop = typeof(DataRef<>).MakeGenericType(t).GetProperty("DataList");\n    var dataList = prop.GetValue(null) as //List<int> or whatever your dataList is;\n    tempJson = JsonConvert.SerializeObject(dataList.ToArray());\n    System.IO.File.WriteAllText(filename, tempJson);\n}	0
3114193	3114155	Improve string camelization method	public static string Camelize(string text)\n    {\n        return CultureInfo.CurrentCulture.TextInfo.ToTitleCase(text.ToLower());\n    }	0
14629411	14629318	C# escape characters in user input	text = text.Replace(@"\r\n", Environment.NewLine);	0
32541277	32541151	C#: How to cancel the focus of a previousely focused text box?	private void textBox1_KeyPress(object sender, KeyPressEventArgs e)\n{\n    if (!char.IsDigit(e.KeyChar) && e.KeyChar != (char)Keys.Back)\n    {\n        e.Handled = true;\n        MessageBox.Show("Numbers only!" + "\n" + "Press ok to try again or Cancel to abort the operation", "Warning!");\n    }\n}	0
24896656	24895405	truncate to datagridview cells to significant digits while keeping datatable values the same	// doubleValueDataGridViewTextBoxColumn with precision = 2\n    // \n    this.doubleValueDataGridViewTextBoxColumn.DataPropertyName = "Double_Value_Data";\n    dataGridViewCellStyle2.Format = "N2";\n    dataGridViewCellStyle2.NullValue = null;\n    this.doubleValueDataGridViewTextBoxColumn.DefaultCellStyle = dataGridViewCellStyle2;\n    this.doubleValueDataGridViewTextBoxColumn.HeaderText = "Double_Value_Data";\n    this.doubleValueDataGridViewTextBoxColumn.Name = "doubleValueDataGridViewTextBoxColumn";	0
18319688	18319447	Remove duplicates with conditions using ASP.NET Regex	(<.+?\/>)(?=\1)	0
15198505	15198429	defining object location by it's center point	void resizeFromCenter(PictureBox box, int w, int h)\n{\n  var cenx = box.Left + box.Width/2;\n  var ceny = box.Top + box.Height/2;\n  box.Left = cenx - w/2;\n  box.Width = w;\n  box.Top = ceny - h/2;\n  box.Height = h;\n}	0
29461387	29454502	How do you create an SQLite Database with c# in Visual Studio?	using SQLite;\n// ...\n\npublic class Note\n{\n    [PrimaryKey, AutoIncrement]\n    public int Id { get; set; }\n    public string Message { get; set; }\n}\n\n// Create our connection\nstring folder = Environment.GetFolderPath (Environment.SpecialFolder.Personal);\nvar db = new SQLiteConnection (System.IO.Path.Combine (folder, "notes.db"));\ndb.CreateTable<Note>();\n\n// Insert note into the database\nvar note = new Note { Message = "Test Note" };\ndb.Insert (note);	0
29320580	29319253	How to make C# chart with two columns per one X value?	chart.Series.Clear();\n    chart.Series.Add("series 1");\n    chart.Series.Add("series 2");\n\n    for (int i = 0; i < alphabet.Length; i++)\n    {\n        DataPoint dp = new DataPoint();\n        dp.AxisLabel = alphabet[i].ToString();\n        dp.YValues = new double[] { freq[i] };\n\n        chart.Series[0].Points.Add(dp);\n\n\n\n        DataPoint dp1 = new DataPoint();\n        dp1.AxisLabel = alphabet[i].ToString();\n        dp1.YValues = new double[] { 100 };\n        chart.Series[1].Points.Add(dp1);\n    }	0
22391582	22142321	Get all triggers in Quartz.NET	var allTriggerKeys = sched.GetTriggerKeys(GroupMatcher<TriggerKey>.AnyGroup());\nforeach (var triggerKey in allTriggerKeys)\n{\n    ITrigger trigger = sched.GetTrigger(triggerKey);\n}	0
27539267	27539216	Set null object to a value	thisuser.FirstName = user.FirstName;\nthisuser.LastName = user.LastName;\nthisuser.UserName = user.UserName;\nthisuser.Password = user.Password;\n\nif (thisuser.Address == null)\n{\n    thisuser.Address = new Address();   // Make sure this is the type \n                                        // that Address should be\n                                        // This also assumes that Address is 1 to 1\n}\n\nthisuser.Address.City = user.Address.City;	0
15288308	15288187	How to fetch attribute values from Web.config XML file	XDocument document = XDocument.Load(fullPath);\nvar connectionString = from c in document.Descendants("connectionStrings").Descendants("add")\n    where c.Attribute("name").Value == "abc"                \n    select c;	0
539069	539003	Preventing Edits to specific rows in DataGridView	private void dataGridView3_CellBeginEdit(object sender, DataGridViewCellCancelEventArgs e) {\n    if (e.RowIndex < 3) {\n        e.Cancel = true;\n    }\n}\n\nprivate void dataGridView3_UserDeletingRow(object sender, DataGridViewRowCancelEventArgs e) {\n    if (e.Row.Index < 3) {\n        e.Cancel = true;\n    }\n}	0
16187701	16187631	Enumerate a databinding source, Instances in a custom Config Section	foreach(var item in EmailCustomSection.Instances)\n{\n   // do stuff with item\n}	0
31427243	31379996	Azure Slot Swapping: Configure WCF endpoint in Azure	wcfServiceClient.Endpoint.Address = new EndpointAddress(endPointAddress);	0
24620527	19271983	How can i make a js function interact with c# using webkit?	public class MyDerived: WebView\n{\n...\n\n    public const string COM_COMMAND_INIT = "http://mypresetcommand/?";\n    protected override void OnResourceRequestStarting(WebKit.WebFrame web_frame, WebKit.WebResource web_resource, WebKit.NetworkRequest request, WebKit.NetworkResponse response)\n    {\n        // check if this is a command\n        if (request.Uri.ToLower().StartsWith(COM_COMMAND_INIT))\n        {\n            // this is a com command. Responding with responce.\n            string cmnd = web_resource.Uri.Substring(COM_COMMAND_INIT.Length);\n            // HANDLE COMMAND HERE.\n            return;\n        }\n        base.OnResourceRequestStarting(web_frame, web_resource, request, response);\n    }\n}	0
34116373	34116014	Remove dynamic substring from string c#	string supposedToBeJson = "img_CB(\"imgCount\":31,\"imgHash\":\"[6ede94341e1ba423ccc2d4cfd27b9760]\",\"images\":{});";\n\nvar jobject = JObject.Parse(supposedToBeJson.Replace("img_CB(", "{").Replace(");", "}"));\n\nvar images = jobject.SelectToken("images");	0
34002585	34002362	c# Looping through directory, finding XML in each directory and, if & present replace with &amp; - Save	foreach (string d in Directory.GetFiles(targetDirectory, "*.xml", SearchOption.AllDirectories))\n{\n    String[] lines = File.ReadAllLines(d);\n    for (int i = 0; i < lines.Length; i++)\n    {\n        if (lines[i].Contains("&"))\n        {\n            lines[i] = lines[i].Replace("&", "&amp;");                             \n        }\n    }\n    System.IO.File.WriteAllLines(d, lines);\n}	0
11618904	11618865	Validating constructor parameters	public MyObjGroup(MyObj primaryObj) \n{\n    if(primaryObj == null) \n        throw new ArgumentNullException("value", "PrimaryObj cannot be null");\n}\n\npublic MyObjGroup(MyObj primaryObj, MyObj secondaryObj) \n    : this(primaryObj)\n{\n    SecondaryObj = secondaryObj;\n}	0
2765265	2765234	C# datatable to listview	foreach (DataRow row in data.Rows)\n{\n    ListViewItem item = new ListViewItem(row[0].ToString());\n    for (int i = 1; i < data.Columns.Count; i++)\n    {\n        item.SubItems.Add(row[i].ToString());\n    }\n    listView_Services.Items.Add(item);\n}	0
1940464	1940446	LINQ to SQL: Data from two unrelated tables, sorting on date	var query = context.Logins.Where( l => l.UserID == userID )\n                          .Select( l => new { Date = l.Date, What = "logged in" } )\n                  .Union( context.Actions.Where( a => a.UserID == userID )\n                                          .Select( a => new { Date = a.Date, What = a.Action  } ))\n                  .OrderBy( r => r.Date );	0
16012981	16012880	How to get selected value of dropdownlist in edititemtemplate - datagridview?	protected void gridview1_RowEditing(object sender, GridViewEditEventArgs e)\n        {\nGridViewRow row = gridview1.Rows[e.RowIndex];\n\n            DropDownList ddl = row.FindControl("DropDownList1") as DropDownList;\n        var value=ddl.SelectedValue;\n            //now do whatever with that value\n        }	0
24149671	24149471	How to insert into SQL table from a List	class CSVRow{\n         Dictionary<string, string> Values;\n          public CSVRow(string csvFields, string csvValues)\n            {\n                // iterate properly and fill the fields that contains values.\n            }\n         string ToInsert(){\n              string csvFields="Insert into csv123 (";\n               string csvValues="VAlues(";\n              foreach(KeyValuePair<string, string> entry in Values)\n               {\n\n                     if(string.isEmpty(entry.Value)==false){ //double check? probably not need it.\n                         // add the field to the insert and the value to the values.\n                         }\n              }\n\n            return csvFields + ") " + csvValues + ")";\n           }\n    }	0
10300071	10251092	How to read text transitions in a Powerpoint file via C#	With ActivePresentation.Slides(1).TimeLine.MainSequence\n\n  ' how many animations are there in the main sequence?\n  Debug.Print .Count\n\n  For x = 1 to .Count\n    ' What kind of effect is it?\n    Debug.Print .Item(x).EffectType\n    ' What shape is this animation applied to?\n    Debug.Print .Item(x).Shape.Name\n  Next\nEnd With	0
22557783	22557373	How to parse JSON response using Newtonsoft.JSON?	jsonClass posts2 = Newtonsoft.Json.JsonConvert.DeserializeObject<jsonClass>(result.ToString());	0
21351602	21351582	How to split among two different characters	var arr = "3*10^5".Split("*^".ToCharArray());	0
18372202	18360746	Can I add DataTable in DataGridView without using DataSource property	object[] _items = _row.ItemArray;	0
19613471	19568046	Keep Watin session alive	var IE = IE.AttachTo<IE>(Find.ByUrl(someURLHere));	0
25141539	25141235	How to open a file with out downloading it to my computer	private void OpenAttachment(DataGridViewCell dgvCell)\n    {\n        if (SelectedNonNullCellFromColumn(1))\n        {\n            string s = cncInfoDataGridView.Rows[dgvCell.RowIndex].Cells[5].Value.ToString(); // stores in string s\n            System.Diagnostics.Process.Start(s);   ///Open the file\n        }\n     }	0
16135929	16131670	List<Uri> How do I get at its contents?	matchString = Regex.Match(((Property)e.Item.FindControl("Property4")).Text, "<img.+?src=[\"'](.+?)[\"'].+?>", RegexOptions.IgnoreCase).Groups[1].Value;//image src	0
7596348	7559679	Sorting excel sheet in reverse order on basis of created time / reversing the excel sheet	Workbook wb = app.Workbooks.Open(Form1.strRecentFilename, temp, temp, temp, temp, temp, temp, temp, temp, temp, temp, temp, temp, temp, temp);\n        int count = wb.Worksheets.Count;\n        Worksheet ws, lastws;\n        lastws = (Worksheet)wb.Worksheets[count];\n        MessageBox.Show(lastws.Name);\n        for (int i = count - 1; i >= 1; i--)\n        {\n            lastws = (Worksheet)wb.Worksheets[count];\n            ws = (Worksheet)wb.Worksheets[i];\n            ws.Move(System.Reflection.Missing.Value, lastws);\n        }	0
12827010	12826760	Printing 2D array in matrix format	long[,] arr = new long[5, 4] { { 1, 2, 3, 4 }, { 1, 1, 1, 1 }, { 2, 2, 2, 2 }, { 3, 3, 3, 3 }, { 4, 4, 4, 4 } };\n\n        int rowLength = arr.GetLength(0);\n        int colLength = arr.GetLength(1);\n\n        for (int i = 0; i < rowLength; i++)\n        {\n            for (int j = 0; j < colLength; j++)\n            {\n                Console.Write(string.Format("{0} ", arr[i, j]));\n            }\n            Console.Write(Environment.NewLine + Environment.NewLine);\n        }\n        Console.ReadLine();	0
22444795	22444664	Access cell data in a DataGrid	var celldata=dataGrid1.SelectedCells[0];\nvar val=celldata.Column.GetCellContent(celldata.Item);	0
21829107	21828783	Entity Framework multiple search with empty variables?	List<ActivityLog> list = db.ActivityLog.Where(c => devicename == "" || c.Devices.devName.ToLower().Contains(devicename.ToLower()))\n                                               .Where(c => user == "" || c.Users.uName.ToLower().Contains(user.ToLower()))\n                                               .Where(c => alarm == "" || c.AlarmCodes.aName.ToLower().Contains(alarm.ToLower()))\n                                               .OrderBy(c => c.dateTime).Skip(skip).Take(pageSize).ToList();	0
28243526	28163215	Stomp WebSocket Client for a Spring based broker built in Java is failing	websocket.Send("SUBSCRIBE\nid:sub-0\ndestination:/topic/mytopic\n\n\0");	0
2021001	2020982	Getting firefox url	window.location.href	0
14371228	14371085	Plot a line (y = 2x + 7) on a graph	mathematical function plot library for windows	0
12257108	12257043	getting input from a user to fill a list in C#	Console.Writeline("Enter Item Prices\n");\n  List<double> items = new List<double>();\n  for (double i = 0; i < 100; i++)\n  {\n       string userInput;\n       double newItem;\n\n       // repeatedly ask for input from the user until it's a valid double\n       do \n       {\n           Console.Write(string.Format("Enter item #{0}: ", i));\n           // read from console into userInput\n           userInput = Console.ReadLine();\n       } while (!double.TryParse(userInput, out newItem))\n\n       // add the new item to the array\n       items.Add(newItem);\n  }\n\n  // output all the items to the console, separated by commas\n  Console.WriteLine(\n      string.Join(", ", \n          items.Select(item => item.ToString())\n      )\n  );	0
15992463	15992329	run an executable that was downloaded from blob into stream in c#	public static void RunBlob(ICloudBlob blob, string targetFilePath) {\n    using (var fileStream = File.OpenWrite(targetFilePath)) {\n        blob.DownloadToStream(fileStream);\n    }\n\n    var process = new Process() {StartInfo = new ProcessStartInfo(targetFilePath)};\n    process.Start();\n    process.WaitForExit(); // Optional\n}	0
2779656	2779628	How to create new file with path?	FileInfo fi = new FileInfo(@".\a\bb\file.txt");\nDirectoryInfo di = new DirectoryInfo(@".\a\bb");\nif(!di.Exists)\n{\n    di.Create();\n}\n\nif (!fi.Exists) \n{\n    fi.Create().Dispose();\n}	0
28682388	28681263	Marshal C# string to C++ tchar through streamwriter	using (NamedPipeClientStream pipeClient = new NamedPipeClientStream(".", "mynamedpipe", PipeDirection.InOut))\n{\n    pipeClient.Connect();\n    pipeClient.ReadMode = PipeTransmissionMode.Message;\n    var msg = Encoding.Unicode.GetBytes("Hello from Kansas!");\n    pipeClient.Write(msg, 0, msg.Length);\n}	0
14691608	14691502	Bind to a DependencyProperty in code (besides change notification)	// You need these instances\nvar yourViewModel = GetTheViewModel();\nvar yourView = GetYourView();\n\nBinding binding = new Binding("IsRequired");\nbinding.Source = yourViewModel;\nbinding.Mode = BindingMode.TwoWay;\nyourView.SetBinding(YourViewType.IsRequiredProperty, binding);	0
3698284	3698196	How do I check for a URL's top-level domain in ASP.NET/C#?	if (Request.Url.Host.ToLower().EndsWith(".fr"))\n  {\n    ...\n  }	0
2681137	2681120	Find Shortest element in Array	var orderedNames = names.OrderBy(name => name.Length);\n\nstring shortestName = orderedNames.First();\n\nstring[] otherNames = orderedNames.Skip(1).ToArray();	0
18670874	18670863	Convert text to string array with separator	string text = "1,2,5,6";\nstring[] textarray = text.split(',');	0
17151620	17151479	Exec proc with variables taken from c# text box's	private void buttonUpdateProfileClass_Click(object sender, EventArgs e) \n{\n    int ID = Convert.ToInt32(recordID.Text);\n    int oldPC = Convert.ToInt32(oldProfileClass.Text);\n    int NewPC = Convert.ToInt32(newProfileClass.Text);\n\n\n    string connstr = @"Initial Catalog=myDB;Data Source=localhost;Integrated Security=SSPI;";\n    SqlConnection conn = new SqlConnection(connstr);\n    conn.Open();\n\n    var cmd= new SqlCommand("dbo.updateclass", conn);\n    cmd.CommandType = CommandType.StoredProcedure;\n\n    cmd.Parameters.AddWithValue("@ID", ID);\n    cmd.Parameters.AddWithValue("@NEWCLASS", NewPC);\n    cmd.Parameters.AddWithValue("@OLDCLASS", oldPC); \n\n    cmd.ExecuteNonQuery();\n\n    cmd.Dispose();\n    conn.Close();\n    conn.Dispose();\n    MessageBox.Show("Profile Class updated");\n}	0
20303587	20302844	Interface for two methods that take different parameters	interface IWalker\n{\n    void Walker(object a=null, object b=null);\n}\n\nclass RegistryList: IWalker\n{\n    public void Walker(object a, object b){\n        var _key = (RegistryKey)a;\n        var _indent = Convert.ToInt32(b)\n        RegistryWalker(_key, _indent)\n    }\n\n    private void RegistryWalker(RegistryKey _key, int _indent)\n    { \n        ....\n    }\n}\n\nclass FileListIWalker\n{\n    public void Walker(object a=null, object b=null){\n        FileWalker();\n    }\n\n    public void FileWalker(){...}\n{	0
5597767	5597718	Url.RouteUrl from an Html helper extension	UrlHelper Url = new UrlHelper(helper.ViewContext.RequestContext);\nUrl.RouteUrl(???);	0
11218274	11210476	How to find certain strings in List<string> via LINQ?	var dist = test.Where(a => a == "1");	0
21590266	21570545	kentico accessing ui culture values programmitcally	// ResHelper\nusing CMS.GlobalHelper;\nusing CMS.SiteProvider;\n\n    // Get culture ID from query string\n    var uiCultureID = QueryHelper.GetInteger("UIcultureID", 0);\n\n    // Get requested culture\n    var ui = UICultureInfoProvider.GetSafeUICulture(uiCultureID);\n\n    var dui = UICultureInfoProvider.GetUICultureInfo(CultureHelper.DefaultUICulture);\n\n    var s = ResHelper.GetString("myculturevalue.test", dui.UICultureCode);	0
28615014	26350895	OData Expand fails on Client Win8.1 universal app	builder.EntitySet<Menus>("Menus");	0
25305679	25158908	How to refresh SQL Server database table during runtime in Visual Studio-2010?	void fill_datagrid()\n{\n     string ConString = "YOUR CONNECTION STRING";\n\n     string CmdString ;\n\n     SqlConnection con = new SqlConnection(ConString);\n\n\n     CmdString = "SELECT emp_id, emp_name from employee2";\n\n     SqlCommand cmd = new SqlCommand(CmdString, con);\n\n     SqlDataAdapter sda = new SqlDataAdapter(cmd);\n\n     DataTable dt = new DataTable("employee2");\n\n     sda.Fill(dt);\n\n     employee2DataGrid.ItemsSource = dt.DefaultView;\n\n}	0
1018624	1018407	What is the most elegant way to get a set of items by index from a collection?	public static IEnumerable<T> GetIndexedItems<T>(this IEnumerable<T> collection, IEnumerable<int> indices)\n{\n    int currentIndex = -1;\n    using (var collectionEnum = collection.GetEnumerator())\n    {\n        foreach(int index in indices)\n        {\n            while (collectionEnum.MoveNext()) \n            {\n                currentIndex += 1;\n                if (currentIndex == index)\n                {\n                    yield return collectionEnum.Current;\n                    break;\n                }\n            }\n        }    \n    }\n}	0
33860758	33860713	Get caret position in RichTextBox_Click event	private void richTextBox1_MouseUp(object sender, MouseEventArgs e)\n{\n        RichTextBox box = (RichTextBox)sender;\n        Point mouseLocation = new Point(e.X, e.Y);\n        box.SelectionStart = box.GetCharIndexFromPosition(mouseLocation);\n        box.SelectionLength = 0;\n        int selectionStart = richTextBox.SelectionStart;\n        int lineFromCharIndex = box.GetLineFromCharIndex(selectionStart);\n        int charIndexFromLine = box.GetFirstCharIndexFromLine(lineFromCharIndex);\n\n        currentLine = box.GetLineFromCharIndex(selectionStart) + 1;\n        currentCol = box.SelectionStart - charIndexFromLine + 1;\n}	0
4202216	4202195	Textbox validation in a Windows Form	private bool WithErrors()\n{\n    if(textBox1.Text.Trim() == String.Empty) \n        return true; // Returns true if no input or only space is found\n    if(textBox2.Text.Trim() == String.Empty)\n        return true;\n    // Other textBoxes.\n\n    return false;\n}\n\nprivate void buttonSubmit_Click(object sender, EventArgs e)\n{\n    if(WithErrors())\n    {\n        // Notify user for error.\n    }\n    else\n    {\n        // Do whatever here... Submit\n    }\n}	0
4052495	4052428	Ninject, how to inject an object living in the session into my business class?	Bind<Profile>()\n    .ToMethod(context => \n        HttpContext.Current.Session["Profile"] as Profile);	0
12459952	12459822	How can I make a button take up its entire containing form?	this.button.Dock = System.Windows.Forms.DockStyle.Fill;	0
12720285	12667606	Read excel using OLEDB	var reader = System.IO.File.OpenText(pathCopy);\nstring firstLine = reader.ReadLine();\nif (firstLine.IndexOf("html", StringComparison.InvariantCultureIgnoreCase) > 0)\n    //some stuff\nelse\n    //other stuff	0
22869124	22868953	Regex to get last 10 digits	Regex rgx = new Regex("\d*(\d{10})");\nrgx.Replace("013456547887", "$1");	0
2877829	2877661	Serializing data from a RSS feed in ASP.NET	using (var reader = XmlReader.Create(@"http://newsrss.bbc.co.uk/rss/newsonline_world_edition/front_page/rss.xml"))\n{\n    var feed = SyndicationFeed.Load(reader);\n    if (feed != null)\n    {\n        foreach (var item in feed.Items)\n        {\n            Console.WriteLine(item.Title.Text);\n        }\n    }\n}	0
27081057	27081009	How to update a table column where column name is dynamic	obj.GetType().GetProperty(field).SetValue(obj, newValue);	0
490598	490596	How to get "Guid" variable from http header in ASP.NET	try {\n    userId = new Guid(Request.QueryString["id"]);\n} catch (FormatException e) {\n    /*\n     * It's possible that the guid is not properly formatted and an\n     * exception will be thrown, so handle that here.\n     */\n}	0
30877933	30875408	Get TitleBar Caption of any application using Microsoft UI Automation?	class Program\n{\n    static void Main(string[] args)    \n    {\n        // start our own notepad from scratch\n        Process process = Process.Start("notepad.exe");\n        // wait for main window to appear\n        while(process.MainWindowHandle == IntPtr.Zero)\n        {\n            Thread.Sleep(100);\n            process.Refresh();\n        }\n        var window = AutomationElement.FromHandle(process.MainWindowHandle);\n        Console.WriteLine("window: " + window.Current.Name);\n\n        // note: carefully choose the tree scope for perf reasons\n        // try to avoid SubTree although it seems easier...\n        var titleBar = window.FindFirst(TreeScope.Children, new PropertyCondition(AutomationElement.ControlTypeProperty, ControlType.TitleBar));\n        Console.WriteLine("titleBar: " + titleBar.Current.Name);\n    }\n}	0
13814146	13813967	How to read XML file in Console app	var doc = new XmlDocument();\n            doc.Load(@"XmlFile.xml");\n\n            var root = doc.DocumentElement;\n\n            if (root == null)\n                return;\n\n            var books = root.SelectNodes("book");\n            if(books == null)\n                return;\n\nforeach (XmlNode book in books)\n                {\n                    var title = book.SelectSingleNode("title");\n                    var auth = book.SelectSingleNode("author");\n                    //And so on\n                }	0
7620498	7620422	Interface Downcasting	IList<T>	0
2317030	2317012	Attaching Image in the body of mail in C#	string attachmentPath = Environment.CurrentDirectory + @"\test.png";\n    Attachment inline = new Attachment(attachmentPath);\n    inline.ContentDisposition.Inline = true;\n    inline.ContentDisposition.DispositionType = DispositionTypeNames.Inline;\n    inline.ContentId = contentID;\n    inline.ContentType.MediaType = "image/png";\n    inline.ContentType.Name = Path.GetFileName(attachmentPath);\n\n    message.Attachments.Add(inline);	0
5674523	5674178	Singleton implementation	public class Singleton\n{\n    private static object _syncRoot = new object();\n\n    public Singleton Instance\n    {\n        get\n        {\n            if (_instance == null)\n            {\n                lock (_syncRoot)\n                {\n                    if (_instance != null)\n                       return _instance;\n\n                    _instance = new Singleton();\n                }\n            }\n            return _instance;\n        }\n    }\n\n    private Singleton() { }\n    private static Singleton _instance;\n}	0
7085871	7085566	How Ajaxcontroltookit website reloads a Label text Async?	protected void DropDownList3_SelectedIndexChanged(object sender, EventArgs e)\n{\n    // Get selected values\n    string make = DropDownList1.SelectedItem.Text;\n    string model = DropDownList2.SelectedItem.Text;\n    string color = DropDownList3.SelectedItem.Text;\n\n    // Output result string based on which values are specified\n    if (string.IsNullOrEmpty(make))\n    {\n        Label1.Text = "Please select a make.";\n    }\n    else if (string.IsNullOrEmpty(model))\n    {\n        Label1.Text = "Please select a model.";\n    }\n    else if (string.IsNullOrEmpty(color))\n    {\n        Label1.Text = "Please select a color.";\n    }\n    else\n    {\n        Label1.Text = string.Format("You have chosen a {0} {1} {2}. Nice car!", color, make, model);\n    }\n}	0
15804421	15798265	Load char array into data table	string arrayUp = "ABBAAAABABAAAB"; // Example value for rtb_up.Text\nstring arrayDown = "ABABAAABAB"; // Example value for rtb_down.Text\n\nDataTable dataTable = new DataTable();\n\n// Add variable number of columns, depending on the length of arrayUp\nfor (int i = 0; i < arrayUp.Length; i++)\n    dataTable.Columns.Add("");\n\n// Iterate through the "rows" first\nfor (int i = 0; i < arrayDown.Length; i++)\n{\n    DataRow dataRow = dataTable.NewRow();\n\n    // Then iterate through the "columns"\n    for (int j = 0; j < arrayUp.Length; j++)\n    {\n        if (arrayDown[i] == arrayUp[j])\n            dataRow[j] = "+";\n        else\n            dataRow[j] = "-";\n    }\n\n    dataTable.Rows.Add(dataRow);\n}\n\ndgv_main.AutoGenerateColumns = true;\ndgv_main.DataSource = dataTable;	0
512685	512642	ZedGraph - I am looking for an example of using a DateTime	public XDate ConvertDateToXdate(DateTime date)\n{\n  return new XDate(date.ToOADate);\n}	0
6525263	6524052	Populating Gridview with DropDownList	dropdownlist.DataSource = DataContext.Years;\ndropdownlist.DataValueField = "YearId";\ndropdownList.DataTextField = "Year";\ndropdownlist.DataBind();	0
19396640	19396453	How can I make a filter case insensitive?	bool contains = false;\n\n        for (int i = 0; i < lbxUnsortedList.Items.Count; i++)\n        {\n            if (lbxUnsortedList.Items[i].ToString().ToLower() == this.tbxAddWord.Text.ToString().ToLower())\n            {\n                contains = true;\n            }\n\n        }\n\n        if (!contains)\n        {\n            //your code\n        }\n        else\n        {\n            MessageBox.Show("The word that you have added is already on the list");\n            tbxAddWord.Text = "";\n            tbxAddWord.Focus();\n\n        }	0
30726306	30726274	Runtime set property from a string	Microsoft.CSharp.CSharpCodeProvider	0
12250443	12250385	entity framework - select TOP of both tables in a JOIN	_context.Albums.Select(m => new {\n     album = m,\n     pictures = m.Pictures.Take(5)\n}).Take(10);	0
31032235	31031747	Change GameObject variable value on changing scene Unity c#	Application.LoadLevel("level2");	0
30751093	30749488	How to update a progress bar based on a form in WinRT?	private string _name = "";\n    public string Name\n    {\n        get\n        {\n            return _name;\n        }\n\n        set\n        {\n            if (_name == value)\n            {\n                return;\n            }\n            _name = value;\n            OnPropertyChanged();\n            Window.Current.Dispatcher.RunAsync(CoreDispatcherPriority.Low, () =>\n            {\n                ProgressPercent += 10; //handle the fact that this needs to be added once using a bool or something \n            });\n\n        }\n    }	0
23739511	21119111	change page css file on load	HtmlLink subcss = new HtmlLink();\n        subcss.Href = name of css file as sting;\n        subcss.Attributes.Add("rel", "stylesheet");\n        subcss.Attributes.Add("type", "text/css");\n        Page.Header.Controls.Add(subcss);	0
30719258	30718802	How to "sign" a big string to be identified later?	GetHashCode()	0
3497829	3497699	CSV to object model mapping	from line in File.ReadAllLines(fileName).Skip(1)\nlet columns = line.Split(',')\nselect new\n{\n  Plant = columns[0],\n  Material = int.Parse(columns[1]),\n  Density = float.Parse(columns[2]),\n  StorageLocation = int.Parse(columns[3])\n}	0
32079080	32078328	Copy Xml nodes in other Xml nodes	XDocument d = XDocument.Parse(xml);\n        var students = d.Descendants("student").ToList();\n        var student101 = students.First(i => i.Element("identity").Element("key").Value == "101");\n\n        foreach (var student in students)\n        {\n            student.Descendants("information").Single().ReplaceWith(student101.Descendants("information").Single());\n        }\n\n        var x = d.ToString();	0
594057	593170	TableAdapter - updating without a key	var updateCommand = new SqlCommand();\n  ...	0
3502334	3502311	How to play a sound in C#, .NET	System.Media.SoundPlayer player = new System.Media.SoundPlayer(@"c:\mywavfile.wav");\nplayer.Play();	0
30137260	30137080	Limit the page numbers to show on Custom Paging	if (pageCount > 0)\n{\n    int showMax = 10;\n    int startPage;\n    int endPage;\n    if (pageCount <= showMax) \n    {\n        startPage = 1;\n        endPage = pageCount;\n    }\n    else\n    {\n        startPage = currentPage;\n        endPage = currentPage + showMax - 1;\n    }\n\n    pages.Add(new ListItem("First", "1", currentPage > 1));\n\n    for (int i = startPage; i <= endPage; i++)\n    {\n        pages.Add(new ListItem(i.ToString(), i.ToString(), i != currentPage));\n    }\n\n    pages.Add(new ListItem("Last", pageCount.ToString(), currentPage < pageCount));\n}	0
20473176	20472898	Saving two lists to xml file	var xEle = new XElement("Parent");\nxEle.Add(new XElement("Child"));\nxEle.Add(new XElement("Child2"));	0
4541136	4541096	importing a c dll function into c#	[DllImport("cDLLfile.dll", CharSet = CharSet.Ansi, SetLastError = true, ExactSpelling = true) ]\nprivate static extern short Function(ushort a, UInt32 b, UInt32 c, ushort[] buffer);	0
16966458	16966393	trying to use switch statement in C#	string myType= ((TextBox)DV_LogAdd.FindControl("txtType")).Text.ToString();\n        int updateType = 0;\n        switch (myType)\n        {\n            case "TypeA":\n                updateType = 1;\n                break;\n            case "TypeB":\n                updateType = 2;\n                break;\n            case "TypeC":\n                updateType = 3;\n                break;\n            default :\n                throw new ArgumentException("txtType value not supported :"+myType);\n        }	0
12837412	12837305	Cross-thread operation not valid (How to access WinForm elements from another module events?)	FormContaingTheTextbox.Invoke(new MethodInvoker(delegate(){\n    textBox1.Text += " val: " + myval.ToString() + " ";\n}));	0
20856814	20856775	Controller is not detecting Model	using OfficeAuto.Models;	0
29668522	29668329	Select substring after specific word	string s ="<iframe width=\"560\" height=\"315\" src=\"https://www.youtube.com/embed/KRFHiBW9RE8\" frameborder=\"0\" allowfullscreen></iframe>";\nvar match = Regex.Match(s, "src=\"(.*?)\"");\nstring src;\nif (match.Success)\n    src = match.Groups[1].Value;	0
6005464	6005441	Paging in ASP web page?	PageSize=3	0
21424125	21410186	Runtime generated controls disabled for Async Postback asp.net	ScriptManager.GetCurrent().RegisterPostBackControl(grd_Reports);	0
23344166	23343965	How to use contain clause to query multiple parameters?	data = data.Where(c => list.Any(a => c.NAME.Contains(nameArg)).Where(c => list.Any(a => c.TAG.Contains(tagArg)));	0
16810729	16810434	Hide items before selected index of another combobox	var result = source.Where((x, index) => index > SelectedIndex);	0
23908965	23908844	WPF application OnExit event	public partial class App\n{\n    private MainWindow _mainWindow;\n\n    ...\n}	0
16417308	16417222	IndexOutOfRange Exception while accessing two columns from an access database	string selectString = "SELECT usernam, passwd FROM Table1";	0
29698336	29698196	Creating array consisting of struct values	Console.WriteLine(newarray[0].Name);	0
3608088	3607900	Condensing linq expressions into one expression for a simple blog system	var blogs = from blog in db.BlogPosts\n            join categories in db.BlogCategories\n                on blog.Fk_Category_Id equals category.Id\n            select new\n            {\n                blog,\n                categories,\n                tags = from juncTags in db.Junc_BlogTags\n                       join tags in db.Tags\n                           on juncTags.FK_Tag_Id equals tags.Id\n                       where juncTags.Fk_BlogPost_Id = blog.Id\n                       select tags\n            };	0
13641327	13640062	Listen socket listens only once	static void Main(string[] args)\n{\n    Socket s = new Socket(SocketType.Stream, ProtocolType.TCP);\n    Socket cl = null;\n    System.Net.IPEndPoint endpoint = new System.Net.IPEndPoint(0, 400); // listen on all adapters on port 400\n    s.Bind(endpoint);\n\n    s.Listen(BACKLOG);\n\n    byte[] rcvBuffer = new byte[BUFFSIZE];\n\n    for (; ; )\n    {\n        string text = "";\n\n        Console.Clear();\n        cl = s.Accept();\n        Console.Write("Handling Client >> " + cl.RemoteEndPoint + "\n\n\n");\n        cl.Receive(rcvBuffer, BUFFSIZE, SocketFlags.None);\n        text = Encoding.ASCII.GetString(rcvBuffer, 0, BUFFSIZE).TrimEnd('\0');\n        Console.Write(text);\n        cl.Close();\n    }\n}	0
1326115	1326096	How to determine whether code is getting executed in a console app or in a windows service	if (Environment.UserInteractive)\n{\n    Console.WriteLine("Hi I'm being ran as a console app");\n}	0
4339286	4338700	Finding Out what Interfaces are Queryable for a COM Object?	object unknown = //your com object...\n\n    Type someComObjectType = typeof(ExampleTypeInInteropAssembly);\n\n    Assembly interopAssembly = someComObjectType.Assembly;\n\n    Func<Type, bool> implementsInterface = iface =>\n    {\n        try\n        {\n            Marshal.GetComInterfaceForObject(unknown, iface);\n            return true;\n        }\n        catch (InvalidCastException)\n        {\n            return false;\n        }\n    };\n\n    List<Type> supportedInterfaces = interopAssembly.\n        GetTypes().\n        Where(t => t.IsInterface).\n        Where(implementsInterface).\n        ToList();\n\n    if (supportedInterfaces.Count > 0)\n    {\n        supportedInterfaces.ForEach(Console.WriteLine);\n    }\n    else\n    {\n        Console.WriteLine("No supported interfaces found :(");\n    }	0
21555770	21555738	Before saving in database I want the string to be free from any special characters and escape sequences?	public String addescape(String str)\n{\n    String temp = "";\n    foreach (char ch in str)\n    {\n\n        if (ch == '\0')\n            temp += "";\n        else if (ch == '\'')\n            temp += "&#39;";\n        else if (ch == '\\')\n            temp += "&#34;";\n        else if (ch == '<')\n            temp += "&lt;";\n        else if (ch == '>')\n            temp += "&gt;";\n        else\n            temp += ch;\n    }\n    return (temp);\n}	0
2541209	2541184	Using a Type object to create a generic	// Your code\nType elType = Type.GetType(obj);\nType genType = typeof(GenericType<>).MakeGenericType(elType);\nobject obj = Activator.CreateInstance(genType);\n\n// To execute the method\nMethodInfo method = genType.GetMethod("MyMethod",\n    BindingFlags.Instance | BindingFlags.Public);\nmethod.Invoke(obj, null);	0
24546734	24546687	Finding a string in a string in C# with any char at some points	var text = "This is 1x6 in a string.";\n\nvar result = Regex.Replace(text, "1.6", "hello");	0
6918031	6791311	trying to show the two graphs on same page	targetChartControl.Series[0]	0
386924	386867	Regex Replace to assist Orderby in LINQ	List<Adaptation> result =\n  dbContext.Adaptation\n  .Where(aun => aun.EventID = iep.EventID)\n  .ToList();\n\nresult.ForEach(aun =>\n  aun.Name = Regex.Replace(aun.Name,\n    @"ADAPT([0-9])$", @"ADAPT0$1")\n);\nresult = result.OrderBy(aun => aun.Name).ToList();	0
3483071	3475807	DataGridView save filtering after reload	DataGridViewColumn oldColumn = dataGridView1.SortedColumn;\n\n   ListSortDirection direction;\n   if (dataGridView1.SortOrder == SortOrder.Ascending) direction = ListSortDirection.Ascending;\n   else direction = ListSortDirection.Descending;\n\n   databaseUpdateFunction();\n\n   DataGridViewColumn newColumn = dataGridView1.Columns[oldColumn.Name.ToString()];\n   dataGridView1.Sort(newColumn,direction);\n   newColumn.HeaderCell.SortGlyphDirection =\n                    direction == ListSortDirection.Ascending ?\n                    SortOrder.Ascending : SortOrder.Descending;	0
1403109	1403083	C#: Strip Illegal Chars from a filename string	string name = "tru\\e.jpg";\nchar[] invalidChars = System.IO.Path.GetInvalidFileNameChars();\nstring invalidString = Regex.Escape(new string(invalidChars));\nstring valid = Regex.Replace(name, "[" + invalidString + "]", "");\nConsole.WriteLine(valid);	0
9286493	6022137	Windows Forms Separator Control	public partial class Line : Label\n{\n    public override bool AutoSize\n    {\n        get\n        {\n            return false;\n        }\n    }\n\n    public override Size MaximumSize\n    {\n        get\n        {\n            return new Size(int.MaxValue, 2);\n        }\n    }\n\n    public override Size MinimumSize\n    {\n        get\n        {\n            return new Size(1, 2);\n        }\n    }\n\n    public override string Text\n    {\n        get\n        {\n            return "";\n        }\n    }\n\n    public Line()\n    {\n        InitializeComponent();\n        this.AutoSize = false;\n        this.Height = 2;\n        this.BorderStyle = BorderStyle.Fixed3D;\n    }\n}	0
32207881	32207768	Parse data from JSON API(URL) c#	MessageBox.Show(user.callsign);	0
12184358	12184309	C# Access a method from one class, and not another	namespace C.D\n{\n    class B\n    {\n        internal int a;\n        internal int b;\n\n        public B()\n        {\n        }\n    }\n}	0
21529519	21529426	How to Deserialize JSON	public class AuthResponse {\n    public bool LoginResult { get; set; }\n}\n\nvar deserializedResponse = JsonConvert.DeserializeObject<AuthResponse>(strResult);	0
25946217	25946108	C# - MySQL - Get value from column if status is 'a'	MySqlDataReader dr = command6.ExecuteReader();\nList<string> data=new List<string>();\nwhile (dr.Read())\n{\n    data.Add(dr["123"].ToString());        \n}	0
1922770	1905766	How determine css text of each node in html	HTMLDocument doc = (HTMLDocument)axWebBrowser1.Document;\n        var body = (HTMLBody)doc.body;//current style\n\n        var childs = (IHTMLDOMChildrenCollection)body.childNodes;\n        var currentelementType = (HTMLBody)childs.item(0);\n        var width = currentelementType.currentStyle.width;	0
2961789	2961772	How to deal with duplicate anonymous type member conflicts?	new {Name = i.Name, targetName = i.Target.Name, ... };	0
3175472	3175461	Given a List<int> how to create a comma separated string?	List<int> myListOfInt = new List<int> { 1, 2, 3, 4 };\n\nstring result = string.Join<int>(", ", myListOfInt);\n\n// result == "1, 2, 3, 4"	0
6662607	6662247	Accessing SMTP Mail Settings from Web.Config File by using c#	Configuration configurationFile = WebConfigurationManager.OpenWebConfiguration(Request.ApplicationPath);\nMailSettingsSectionGroup mailSettings = configurationFile.GetSectionGroup("system.net/mailSettings") as MailSettingsSectionGroup;\n\nResponse.Write(mailSettings.Smtp.Network.Host);	0
9570535	9565040	Insert with Linq-to-SQL sometimes fails	public void SaveParentAndChildren()\n{\n  using (CustomDataContext myDC = new CustomDataContext())\n  {\n    Parent p = new Parent();\n    Child c = new Child();\n    p.Children.Add(c);\n    myDC.Parents.InsertOnSubmit(p); //whole graph is now tracked by this data context\n    myDC.SubmitChanges(); // whole graph is now saved to database\n    // or nothing saved if an exception occurred.\n\n  }  //myDC.Dispose is called for you here whether exception occurred or not\n}	0
16133401	16132752	How do I alter the value being updated in a ListView?	protected void ListView2ItemUpdating(object sender, ListViewUpdateEventArgs e)\n{\n  using (var myEntities = new i96X_utilEntities())\n  {\n    var myPlotColour = (from plotC in myEntities.PlotColours\n                        where plotC.ID == selectedID\n                        select plotC).Single();\n    myPlotColour.PlotColour1 = ColourChosen.Value;\n    myEntities.SaveChanges();\n  }\n}	0
10982093	10978961	WCF Restful service file upload with multi-platform support	public void FileUpload(string fileName, Stream fileStream)\n{\n    FileStream fileToupload = new FileStream("c:\\FileUpload\\" + fileName, FileMode.Create);\n\n    byte[] bytearray = new byte[10000];\n    int bytesRead, totalBytesRead = 0;\n    do\n    {\n        bytesRead = fileStream.Read(bytearray, 0, bytearray.Length);\n        totalBytesRead += bytesRead;\n    } while (bytesRead > 0);\n\n    fileToupload.Write(bytearray, 0, bytearray.Length);\n    fileToupload.Close();\n    fileToupload.Dispose();\n}\n\n[ServiceContract]\npublic interface IImageUpload\n{\n    [OperationContract]\n    [WebInvoke(Method = "POST", UriTemplate = "FileUpload/{fileName}")]\n    void FileUpload(string fileName, Stream fileStream); \n}	0
5317000	5278414	Deep serialization of LINQ to SQL objects	string cacheKey = "apSpace_GetActiveSpacesForPerson_PersonID:" + personid;\nList<apSpace> list = MemCached.Get<List<apSpace>>(cacheKey);\nif (list == null)\n{\n    //Some complex, intensive query...\n    list = (from s in BaseDB.apSpaces\n            from so in BaseDB.apSpaceOwners\n            from sp in BaseDB.apSpacePersons\n            where (so.PersonID == personid\n            && so.SpaceID == s.SpaceID\n            && s.Deleted == false\n            && s.IsArchived == false)\n            || (sp.PersonID == personid\n            && sp.SpaceID == s.SpaceID\n            && s.Deleted == false\n            && s.IsArchived == false)\n            select s).Distinct().OrderBy(s => s.Name).ToList();\n    //Cache the query result\n    MemCached.Store(cacheKey, list);\n}\nelse\n    BaseDB.apSpaces.AttachAll(list); //Attach immediately!\n\nreturn list;	0
3862657	3752094	zip files in server	// prepare MemoryStream to create ZIP archive within\nusing (MemoryStream ms = new MemoryStream())\n{\n    // create new ZIP archive within prepared MemoryStream\n    using (ZipArchive zip = new ZipArchive(ms))\n    {            \n         // add some files to ZIP archive\n         zip.Add(@"c:\temp\testfile.txt");\n         zip.Add(@"c:\temp\innerfile.txt", @"\subfolder");\n\n         // clear response stream and set the response header and content type\n         Response.Clear();\n         Response.ContentType = "application/zip";\n         Response.AddHeader("content-disposition", "filename=sample.zip");\n\n         // write content of the MemoryStream (created ZIP archive) \n         // to the response stream\n         ms.WriteTo(Response.OutputStream);\n    }\n}\n\n// close the current HTTP response and stop executing this page\nHttpContext.Current.ApplicationInstance.CompleteRequest();	0
5466050	5464432	Refresh Bound Datagridview	private void LoadCaseNumberKey(String CaseNumberKey)\n{//do your stuff loading to datagrid }\n\n\n        private void cmdAdd_Click(object sender, EventArgs e) {          DataClasses1DataContext db = new DataClasses1DataContext();         \n    MuniLien newlien = new MuniLien();\n    newlien.CaseNumberKey = caseNumberKeyTextBox.Text;\n\n    db.MuniLiens.InsertOnSubmit(newlien);\n    db.SubmitChanges();  \n    this.muniLiensDataGridView.EndEdit(); \n    this.muniLiensDataGridView.Refresh();      \n\n    // add this if it is the way you bind datagrid -->> LoadCaseNumberKey(String CaseNumberKey)\n    or\n    //LoadData();\n\n}	0
10983357	10983344	one digit after a round number	move.ToString("+0.0;-0.0;0.0")	0
33569463	33548858	SonarQube Execution Failure Cannot find the assembly	sonar.cs.fxcop.assembly	0
5638944	5638625	Control no longer gaining focus after putting it in a splitcontainer	splitContainer1.Focus();\nsplitContainer1.ActiveControl = textBox1;	0
2114723	2113739	How to compare two lists of objects using moq with mspec (BDD style)	public override bool Equals(object obj)\n{\n    if (((Data)obj).a.Equals(this.a))\n        return true;\n\n    return false;\n}	0
7413286	7413107	Excel image in a cell	object missing = System.Reflection.Missing.Value;\nExcel.Range picPosition = GetPicturePosition(); // retrieve the range for picture insert\nExcel.Pictures p = yourWorksheet.Pictures(missing) as Excel.Pictures;\nExcel.Picture pic = null;\npic = p.Insert(yourImageFilePath, missing);\npic.Left = Convert.ToDouble(picRange.Left);\npic.Top = picRange.Top;\npic.Placement = // Can be any of Excel.XlPlacement.XYZ value	0
22140280	22132350	Compare items of List<Object> to other elements in the list	var smallestValue = list.SingleOrDefault(arg => arg.intVar== list.Min(arg => arg.intVar)	0
24552120	24541166	Start one of multiple startup projects before all others are finished building	In order to change build order just right click the Solution node and select \n"Project Build Order"	0
10055526	10054556	How to GET list based on a string input	string uriGetGroupsCollection = \n     "http://localhost:8000/Service/GetGroupsCollection/{TagName}";\n\nprivate void button6_Click(object sender, EventArgs e)\n{\n    string tagUri = uriGetGroupsCollection.Replace("{TagName}", textbox1.text);\n    XDocument xDoc = XDocument.Load(tagUri);\n    ...\n}	0
10642891	10642799	Changing Image from a control in another form	public Image picboximage \n{\n    get { return pictureBox23.Image; }\n    set { pictureBox23.Image = value; }\n}	0
5675102	5660380	updating a column depending on checkbox value	for (int i = 0; i < GridViewOrder.Rows.Count; i++)\n        {\n            CheckBox ck = (CheckBox)GridViewOrder.Rows[i].Cells[0].FindControl("CheckBoxATH");\n            Label orderID = (Label)GridViewOrder.Rows[i].Cells[5].FindControl("LabelOrderID");\n\n            if (ck != null)\n            {\n                string conn = "Data Source=pc-...";\n                System.Data.SqlClient.SqlConnection sqlConn = new System.Data.SqlClient.SqlConnection(conn);\n                sqlConn.Open();\n                System.Data.SqlClient.SqlCommand updateCommand = new System.Data.SqlClient.SqlCommand("UPDATE tblOrders SET tOrderATH = '" + ck.Checked + "' WHERE tOrderId= '" + orderID.Text + "'", sqlConn);\n                updateCommand.Parameters.AddWithValue("@orderID", orderID.Text);\n                updateCommand.ExecuteNonQuery();\n            }\n        }	0
11475264	11443322	NameSpace Manager or XsltContent to parse aspx page	HtmlAgilityPack.HtmlDocument htmlDoc = new HtmlAgilityPack.HtmlDocument();\n\nstring filePath = @"C:\webform4.aspx";\n\nhtmlDoc.Load( filePath );\n\nvar aspNodes = htmlDoc.DocumentNode.Descendants().Where( n => n.Name.StartsWith( "asp:" ) );\n\nforeach ( var aspNode in aspNodes ) {\n    Console.WriteLine( "Element: {0} Id: {1}", aspNode.Name, aspNode.Attributes["Id"].Value );\n}	0
5993476	5993265	How can I use Tasks in this context?	private void cmbPlatform_SelectedIndexChanged(object sender, EventArgs e)\n{\n    var uiContext = TaskScheduler.FromCurrentSynchronizationContext();\n    string platform = cmbPlatform.Text;\n    UpcomingGameFinder gameFinder = new UpcomingGameFinder();\n    Task.Factory.StartNew<IEnumerable<Game>>(() => gameFinder.FindUpcomingGamesByPlatform(platform))\n        .ContinueWith((i) => PlaceGameItemsInPanel(i.Result), uiContext);        \n}	0
12085845	12085821	How to parse string to DateTime?	DateTime date = DateTime.ParseExact(EnteredDate, "MM/dd/yyyy",\n                                    CultureInfo.InvariantCulture);\n\nvar dates = Products.Where(d => d.CreateDate >= date);	0
22866310	22862291	how to set picturebox image location from zip without extrat?	ZipFile zip = new ZipFile("data.zip");\nusing (Stream s = zip["p3.png"].OpenReader())\n{\n    Bitmap bitmap= new Bitmap(s);\n    PictureBox picturebox.Image = bitmap;\n}	0
19371027	19370546	string format negative hexadecimal	String FormatByte(sbyte b) {\n    return (b & 0x80) == 0x80 ? String.Format("-${0}", -b) : String.Format("${0:X}", b);\n    }	0
4589944	4589912	Add custom message to unit test result	System.Diagnostics.Trace.WriteLine("Hello World");	0
16526020	16525947	How to get a Lookup from nested dictionaries	var cols = (from a in binary_transaction_model\n            from b in a.Value\n            where b.Value == true\n            select new { aKey = a.Key, bKey = b.Key })\n            .ToLookup(x => x.bKey, x => x.aKey);	0
1785573	1785271	Debug Techniques: Visual Studio 2008 Process fatal crash after debug of WPF application	devenv.exe /ResetSettings\ndevenv.exe /ResetSkipPkgs \ndevenv.exe /Setup	0
10518496	10451296	Add new row in a datagridview	//define datatable (with all columns you want to have)...\n  DataRow dr;\n  int lastRow = this.dataGridView1.Rows.Count-2;\n  for(int i=0;i<dataGridView1.Columns.Count; i++)\n  {\n     // grab the values from the last row cells.\n     dr[i] = dataGridView1[i, lastRow].Value;\n   }\n     dataTable.Rows.Add(dr);	0
31957793	26710579	How to show dropshadow on drawingcontext tools	RenderTargetBitmap bmp = new RenderTargetBitmap((int)width, (int)(height), DpiX, DpiY, PixelFormats.Default);\nBitmapSource source = null;\n\nif (bmp != null)\n{\n    bmp.Render(image);\n    bmp.Render(drawingCanvas);\n    source = bmp;\n}	0
11091192	11091122	C# Regex To Escape Certain Characters	resultString = Regex.Replace(subjectString, \n    @"(?<!      # Match a position before which there is no\n     (?<!\\)    # odd number of backlashes\n     \\         # (it's odd if there is one backslash,\n     (?:\\\\)*  # followed by an even number of backslashes)\n    )\n    (?=[%'])    # and which is followed by a % or a '", \n    @"\", RegexOptions.IgnorePatternWhitespace);	0
22035191	22034937	How to pragmatically select tabPage2 of tabControl1 in C# in serialPort1 receiveData event?	// This delegate enables asynchronous calls\ndelegate void SetIndexCallback(string text);\n\n    private void serialPort1_DataReceived(object sender, SerialDataReceivedEventArgs e)\n    {\n\n    if (this.tabControl1.InvokeRequired)\n    {   \n            SetIndexCallback d = new SetIndexCallback(SetText);\n        this.Invoke(d, new object[] { text });\n    }\n    else\n    {\n        tabControl1.SelectedIndex = int(text);\n    }\n}	0
1268773	1268766	Writing file to web server - ASP.NET	protected void TestSubmit_ServerClick(object sender, EventArgs e)\n{\n  using (StreamWriter _testData = new StreamWriter(Server.MapPath("~/data.txt"), true))\n {\n  _testData.WriteLine(TextBox1.Text); // Write the file.\n }         \n}	0
11621751	11620227	Windows8 - Using localised string in C#	var loader = new Windows.ApplicationModel.Resources.ResourceLoader();\nstring result = loader.GetString("noResults/text");	0
10907520	10907510	How do you use collection initializers to create a new dictionary?	Dictionary<int, bool> b = new Dictionary<int, bool>() {\n   {1, true},{2, false},{3, true}\n};	0
26594643	26594566	How to change the format of the calender in c#.net	Label1.Text = Label1.Text + Calendar1.SelectedDate.ToString("dd-MM-yyyy");	0
27506375	27506050	Waiting for specific time before accepting client connexion TCPLISTENER	// Process the client connection.\npublic static void DoAcceptTcpClientCallback(IAsyncResult ar)\n{\n    // Get the listener that handles the client request.\n    TcpListener listener = (TcpListener)ar.AsyncState;\n\n    // Wait a while\n    Thread.Sleep(10 * 1000);        \n\n    // End the operation and display the received data on \n    // the console.\n    TcpClient client = listener.EndAcceptTcpClient(ar);\n\n    // ...\n}	0
32002064	32000094	No Book Results from ISBNDB with Valid ISBN	textBarcode.BeginInvoke(new Action(() => { \n   textBarcode.Text = bCode;\n   GetXMLBarcodeData();\n}));	0
25946196	25946129	Create derived classes with parameterized constructors using factory method with type parameter	public static T Create<T>(int number) where T : Base\n{\n    return (T) Activator.CreateInstance(typeof (T), number);\n}	0
13879857	13879789	x64 Application Accessing mdb database	Provider=Microsoft.ACE.OLEDB.12.0;Data Source=yourPathToTheMDBFile.mdb;\nPersist Security Info=False;	0
22565793	22565767	How do I convert Regex object to string	htmlcode1 = match.Groups["link"].Value;	0
34276761	34274568	How to read an xml file by using xmlreader in c#	using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing System.Xml;\nusing System.Xml.Linq;\n\nnamespace ConsoleApplication61\n{\n    class Program\n    {\n        const string FILENAME = @"c:\temp\test.xml";\n        static void Main(string[] args)\n        {\n            XmlReader reader = XmlReader.Create(FILENAME);\n            reader.MoveToContent();\n            string nsUn = reader.LookupNamespace("un");\n            while (!reader.EOF)\n            {\n                reader.ReadToFollowing("ExternalUtranCell", nsUn);\n                if (!reader.EOF)\n                {\n                    XElement cell = (XElement)XElement.ReadFrom(reader);\n                }\n            }\n\n\n        }\n    }\n\n}	0
11300820	11300739	Parse XML string to class in C#?	XmlSerializer serializer = new XmlSerializer(typeof(Book));\nusing (StringReader reader = new StringReader(xmlDocumentText))\n{\n    Book book = (Book)(serializer.Deserialize(reader));\n}	0
17946996	17946862	How to validate if a string is a regular expression?	try { Regex reg = new Regex(userDefinedValidation); } \ncatch (ArgumentException) { /* not a regex */ }	0
5494914	5494651	saving data from a query as a csv file	SaveFileDialog saveFileDialog1 = new SaveFileDialog();\n        string filter = "CSV file (*.csv)|*.csv| All Files (*.*)|*.*";\n        saveFileDialog1.Filter = filter;\n        const string header = "Animal_Name,Hair,Feathers,Eggs,Milk,Airborne,Aquatic,Predator,Toothed,Backbone,Breathes,Venomous,Fins,Legs,Tail,Domestic,Catsize,Type";\n        StreamWriter writer = null;\n\n        if (saveFileDialog1.ShowDialog() == DialogResult.OK)\n        {\n            filter = saveFileDialog1.FileName;\n            writer = new StreamWriter(filter);\n\n            writer.WriteLine(header);\n\n            writer.Close();\n        }	0
18668630	18668367	How to retrieve the XML query in asp.net page?	using (System.Data.SqlClient.SqlConnection c = new SqlConnection(ConfigurationManager.ConnectionStrings["fbgame"].ConnectionString))\n    using (System.Data.SqlClient.SqlCommand cmd = c.CreateCommand())\n    {\n        cmd.CommandText = "procGetPlayerScore";\n        cmd.CommandType = CommandType.StoredProcedure;\n\n        c.Open();\n\n        System.Xml.XmlReader r = cmd.ExecuteXmlReader();\n        XmlDocument document = new XmlDocument();\n        document.Load(r);\n\n        Response.ContentType = "text/xml";\n        document.Save(Response.Output);\n\n        c.Close();\n    }\n}	0
25299960	25299889	Customize MapHttpAttributeRoutes for Web Api Versioning	[VersionedRoute("api/Customer", 1)]\npublic class CustomerVersion1Controller : ApiController\n{\n    // controller code goes here\n}\n[VersionedRoute("api/Customer", 2)]\npublic class CustomerVersion2Controller : ApiController\n{\n    // controller code goes here\n}	0
18962665	18790135	Access to a Sharepoint Remote Folder from C#	PinvokeWindowsNetworking.connectToRemote(@"\\tests.sharepoint.es\folder1", "domain\user", "password");\n//manage files and folders of my remote resource\n//...\nPinvokeWindowsNetworking.disconnectRemote(@"\\tests.sharepoint.es\folder1");	0
5977527	5977485	How to get part of model expression points to in strongly typed HtmlHelper extension	TValue val = expression.Compile()(htmlhelper.ViewData.Model);	0
4955887	4955798	Sliding an image with fixed header and footer in WP7	SlideTransition slideTransition = new SlideTransition();\n    ITransition transition = slideTransition.GetTransition(TargetImage);\n    transition.Completed += delegate\n    {\n        transition.Stop();\n    };\n    transition.Begin();	0
8754275	8754147	cropping a image	File.IO.Delete	0
10006370	9995834	How would be this design about access data?	public interface IFooRepository\n{\n   void Save(Foo);\n   Foo GetById(int id);\n   Foo GetByLevel(int level) \n}\n\n public class FooXmlRepository:IFooRepository\n  {\n       //implementation\n   }\n\n  IFooRepository repo= new FooXmlRepository(); //or via your favorite DI container	0
16679997	16640938	Programmatically create and export WPF Viewport3D visual object in a console application on the fly	v.Dispatcher.Invoke(((Action)(() => bmp.Render(v))), DispatcherPriority.Render);	0
8618203	8614234	How to auto-mock a container (e.g. IList) in MOQ without extensions/contrib	var aList = new List<int>() { 1, 2, 3, 4, 5 };\nvar mockService = new Mock<IMyService>();\nmockService.Setup(mock => mock.GetFooList()).Returns(aList);	0
6150095	6140459	Provide different values for same Import using MEF	public class AExporter\n{\n    [Export("A1", typeof(IA)]\n    public IA A1\n    {\n        get\n        {\n             return new A(this.B1);\n        }\n    }\n\n    [Export("A2", typeof(IA)]\n    public IA A2\n    {\n        get\n        {\n            return new A(this.B2);\n        }\n    }\n\n    [Import("B1", typeof(IB))]\n    public IB B1 { private get; set; }\n\n    [Import("B2", typeof(IB))]\n    public IB B2 { private get; set; }\n\n}	0
32863604	32863387	Reading Null DateTime column from a Table in SqlServer	if (dataReader.IsDBNull(8))	0
9596662	9596624	how to find day name from given date for current year?	var birthDate = new DateTime(1983, 10, 21);\nvar thisYear = new DateTime(DateTime.Today.Year, birthDate.Month, birthDate.Day);\n\nvar dayOfWeek = thisYear.DayOfWeek; // it gives you day of week of birth day in this year	0
9103956	9103903	How to prevent SaveChanges in Entity Framework to try to add referenced objects to database	trainingConsultant.TrainingId = training.Id;\ntrainingConsultant.ConsultantId = consultant.Id;\n\ncontext.TrainingConsultants.AddObject(trainingConsultant);\ncontext.SaveChanges();	0
5379773	5379730	Using Reflection to call a method of a property	m.Invoke(p.GetValue(newControl, null), new object[] { newValue });	0
5362912	5362867	Fill DataTable with Array	var dt = new DataTable();\n//AddColumns\nfor (int c = 0; c < dim; c++)\n    dt.Columns.Add(c.ToString(), typeof(double));\n//LoadData\nfor (int r = 0; r < dim; r++)\n    dt.LoadDataRow(arry[r]);	0
3870712	3857699	Problem reference a com assembly dll	regsvr32 MYDLL.DLL	0
646070	646047	How do I access the variables from urls that come from the GET method in ASP.net?	Dim itemId As Integer\nDim itemType as String\n\nIf Not Integer.TryParse(Request.QueryString("i").ToString, itemId) Then\n    itemId = -1 ' Or whatever your default value is\nElse\n    ' Else not required. Variable itemId contains the value when Integer.TryParse returns True.\nEnd If\n\nitemType = Request.QueryString("t").ToString ' <-- ToString important here!	0
4352635	4352134	How to use a timer to display content?	timer = new DispatcherTimer(\n    TimeSpan.FromSeconds(15), \n    DispatcherPriority.Background, \n    TimeoutEvent, \n    this.Dispatcher);\n\ntimer.Start();	0
27318861	27318352	Get thumbnail of Network DWG file by Windows API Code Pack	using System;\nusing System.Drawing;\nusing System.IO;\nusing System.Windows.Forms;\nusing Microsoft.WindowsAPICodePack.Shell;\n\nnamespace WindowsFormsApplication1\n{\n    public partial class Form1 : Form\n    {\n        public Form1()\n        {\n            InitializeComponent();\n        }\n\n        private void Form1_Load(object sender, EventArgs e)\n        {\n            string fileName = @"\\PC\Users\Public\bitmap.bmp";\n            ShellFile shellFile = ShellFile.FromFilePath(fileName);\n            ShellThumbnail thumbnail = shellFile.Thumbnail;\n            var pictureBox = new PictureBox\n            {\n                Image = thumbnail.Bitmap,\n                Dock = DockStyle.Fill\n            };\n            Controls.Add(pictureBox);\n        }\n    }\n}	0
8717126	8716804	Using code contracts to make a generic to be of type enum	public class SomeClass<T>\n{\n    [ContractInvariantMethod]\n    private void Invariants()\n    {\n        Contract.Invariant(typeof(System.Enum).IsAssignableFrom(typeof(T)));\n    }\n\n    /// <summary>Initializes a new instance of the SomeClass class.</summary>\n    /// <param name="dependency"></param>\n    public SomeClass()\n    {\n\n    }\n}\n\npublic class SomeOtherClass\n{\n    public SomeOtherClass()\n    {\n        var myClass = new SomeClass<int>();\n\n    }\n}	0
21010049	21010004	Removal of Tab-whitespace?	string s = "This is a string without        spaces";\ns = s.Replace(" ", string.Empty);\ns = s.Replace("\t", string.Empty);	0
13352985	13352929	I need to remove duplicates from a List<>	using System.Linq;\n\npublic List<string> GetUniqueCardNumbers(List<string> cardNumbers)\n{\n    // First replace the spaces with empty strings\n    return cardNumbers.Select(cc => cc.Replace(" ", ""))\n                      .Distinct()\n                      .ToList();\n}	0
13719741	13719449	Repeat Row Labels On All Lines Of A Pivot Table Excel 2007	On Error Resume Next\n    With .Range(.Cells(2, 1), .Cells(MaxRow, 1))\n        .SpecialCells(xlCellTypeBlanks).Select\n        Selection.FormulaR1C1 = "=R[-1]C"\n        .Value = .Value\n    End With\n    On Error GoTo 0	0
9270046	9270023	How to determine if an exception is of a particular type	catch(DbUpdateException ex)\n{\n  if(ex.InnerException is UpdateException)\n  {\n    // do what you want with ex.InnerException...\n  }\n}	0
6554391	6554367	Remove Table from HTML or XAML C#	string html = "...";\nhtml = html.Replace("<table>","<p>");\nhtml = html.Replace("<td>","");\nhtml = html.Replace("</td>"," ");\nhtml = html.Replace("<tr>","");\n\nhtml = html.Replace("</tr>","<br/>");\nhtml = html.Replace("</table>","</p>");	0
6495407	6495159	MVC3 null Querystring Retured To Action Method	Html.BeginForm("Create", "MyController", new { pid = Request.QueryString["pid"] },   FormMethod.Post, new { id = "myForm" }))	0
5037529	5037422	How to create an IAsyncResult that immediately completes?	protected override IAsyncResult BeginDoSomething(int a, int b, AsyncCallback callback, object state)\n{\n     bool returnValue = a > b;\n     Func<int,int,bool> func = (x,y) => x > y;\n     return func.BeginInvoke(a,b,callback,state);\n}	0
20650101	20649804	How to add the IEnumerable collection to ICollection list?	ICollection<UserInApplication> userInAppRole=new Collection<UserInApplication>(); //Initialize this\nIEnumerable<UserInApplication> result=null;\nresult = _userService.UserInApplicationRoles(iAppRoleId,collection["displayName"])\n                     .AsEnumerable();\n userInAppRole = result.AddTo(userInAppRole);	0
34137039	34129883	Datagridview: Get column name by right clicking on column header (read info)	Private Sub dgv1_ColumnHeaderMouseClick(sender As Object, e As DataGridViewCellMouseEventArgs) Handles dgv1.ColumnHeaderMouseClick\n    If e.Button = Windows.Forms.MouseButtons.Right Then\n        MsgBox(e.ColumnIndex & " " & dgv1.Columns(e.ColumnIndex).Name & " " & dgv1.Columns(e.ColumnIndex).HeaderText)\n    End If\nEnd Sub	0
26650858	26607817	DataGridview, How to get some value from second level of an item and show it in a new column?	int counter = dvg1.RowCount ;\ncounter ++;\ndvg1.Rows[counter].Cells[0].Value = "do some stuff here";	0
3388239	3388025	How can I add image to ListView when I set it to details?	ImageList imgList = new ImageList();\n  imgList.Images.AddStrip(bitmap);\n  this.listView1.StateImageList = imgList;	0
5651703	5651138	Copy 2d array of structs to byte[]	var source = new PixelColorRGBA[1000, 1000];\nvar destination = new byte[4000000];\n{\n    var start = DateTime.Now;\n    unsafe\n    {\n        for (var q = 0; q < 100; q++)\n            fixed (PixelColorRGBA* tmpSourcePtr = &source[0, 0])\n            {\n                var sourcePtr = (IntPtr) tmpSourcePtr;\n                Marshal.Copy(sourcePtr, destination, 0, 4000000);\n            }\n    }\n    Console.WriteLine("MS: " + DateTime.Now.Subtract(start).TotalMilliseconds);\n}	0
19496254	19496186	Variable number of decimal places in Double to String ValueConverter	string.Format(culture, "{0:0." + new string('0', Convert.ToInt32(parameter)) + "}"	0
17647348	17647201	WPF Xaml MainWindow dissappears after its called using Show function	[STAThread] \nstatic void Main() \n{\n  MainWindow winMain = new MainWindow();\n  winMain.Show();\n}	0
632089	632074	FileUpload - Verifying that an actual file was uploaded	if(File.Exists(myFile)){\n  //it was uploaded.\n}	0
12737647	12728530	Windows phone bind data from two separate classes	Message mess = null; \n\n   var item = from user in Users\n              where (mess = Messages.First(m => m.UserID == user.UserID)) != null\n              select new {user.UserName, mess.MessageText};	0
2430274	2423902	Convert an array of bytes into one decimal number as a string	static string BytesToString(byte[] data) {\n    // Minimum length 1.\n    if (data.Length == 0) return "0";\n\n    // length <= digits.Length.\n    var digits = new byte[(data.Length * 0x00026882/* (int)(Math.Log(2, 10) * 0x80000) */ + 0xFFFF) >> 16];\n    int length = 1;\n\n    // For each byte:\n    for (int j = 0; j != data.Length; ++j) {\n        // digits = digits * 256 + data[j].\n        int i, carry = data[j];\n        for (i = 0; i < length || carry != 0; ++i) {\n            int value = digits[i] * 256 + carry;\n            carry = Math.DivRem(value, 10, out value);\n            digits[i] = (byte)value;\n        }\n        // digits got longer.\n        if (i > length) length = i;\n    }\n\n    // Return string.\n    var result = new StringBuilder(length);\n    while (0 != length) result.Append((char)('0' + digits[--length]));\n    return result.ToString();\n}	0
11235715	11235678	Adding Integer from textbox to database c#	u.Age = Int32.Parse(txtboxAge.Text);	0
6709820	6709762	C# Deserialize JSON html string	escape()	0
915221	915210	How can i get the path of the current user's "Application Data" folder?	Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData)	0
1816182	1816159	how do i get an always changing value from a string c#	using System;\nusing System.Text.RegularExpressions;\n\nclass Program\n{\n    public static void Main()\n    {\n        string html = @"        function strengthObject() {\n                this.base=""168"";\n                this.effective=""594"";\n                this.block=""29"";\n                this.attack=""1168"";";\n\n        string regex = @"this.effective=""(\d+)""";\n\n        Match match = Regex.Match(html, regex);\n        if (match.Success)\n        {\n            int effective = int.Parse(match.Groups[1].Value);\n            Console.WriteLine("Effective = " + effective);\n            // etc..\n        }\n        else\n        {\n            // Handle failure...\n        }\n    }\n}	0
1587507	1587440	How to scan an IP Range C#	private static long ToInt(string addr) \n{\n\n    return (long)(uint)System.Net.IPAddress.NetworkToHostOrder(\n        (int)System.Net.IPAddress.Parse(addr).Address);    \n}\n\n\n\nprivate static string ToAddr(long address)\n{\n    return System.Net.IPAddress.Parse(address.ToString()).ToString();\n}	0
28812441	28812380	How to Auto-Populate Textboxes in C#?	txtNickname.Text = txtFirstName.Text[0] + txtLastName.Text;\ntxtAlias.Text = txtFirstName.Text[0] + txtLastName.Text.Substring(0, 4);	0
18150379	18150282	How do I remove null properties from xml?	var elementMap = XElement.Load(path_to_xml); // or XElement.Parse(xml_string)\nelementMap.Attributes().Where(a => (string)a == "{assembly:Null}").Remove();\nelementMap.Save(path_to_xml);	0
6384944	6384785	How can I receive OutputDebugString from service?	CreateEvent(@SecurityAttributes, False, True, 'Global\DBWIN_BUFFER_READY');\nCreateEvent(@SecurityAttributes, False, False, 'Global\DBWIN_DATA_READY');\nCreateFileMapping(THandle(-1), @SecurityAttributes, PAGE_READWRITE, 0, 4096, 'Global\DBWIN_BUFFER');	0
6188147	6187140	compare two datatable in c#	bool flag = false;\nif (dtFirst.Columns.Count == dtSecond.Columns.Count)\n{\n    for (int i = 0; i <= dtFirst.Columns.Count - 1; i++)\n    {\n        String colName = dtFirst.Columns[i].ColumnName;\n        var colDataType = dtFirst.Columns[i].DataType.GetType();\n        var colValue = dtFirst.Columns[i];\n        flag = dtSecond.AsEnumerable().Any(T => typeof(T).GetProperty(colName).GetValue(T, typeof(colDataType)) == colValue);\n    }\n}	0
21023852	21023632	Store specific data from SPListItem data?	using (SPSite site = new SPSite("http://mysharepointsiteurl"))\nusing (SPWeb web = site.OpenWeb())\n{\n    var items = web.Lists["List Name"].GetItems("Field Name");\n    string value = (string)items[3]["Field Name"];\n}	0
12608096	12607920	how to open ssrs report from asp web page using report viewer	protected void Page_Init(object sender, EventArgs e)\n{\n    if (!Page.IsPostBack)\n    {\n        // Set the processing mode for the ReportViewer to Remote\n        reportViewer.ProcessingMode = ProcessingMode.Remote;\n\n        ServerReport serverReport = reportViewer.ServerReport;\n\n        // Set the report server URL and report path\n        serverReport.ReportServerUrl =\n            new Uri("http://<Server Name>/reportserver");\n        serverReport.ReportPath =\n            "/AdventureWorks Sample Reports/Sales Order Detail";\n\n        // Create the sales order number report parameter\n        ReportParameter salesOrderNumber = new ReportParameter();\n        salesOrderNumber.Name = "SalesOrderNumber";\n        salesOrderNumber.Values.Add("SO43661");\n\n        // Set the report parameters for the report\n        reportViewer.ServerReport.SetParameters(\n            new ReportParameter[] { salesOrderNumber });\n    }\n}	0
8385311	8385229	Downloading a file with response doesn't show a filesize	Response.AddHeader("Content-Length", someBytes.Length.ToString());	0
2343688	2343614	Entity Framework with many-to-many deleting	on delete cascade	0
17687251	17687219	C# timer tick with ofd files	private SoundPlayer s;\n\nprivate void button1_Click(object sender, EventArgs e)\n{     \n    OpenFileDialog ofd = new OpenFileDialog();\n    if (ofd.ShowDialog() == System.Windows.Forms.DialogResult.OK)\n    {\n        s = new SoundPlayer(ofd.FileName);\n        timer1.Start();\n        s.Play();\n    }\n\n}\n\nprivate void timer1_Tick(object sender, EventArgs e)\n{\n    s.Play();\n}	0
32666147	32666115	How write right route to REST Api Controller with get method	routes.MapRoute(\n                name: "ViewConfigFile",\n                url: "{controller}/{action}/{id}",\n                defaults: new { controller = "ViewConfigFile", action = "Get", id = UrlParameter.Optional }\n            );	0
14463231	14460964	How to press multiple button's at once on a WP7 in c#	Touch.FrameReported	0
15246047	15135896	How to find folder below given section of a path?	public static string GetBranchName(string path, string prefix)\n{\n    string folder = Path.GetDirectoryName(path);\n\n    // Walk up the path until it ends with Dev\Branches\n    while (!String.IsNullOrEmpty(folder) && folder.Contains(prefix))\n    {\n        string parent = Path.GetDirectoryName(folder);\n        if (parent != null && parent.EndsWith(prefix))\n            return Path.GetFileName(folder);\n\n        folder = parent;\n    }\n\n    return null;\n}	0
11139499	11139419	How can we check whether one array contains one or more elements of another array in #?	names.Any(x => subnames.Contains(x))	0
3798787	3798656	P/Invoke AccessViolationException that makes no sense	IntPtr.Size	0
13150384	13150327	Passing static object from one dll to another	static MyObject objRandom...	0
3949632	3949611	Bind a calculated value somehow to a datagrid	public Observablecollection<int> foo = new ObservableCollection<int>()\n\n\nprivate void Calculation(int[] X, int[] Y)\n{\n    foo.Clear();\n    int i;\n    for(int index = 0; index < X.Length; index++)\n    {\n        //Calculation Like\n        i = X[index] + y[index];\n        foo.Add(i);\n    }\n}	0
18553355	18553317	Grab information from a php script and display on a winform	using(var client = new WebClient())\n{\n    String result = client.DownloadString("www.foosite.com/page.php");\n}	0
12195654	12195267	Displaying entire year in C# WinFrom application	myMonthCalendarControl.SetCalendarDimensions(4, 3); \n//I used 4 columns and 3 rows because the product should be not greater than 12	0
3280663	3280602	how to draw an image on a canvas with transparency/alpha	ColorMatrix cm = new ColorMatrix();\ncm.Matrix33 = 0.55f;\nImageAttributes ia = new ImageAttributes();\nia.SetColorMatrix(cm);\ncanvas.DrawImage(image, new Rectangle(0, 0, image.Width, image.Height), GraphicsUnit.Pixel, cm);	0
21212167	21208527	Breeze one-to-many deletion - children entities FKs set to 0	EntityInfo.OriginalValuesMap	0
2431028	2430930	How to pause/suspend a thread then continue it?	ManualResetEvent mrse = new ManualResetEvent(false);\n\npublic void run() \n{ \n    while(true) \n    { \n        mrse.WaitOne();\n        printMessageOnGui("Hey"); \n        Thread.Sleep(2000); . . \n    } \n}\n\npublic void Resume()\n{\n    mrse.Set();\n}\n\npublic void Pause()\n{\n    mrse.Reset();\n}	0
19936082	19919218	Templates can be used only for field access	Html.DisplayFor(y => y.Data.Select(z => z.Name).First().ToString())	0
3556935	3556908	How to use reflection to get just the object instance's public properties?	private IOrderedEnumerable<PropertyInfo> GetSortedPropInfos()\n{\n    return dataExtractor.GetType()\n                        .GetProperties(BindingFlags.Instance | BindingFlags.Public)\n                        .OrderBy( p => p.Name );\n}	0
20781208	20781103	Insert a byte array into sql server	public static void LogActivity( byte[] data)\n        {\n\n                var connection =\n                    new SqlConnection(ConfigurationManager.ConnectionStrings["LogConnectionString"].ConnectionString);\n                var command = new SqlCommand { Connection = connection, CommandType = CommandType.Text };\n                try\n                {\n                    command.CommandText = @"\ninsert into Logs (Data)\nvalues ( @data)\n";\n                    command.Parameters.Add("@data", SqlDbType.VarBinary, data.Length).Value = data;\n                    connection.Open();\n                    command.ExecuteNonQuery();\n                    connection.Close();\n                    connection.Dispose();\n                }\n                catch (Exception ex)\n                {\n                    Log(ex);\n                }\n\n    }	0
17294827	17294737	converting an image to png on upload	using System.Drawing;\n\nBitmap b = (Bitmap)Bitmap.FromStream(file.InputStream);\n\nusing (MemoryStream ms = new MemoryStream()) {\n    b.Save(ms, ImageFormat.Png);\n\n    // use the memory stream to base64 encode..\n}	0
9594903	9594853	Sending Data to Non-Parent Window	public partial class frmSchedule : Window \n{       \n   ...  \n   private void btnAdd_Click(object sender, RoutedEventArgs e)  \n   {  \n    //New frmAddLesson window  \n    frmAddLesson addLesson = new frmAddLesson(this);  \n    addLesson.Show();  \n   }  \n\n   public void AddLesson(Lesson lesson)\n   {\n     ...\n   }\n}\n\npublic partial class frmAddLesson : Window    \n{\n  public frmAddLesson(frmSchedule schedule)      \n  {      \n    InitializeComponent();      \n\n    this.schedule = schedule;\n\n    ...\n\n  }    \n  frmSchedule schedule;\n\n  //ADD LESSON    \n  private void btnAdd_Click(object sender, RoutedEventArgs e)    \n  {    \n    //Create new Lesson object    \n    var theLesson = new Lesson();    \n\n    //Set Lesson property    \n    theLesson.Time = (int)cmbTime.SelectedValue; //Time    \n\n    schedule.AddLesson(theLesson);\n\n    this.Close();    \n  }    \n}	0
15281773	15280982	drawing a rectangle for a bitmap clone	Bitmap bp = new Bitmap("myImage.jpg");\npictureBox1.Image = bp;\nbp.RotateFlip(RotateFlipType.Rotate90FlipNone);\npictureBox1.Invalidate();	0
18756833	18756442	c# - How to bind values from list in gridview rows?	if (Application["mondayValues"] != null)\n{\n    List<string> monValues = Application["mondayValues"] as List<string>;\n    for (int i = 0; i <= gridActivity.Rows.Count-1; i++)\n    {\n        GridViewRow row = gridActivity.Rows[i];\n        TextBox txtMon = (TextBox)row.FindControl("txtMon");\n        txtMon.Text = monValues[i];\n    }           \n}	0
19268374	10125748	GZip compression in WCF WebService	my_service_object.EnableDecompression = true;	0
22386201	22385771	How to change db connection programmatically c# Entity Framework	using(var db = new VMaxEntities())\n{\n   var connectionString = context.Database.Connection.ConnectionString;\n   var datasource = context.Database.Connection.DataSource;\n   var databaseServer = "yourDevDatabaseServerName"        \n\n   db.Database.Connection.ConnectionString = connectionString.Replace(datasource, databaseServer);\n}	0
22151519	22109569	In Unity, how do I automatically slide diagonally when hitting a diagonal?	void FixedUpdate()\n{\n    float moveHorizontal = Input.GetAxisRaw("Horizontal");\n    float moveVertical = Input.GetAxisRaw("Vertical");\n\n    movement = new Vector2(moveHorizontal, moveVertical);\n    movement.Normalize();\n    rigidbody2D.velocity = movement * Speed;\n}	0
5198238	5198149	How to reset a singleton instance in c#?	public void Reset(){ _list.Clear(); }	0
20035343	20035152	LINQ join with top 1 from another table	var res = db.Item.Join(db.Comment, x=>x.ID, x=>x.ID, (x,y)=>new{x,y})\n            .OrderByDescending(a=>a.y.Created)\n            .GroupBy(a=>a.x.ID,(key,items)=>items.First())\n            .Select(a=> new {\n                       a.x.ID,\n                       a.x.Name,\n                       a.y.Message\n                   });	0
10492540	10492492	How to download a file in IIS?	Process.Start	0
23231528	23231400	Remove from Everything but these values	var strValue = "DUE IN THIRTY SEVEN DAYS".ToLower().Split(' ');\n\nvar numbers = (from u in units\n               join s in strValue on u equals s\n               select u);\nConsole.Write(string.Join(" ", numbers));	0
33865951	33857910	Read from blocking IEnumerable	var cancellationTokenSource = new CancellationTokenSource(1000);\nforeach (var data in consumer.Consume(cancellationTokenSource.Token))\n{\n    Console.WriteLine(data.message);\n    cancellationTokenSource.CancelAfter(1000);\n}	0
25181041	25180913	WebForms: How detect if I pushed ENTER Key or I clicked to a button to look for data	TextBox tb = new TextBox();\n    tb.KeyDown += new KeyEventHandler(tb_KeyDown);\n\n    private void tb_KeyDown(object sender, KeyEventArgs e) {\n        if (e.KeyCode == Keys.Enter)\n        {\n            //enter key is down\n        } \n    }	0
16210851	16210796	Apply filter to business object	var allemps = empService.GetAllEmployees();\nIEnumerable<Emp> emps;\nif (allemps.IsFreeOfErrors)\n{\n   emps = allemp.Where(w=>w.Value.StartWith("abc"));\n}	0
23132589	23129307	How programmatically handling Canvas event WPF?	for (int i = 0; i < canvases.Count; i++)\n{\n    canvases[i] = new Canvas();\n    canvases[i].Width = sheetWidth;\n    canvases[i].Height = sheetHeight;\n    canvases[i].Background = Brushes.White;\n    canvases[i].RenderTransform = new ScaleTransform(); // here !!!\n\n    canvases[i].MouseWheel += (sender, e) =>\n    {\n        double ScaleRate = 1.00000001; // really ??\n\n        var canvas = (Canvas)sender;\n        var scaletransform = (ScaleTransform)canvas.RenderTransform;\n\n        if (e.Delta > 0)\n        {\n            scaletransform.ScaleX *= ScaleRate;\n            scaletransform.ScaleY *= ScaleRate;\n        }\n        else\n        {\n            scaletransform.ScaleX /= ScaleRate;\n            scaletransform.ScaleY /= ScaleRate;\n        }\n   };\n\n   stackPanel.Children.Add(canvases[i]);	0
6166173	6165874	C#: Running a process on button click	private void button1_Click(object sender, EventArgs e)\n        {\n            string arg1 = "1";\n            Process p1 = new Process();\n            p1.StartInfo.CreateNoWindow = true;\n            p1.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;\n            p1.StartInfo.FileName = @"yourExecutable";\n            p1.StartInfo.Arguments = arg1;\n            p1.StartInfo.UseShellExecute = false;\n            p1.StartInfo.RedirectStandardOutput = true;\n            p1.StartInfo.RedirectStandardInput = true;\n            p1.StartInfo.RedirectStandardError = true;\n            p1.Start();\n            //while (!p1.HasExited)\n            //{\n\n            // }\n\n            MessageBox.Show(p1.StandardOutput.ReadToEnd());\n\n            button2.Focus();  // set button 2 to have a height of 0 so it is not visible\n            // or place it somewhere where it cannot be seen\n\n\n\n        }	0
10320850	10320802	c# getting items of my checkedboxlist in form1 from my form2	string[] list = new string[form1.ckdBoxList.Items.Count];\n\n    MessageBox.Show(form1.ckdBoxList.Items.Count+"");//In debug it tells me that the lenght is 0\n\n    for (int i = 0; i < form1.ckdBoxList.Items.Count; i++)\n    {\n        list[i] = form1.ckdBoxList.Items[i].ToString();\n    }	0
27682113	27681997	Restriction of maximum 3 threads at a time	var URLsToProcess = new List<string>\n                    {\n                        "http://www.microsoft.com",\n                        "http://www.stackoverflow.com",\n                        "http://www.google.com",\n                        "http://www.apple.com",\n                        "http://www.ebay.com",\n                        "http://www.oracle.com",\n                        "http://www.gmail.com",\n                        "http://www.amazon.com",\n                        "http://www.yahoo.com",\n                        "http://www.msn.com"\n                    };\n\nConsole.WriteLine("waiting now");\n\nstring[] tURLs = URLsToProcess\n    .AsParallel()\n    .WithDegreeOfParallelism(3)\n    .Select(uri => this.DownloadStringAsTask(new Uri(uri)).Result)\n    .ToArray();\n\nConsole.WriteLine("download all done");\nforeach (string t in tURLs)\n{\n    Console.WriteLine(t);\n}	0
31944515	31944453	Include multiple values in Linq list	class Item\n{\n    public string CardCode {get;set;}\n    public string CardName {get;set;}\n}\n\npublic List<Item> getCustomerNames()\n{\n     var Customers = (from c in _context.OCRDs\n                      where c.CardType == "c"\n                      select new Item { CardCode = c.CardCode, CardName = c.CardName }\n                      ).ToList();\n\n     return Customers;\n}	0
22577745	22577666	C++ socket server receive msg from Java client, but not otherwise	BufferedInputStream input = new BufferedInputSream(socket.getInputStream());\nbyte[] buffer = new byte[10]; // 10 bytes buffer\nint bytesRead = 0;\nwhile( (bytesRead=input.read(buffer)) !=-1 ) { // read up to 10 bytes\n    String str = new String(buffer,0,bytesRead); // convert bytes to String using default encoding\n    System.out.println("Data received: " + str);\n}	0
2774071	2774015	What is the best way to return two values from a method?	class MyReturnValue\n{\n    public string Id { get; set; }\n    public string Name { get; set; }\n}	0
30675717	30669918	DataGridComboBoxColumn wont display selected item in cell on ending edit	private ObservableCollection<string> _listOStrings = new ObservableCollection<string>();\npublic ObservableCollection<string> ListOStrings \n{\n    get\n    {\n        return _listOStrings;\n    }\n\n    set\n    {\n        _listOStrings = value;\n        OnPropertyChanged("ListOStrings");\n    }\n}	0
7509637	7506745	response-gating next message send, with Rx	var receiveObs = //You have created a observable around the receive mechanism \nvar responses = messages.Select(m => {\n   send(m);\n   return receiveObs.First();\n}).ToList();	0
16364755	16364699	How Can i Connect C#.net desktop application on My Computer to the MYSQL server of another computer	string connectionString = "server=10.10.5.100;uid=theuser;password=thepassword;";	0
25645460	25645314	Create checkboxes from a list and add to winform	List <CheckBox> CheckBoxes=new List <CheckBox> ();\n\nforeach (var box in Checklist)\n{\n CheckBox chk = new CheckBox();\n chk.Left = 50;\n chk.Text = box.Text;\n chk.Name = box.NAme;\n CheckBoxes.Add(chk);\n}	0
9972066	9968994	Extract all occurrences of specific characters from strings	var separators = new char[] { '/', '*' };\nvar words = new List<string>();\nvar delimiters = new List<string>();\nvar idx = source.IndexOfAny(separators);\nvar prevIdx = 0;\nwhile (idx > -1)\n{\n    if (idx - prevIdx > 0)\n        words.Add(source.Substring(prevIdx, idx - prevIdx));\n\n    prevIdx = idx + 1;\n    delimiters.Add(source.Substring(idx, 1));\n    idx = source.IndexOfAny(separators, idx + 1);\n}	0
4846161	4846098	how can i remove an outer <p>...</p> from a string	HtmlDocument doc = new HtmlDocument();\ndoc.LoadHtml("<p> around the text (ending with </p>");\nstring result = doc.DocumentNode.FirstChild.InnerHtml;	0
21796153	21796099	how to get stored procedure text with parameter after execution?	insert into mytable values (@val1,@val2)\n\nDECLARE @res as nvarchar(200)\nset @res = N"insert into mytable \nvalues (" + @val1 + N"," + @val2 +N")"\nSELECT @res	0
21987379	21987012	need help in grouping the boxes according to their property values	void Main()\n{\n    var boxes = new List<Box>()\n    {\n      new Box(1, 2, 2, 2),\n      new Box(2, 2, 2, 2),\n      new Box(3, 3, 3, 3),\n      new Box(4, 3, 3, 3),\n      new Box(5, 4, 4, 4)\n    };\n\n    var groupedBoxes = boxes.GroupBy (b => new {b.depth, b.height, b.length}).Dump();\n}\n\n// Define other methods and classes here\npublic class Box\n{\n  public Box(int bno, int len, int hei, int dep)\n  {\n    this.bno = bno; this.length = len; \n    this.height = hei; this.depth = dep; \n    //assuming volume is result of former 3 properties\n    this.volume = length * depth * height;\n  }\n\n\n    public int bno { get; set; }\n    public int length { get; set; }\n    public int height { get; set; }\n    public int depth { get; set; }\n    public int volume { get; set; }\n}	0
1802981	1802966	C#: Fast way to check how many UTF-8 encoded bytes thats in a StringBuffer?	Encoding.UTF8.GetByteCount(builder.ToString());	0
19957218	19847181	In C#, how can a class do its own application-end finalization in a way that works under both ASP.Net and non-web applications?	public class ClassThatNeedsStaticFinalizer {\n\n    // ... other class properties, methods, etc ...     \n\n    #region Static Finalizer Emulation\n\n    static readonly Finalizer finalizer = new Finalizer();\n    private sealed class Finalizer\n    {\n        ~Finalizer()\n        {\n             //  ... Do final stuff here ...\n        }\n    }\n\n    #endregion\n}	0
27446047	27425501	Dotnet Nlog Mail Target Bold Body Html Text	body="Date:<strong>${longdate}</strong>${newline}\n      Calling Class: <strong>${callsite}</strong>"	0
32159275	32151936	How to convert Json table (array of arrays) data to a collection of c# objects	JObject jo = JObject.Parse(json);\nList<Row> rows = jo["Data"]\n    .Children<JArray>()\n    .Select(ja => new Row\n    {\n        ColumnName1 = (string)ja[0],\n        ColumnName2 = (string)ja[1],\n        ColumnName3 = (int)ja[2]\n    })\n    .ToList();	0
22228080	22227847	Compare Cells between two DataGridViews	for(int i=0; i<src1.Rows.Count; i++)\n{\n    var row1 = src1.Rows[i].ItemArray;\n    var row2 = src2.Rows[i].ItemArray;\n\n    for(int j = 0; j < row1.Length; j++)\n    {\n        if (!row1[j].ToString().Equals(row2[j].ToString()))\n        {\n            dataGridView1.Rows[i].Cells[j].Style.BackColor = Color.Red; \n            dataGridView2.Rows[i].Cells[j].Style.BackColor = Color.Red; \n        }\n    }\n}	0
25207525	25207272	Using webdriver with c# how can I select a drop down item by text if the drop down menu is not a select element?	.//div[text()='Cars']	0
9364023	9363061	How to insert record into a sql server express database table?	using (SqlConnection conn = new SqlConnection(@"Persist Security Info=False;Integrated Security=true;Initial Catalog=myTestDb;server=(local)"))\n{\n    SqlCommand addSite = new SqlCommand(@"INSERT INTO site_list (site_name) VALUES (@site_name)", conn);\n    addSite.Parameters.AddWithValue("@site_name", "mywebsitename");\n    addSite.Connection.Open();\n    addSite.ExecuteNonQuery();\n    addSite.Connection.Close();\n}	0
3067515	3067503	How can i use generic list with foreach?	foreach (Cal?san item in myCal?san.list)	0
21934484	21930839	Get properties from Properties window	IVsMonitorSelection selection = (IVsMonitorSelection)yourSite.GetService(typeof(SVsShellMonitorSelection)); // or yourPackage.GetGlobalService\nIVsMultiItemSelect ms;\nIntPtr h;\nIntPtr pp;\nuint itemid;\n\nselection.GetCurrentSelection(out h, out itemid, out ms, out pp);\nif (pp != IntPtr.Zero)\n{\n    try\n    {\n        ISelectionContainer container = Marshal.GetObjectForIUnknown(pp) as ISelectionContainer;\n        if (container != null)\n        {\n            uint count;\n            container.CountObjects((uint)Microsoft.VisualStudio.Shell.Interop.Constants.GETOBJS_SELECTED, out count);\n            if (count == 1)\n            {\n                object[] objs = new object[1];\n                container.GetObjects((uint)Microsoft.VisualStudio.Shell.Interop.Constants.GETOBJS_SELECTED, 1, objs);\n                object selection = objs[0]; // selection is here\n            }\n        }\n    }\n    finally\n    {\n        Marshal.Release(pp);\n    }\n}	0
22389178	22238292	Access Windows Phone folder from Windows Store app	await StorageApplicationPermissions.FutureAccessList.GetFolderAsync(entry.Token);	0
10087318	10086430	Using fitnesse, fitsharp and slim with c#	!define COMMAND_PATTERN {%m -r fitnesse.slim.Runner, c:\Projects\fitsharp\fitsharp.dll %p}	0
286153	286044	Reading Excel in .NET, how to get specific rows?	string connectionString = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=Book1.xls;Extended Properties=""Excel 8.0;HDR=YES;""";\nusing (System.Data.OleDb.OleDbConnection conn = new System.Data.OleDb.OleDbConnection(connectionString)) {\n    System.Data.OleDb.OleDbCommand cmd = new System.Data.OleDb.OleDbCommand();\n    cmd.Connection = conn;\n    cmd.CommandText = "SELECT top 13 City,State FROM [Cities$]";\n\n    conn.Open();\n    System.Data.IDataReader dr = cmd.ExecuteReader();\n\n    int row = 2;\n    while (dr.Read()) {\n        if (row++ >= 4) {\n            // do stuff\n            Console.WriteLine("{0}, {1}", dr[0], dr[1]);\n        }\n    }\n}	0
1161983	1127992	How do you map a List<string> in iBatis?	public class StringValue\n{\n    public String Name { get; set; }\n}\n\n<resultMap id="StringList" class="StringValue" >\n  <result property="Name" column="Value"/>\n</resultMap>	0
19104172	19104111	C# equivalent of PATINDEX function in SQL Server 2008	.*SELECT .*FROM.*	0
30504893	30504692	Ensure that the necessary enum values are present and are marked with EnumMemberAttribute attribute	private static LPFLogger GetLPFLogger(int value)\n    {\n\n        var lstEnum = Enum.GetValues(typeof(LPFLogger)).Cast<int>().ToList();\n\n        if (lstEnum.Any(s => s == value))\n            return (LPFLogger)value;\n\n        return LPFLogger.None;\n    }	0
1937877	1937847	How to modify key in a dictionary in C#	// we need to cache the keys to update since we can't\n// modify the collection during enumeration\nvar keysToUpdate = new List<int>();\n\nforeach (var entry in dict)\n{\n    if (entry.Key < MinKeyValue)\n    {\n        keysToUpdate.Add(entry.Key);\n    }\n}\n\nforeach (int keyToUpdate in keysToUpdate)\n{\n    SortedDictionary<string, List<string>> value = dict[keyToUpdate];\n\n    int newKey = keyToUpdate + 1;\n\n    // increment the key until arriving at one that doesn't already exist\n    while (dict.ContainsKey(newKey))\n    {\n        newKey++;\n    }\n\n    dict.Remove(keyToUpdate);\n    dict.Add(newKey, value);\n}	0
1942849	1942346	How to create a copy/link of a user element in a tab control?	private void tabControl1_SelectedIndexChanged(object sender, EventArgs e) {\n        textBox1.Parent = tabControl1.SelectedTab;\n    }	0
25661132	25659349	how to store value in to one data table to another datatable?	Try this below code..\n\ntry\n{\n\nDataTable dtdcnomissing = new DataTable();\ndtdcnomissing.Clear();\ndtdcnomissing = objRetailBAL.DCNOMissing(objRetailPL);\nDataTable dtimport = new DataTable();\nDataTable dtmissingreport = new DataTable();\nfor (int i = 0; i <= dtdcnomissing.Rows.Count - 1; i++)\n{\n\ndtmissingreport.Clear();\nobjRetailPL.dcnoint = Convert.ToInt32(dtdcnomissing.Rows[i]["id"].ToString());\ndtmissingreport = objRetailBAL.DCNOMissingReport(objRetailPL);\nif (dtimport.Rows.Count == 0)\ndtimport = dtmissingreport.Clone();\nforeach (DataRow dr in dtmissingreport.Rows)\n{\ndtimport.ImportRow(dr);\n}\n}\n\nGVDCNoMissingReport.DataSource = dtimport;\nGVDCNoMissingReport.DataBind();\n\n\n}	0
22834927	22832968	How to get urls of users profiles by theirs login names in sharepoint 2013?	// Replace the following placeholder values with the target SharePoint site and\n// target user.\nconst string serverUrl = "http://serverName/";  \nconst string targetUser = "domainName\\userName";  \n\n// Connect to the client context.\nClientContext clientContext = new ClientContext(serverUrl);\n\n// Get the PeopleManager object and then get the target user's properties.\nPeopleManager peopleManager = new PeopleManager(clientContext);\nPersonProperties personProperties = peopleManager.GetPropertiesFor(targetUser);\n\n// Load the request and run it on the server.\n// This example requests only the AccountName and UserProfileProperties\n// properties of the personProperties object.\nclientContext.Load(personProperties, p => p.AccountName, p => p.UserProfileProperties);\nclientContext.ExecuteQuery();\n\nforeach (var property in personProperties.UserProfileProperties)\n{\n     Console.WriteLine(string.Format("{0}: {1}", \n         property.Key.ToString(), property.Value.ToString()));\n}	0
25387456	25385332	LINQ get the best match from the list comparing strings	// Get the filtered list and sort by count of matching characters\nIEnumerable<QProduct> filtered = lqp\n    .Where(x=>productNameInaccurate.StartsWith(x.Name, StringComparison.InvariantCultureIgnoreCase))\n    .OrderByDesc(x => Fitness(x.ProductName, productNameInaccurate));\n\nstatic int Fitness(string individual, string target) {\n    return Enumerable.Range(0, Math.Min(individual.Length, target.Length))\n                     .Count(i => individual[i] == target[i]);\n}	0
32852218	32851997	Problems with displaying information from an array	Random random = new Random();\nfor (int j = 0; j < 10; j++)\n {\n    int randomNumber = random.Next(1,10);\n Console.WriteLine(names[randomNumber-1]);\n }	0
7042774	7033669	SSRS External Assembly: Failed to load expression host assembly	[assembly:AllowPartiallyTrustedCallers]	0
189058	188963	Connecting to SQL Server with Visual Studio Express Editions	system.data.SqlClient	0
20975088	20974712	Create one view page for two controllers & two model class?	public class MyScenarioForm\n        {\n            [Key]\n            public string FormName { get; set; }\n            public int SelectedDesgId {get; set;}\n            public int SelectedDeptId { get; set; }\n\n            public IEnumerable<Designation> Designations { get; set; }\n            public IEnumerable<Department> Departments { get; set; } \n\n            // ... constructor or method that creates initial instance with Designations and Departments populated\n        }	0
29733818	29733761	How to access the current ItemType Item value from OnItemDataBound method of ListView?	protected void ListViewPosts_ItemDataBound(object sender, ListViewItemEventArgs e)\n{\n   ...\n   DataRow p = (DataRow)e.Item.DataItem; //where Item stands for the current Post record in ListView.\n    ...\n }	0
8906463	8906433	Anonymous Variables read only case	var tmp = new MyAdd();\ntmp.name = "Mike";\ntmp.Address = "MyTown";\nreturn tmp;	0
15503742	15503657	Calling an ASP generated button click from a javascript	if (!IsPostBack)\n   {\n        ScriptManager.RegisterStartupScript(this, this.GetType(), "scr", "setTimeout(function(){document.getElementById('"+btnSave.ClientID+"').click(); return false;}, 180000);", true);\n   }	0
3364679	3364567	Display a text file in two boxes, one in plain text and the other converted to hex	StringBuilder sb = new StringBuilder();\n        foreach (char character in File.ReadAllText("input.txt").ToCharArray())\n        { //convert the string to array of bytes\n            sb.Append("0x"+      ///"0x" prefix\n               ((int)character). //convert char to int\n               ToString("X2"));  //generate string with two hex digit.\n            sb.Append("\n");         //new line after each converted char\n        }\n\n        TextBox1.Text = sb.ToString(); //set text box text	0
29616327	29602806	Set namespace for element in complextype in WCF	XmlDocument doc = new XmlDocument();\ndoc.LoadXml(payload.generate());\nXmlElement newRootNode = RecursiveCopy(doc.DocumentElement, doc, "urn:org:ns");\n\npublic XmlElement RecursiveCopy(XmlNode node, XmlDocument doc, string targetNamespace) \n{  \n    XmlElement nodeCopy = doc.CreateElement(node.LocalName, targetNamespace);\n    foreach (XmlNode child in node.ChildNodes) \n    {\n        if (child.NodeType == XmlNodeType.Element)\n        {\n            nodeCopy.AppendChild(RecursiveCopy(child, doc, targetNamespace);\n        }\n        else if (child.NodeType == XmlNodeType.Text || child.NodeType == XmlNodeType.CDATA) \n        {\n            XmlNode newNode = doc.CreateNode(child.NodeType, child.LocalName, targetNamespace);\n            newNode.Value = child.Value;\n            nodeCopy.AppendChild(newNode);\n        }\n    }\n    return nodeCopy;\n}	0
3685708	3685632	Configuring log4net in a VSTO	XmlConfigurator.Configure();	0
15179739	15164837	Return correct data type from XML element with xsi:type attribute specified	xsi:type	0
10242364	10206670	Original Route parameters in partial view	this.Request.RequestContext.RouteData.Values["controller"].ToString();	0
26762795	26762049	Trim string contents to get only the ID value	var startIndex= inputString.IndexOf("[@ID=");\n var endIndex = inputString.LastIndexOf("]");\n\n if (startIndex < 0 || endIndex < startIndex)\n     throw new ArgumentException("Format is not valid.");\n\n startIndex += "[@ID=".Length;\n var potentialIdString = inputString.Substring(startIndex, endIndex - startIndex);\n int id;\n\n if (int.TryParse(potentialIdString, out id))\n      return id;\n else\n     throw new ArgumentException("ID is not valid.");	0
1773216	1773189	Testing Data Model in project that uses NHibernate for persistence	public class MyEntity\n{\n   private readonly ISet<ChildEntity> children;\n\n   public MyEntity()\n   {\n      children = new HashedSet<ChildEntity>();\n   }\n\n   public IEnumerable<ChildEntity> Children\n   {\n      get { return children; }\n   }\n\n   public void AddChild(Child child)\n   {\n     children.Add(child);\n   }\n}	0
12942777	12942580	Convert SQLDateTime DayTicks back to DateTime value	SqlDateTime sdt = new SqlDateTime(dayTicks, 0);\nDateTime dt = sdt.Value;	0
16743386	16743299	Get values of parameters in stack trace	void SuspiciousFunction(string name, long count) {\n    try {\n        // The code of your function goes here\n    } catch (Exception e) {\n        var args = new Dictionary<string,object> {\n            { "name" , name  }\n        ,   { "count", count }\n        };\n        throw new MySpecialException(e, args);\n    }\n}	0
26112714	26112688	C# XMLDocument Assistance	//THE_SETTINGS/NETWORK_DEVICE/text()	0
28828463	28828210	How can I use a where clause and check if a string variable contains in a many table column	var query = from o in db.tbl_Custommer\n                   where o.Name.Contains(name) && o.Projects.Any(p => p.Name.Contains(name))\n                   select new SearchObject\n                   {\n                       Url = o.tbl_Webs.WebUrlName,\n                       Name = o.Name,\n                   };	0
332496	332486	How to set the default browser home page (IE) with C#?	HKCU\Software\Microsoft\Internet Explorer\Main\Start Page	0
11449095	11448987	Efficient Way for Finding Reference Object in LINQ to SQL	var c = context.GiftCoupons.FirstOrDefault(gc => gc.GiftCouponID == GiftCouponID);\nif (c != null && c.Payment != null)\nreturn c.Payment.PaymentDate	0
33642217	33581699	prevent duplicate entries in C1TrueDBGrid	private void c1TrueDBGrid1_BeforeColUpdate(object sender, C1.Win.C1TrueDBGrid.BeforeColUpdateEventArgs e)\n{\n    if (e.ColIndex == 1)\n    {\n       for (int i = 0; i < c1TrueDBGrid1.RowCount; i++)\n       {\n        if (c1TrueDBGrid1.Editor.Text == c1TrueDBGrid1[i, e.ColIndex].ToString())\n        {\n            MessageBox.Show("Sorry: but this item(s) already Exists", "Error Info", MessageBoxButtons.OK, MessageBoxIcon.Information);\n            e.Cancel = true;\n        }\n    }\n }\n}	0
18739565	18739103	Highlight search word in Excel in c#	if (str == text.ToString())\n{\n  var cell = (range.Cells[rCnt, cCnt] as Excel.Range);\n  cell.Font.Bold = 1;\n  cell.Font.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.Red); \n}	0
30918940	11048628	SelectNodes with XPath ignoring cases in node names	string value = "aBc";\nXmlNode xmlnode = xmldoc.SelectSingleNode(string.Format("/some/path/add[translate(@key, 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz') = '{0}']", value.ToLower()));	0
20422375	20310162	get value from ascx user control to aspx page	protected void GridView1_SelectedIndexChanging(object sender, GridViewSelectEventArgs e)\n{\nGridViewRow row = GridView1.Rows[e.NewSelectedIndex];\nSession["sessionid"]= row.Cells[1].Text; \ne.Cancel = true;\n}	0
17742529	17742146	Validate domain user credentials with .NET 2	// Create an empty instance of the NetworkCredential class.\nNetworkCredential myCredentials = new NetworkCredential("", "", "");\nmyCredentials.Domain = domain;\nmyCredentials.UserName = username;\nmyCredentials.Password = password;\n\n// Create a WebRequest with the specified URL. \nWebRequest myWebRequest = WebRequest.Create(url); \nmyWebRequest.Credentials = myCredentials;\nConsole.WriteLine("\n\nUser Credentials:- Domain: {0} , UserName: {1} , Password: {2}",\n                  myCredentials.Domain, myCredentials.UserName, myCredentials.Password);\n\n// Send the request and wait for a response.\nConsole.WriteLine("\n\nRequest to Url is sent.Waiting for response...Please wait  ...");\nWebResponse myWebResponse = myWebRequest.GetResponse();\n\n// Process the response.\nConsole.WriteLine("\nResponse received sucessfully");\n\n// Release the resources of the response object.\nmyWebResponse.Close();	0
18676933	18676881	Take String from Clipboard? No assembly reference?	using System.Windows.Clipboard;	0
15722042	15721768	How to Console.Beep while (during) mouse click down?	private void Window_MouseDown_1(object sender, MouseButtonEventArgs e)\n    {\n        // Starts beep on background thread\n        Thread beepThread = new Thread(new ThreadStart(PlayBeep));\n        beepThread.IsBackground = true;\n        beepThread.Start();\n    }\n    private void PlayBeep()\n    {\n        // Play 1000 Hz for max amount of time possible\n        // So as long as you dont hold the mouse down for 2,147,483,647 milliseconds it should work.\n        Console.Beep(1000, int.MaxValue);\n    }\n\n    private void Window_MouseUp_1(object sender, MouseButtonEventArgs e)\n    {\n        //Aborts the beep with a new 1ms beep on mouse up which finishes the task.\n        Console.Beep(1000, 1);\n    }	0
4064661	4064542	Right Way to access a View Model from an existing View Model	class MainWindow : Window\n{\n     public MainWindow()\n     {\n          Initialize();\n          DataContext = new MainVM();\n     }\n\n     public void FindCustomerClick(object sender, RoutedEventArgs args)\n     {\n          CustomerListView clv = new CustomerListView();\n          clv.DataContext = (DataContext as MainVM).FindCustomer(search.Text);\n          clv.Show();\n     }\n}	0
16142408	16142313	Getting a specialised collection of objects from a base collection	public class Base {\n\n    List<Animals> animals = .... \n    ...\n    ....\n\n    public IEnumerable<T> GetChildrenOfType<T>()  \n        where T : Animals\n    {\n       return animals.OfType<T>();  // using System.Linq;\n    }\n}	0
19319707	19319347	How I get the right linq statement for filter to arraylist values in my xml file?	List<string> list = new List<string>{"NPS_DB", "NPS_IN"};\n\nstring xml = @"<plants>\n                <plant id=""DB"" display="".testDB.."" group=""NPS_DB"" />\n                <plant id=""EL"" display="".testEL.."" group=""NPS_EL"" />\n                <plant id=""IN"" display=""..testIN."" group=""NPS_IN"" />\n                <plant id=""SB"" display="".testSB.."" group=""NPS_SB"" />\n                <plant id=""BL"" display="".testBL.."" group=""NPS_BL"" />\n                <plant id=""LS"" display=""..testLS.."" group=""NPS_LS"" />\n            </plants>";\n\nvar xDoc = XDocument.Parse(xml);\n\nxDoc.Root.Descendants()\n          .Where(e => !list.Contains((string)e.Attribute("group")))\n          .ToList()\n          .ForEach(s => s.Remove());	0
3911487	3911271	How to get only one set of data from my Stored Procedure?	SqlDataReader sqlReader = sqlCmd.ExecuteReader();\nsqlReader.NextResult(); // Skip first result set.\nsqlReader.NextResult(); // Skip second result set.\nwhile (sqlReader.Read())\n{\n    var netTaxableIncome = sqlReader.GetValue(0);\n}	0
793893	793714	How can I fix this up to do generic conversion to Nullable<T>?	public static T To<T>(this IConvertible obj)\n{\n    Type t = typeof(T);\n    Type u = Nullable.GetUnderlyingType(t);\n\n    if (u != null)\n    {\n        return (obj == null) ? default(T) : (T)Convert.ChangeType(obj, u);\n    }\n    else\n    {\n        return (T)Convert.ChangeType(obj, t);\n    }\n}	0
17859760	17859688	lambdas with the standard query operators	Func<T, TResult>	0
34476325	34476237	Assigning an enum value to a parameter	var input = "value-1";\n\nvar myEnumValue = (MyValues)Enum.Parse(typeof(MyValues), input.Replace("-", ""));	0
2921834	2921313	Joining a Many to Many table	var final = (from s in Stores\n             where s.Name=name && s.isLocal && s.State==state\n                   && s.Fruits.Any(f => \n                       f.FruitClassifications.Any(fc => fc.Code == classificationType\n                                                           && fc.Type.Code == "FRT"))\n             select s).ToList();	0
15905135	15905086	Null return from C# application settings file	String MainDB = Properties.Settings.Default.MainDB;\nMessageBox.Show(MainDB);\nString MailInfo = Properties.Settings.Default.MailInfo;\nMessageBox.Show(MailInfo);\nString HousingIndexLocation = Properties.Settings.Default.HousingIndex;\nMessageBox.Show(HousingIndexLocation);	0
17224490	17223953	StackPanel - Confine to the width of the parent ListBox	ScrollViewer.HorizontalScrollBarVisibility="Disabled"	0
191596	123088	Possible pitfalls of using this (extension method based) shorthand	propertyValue1 = myObject.IfNotNull(o => o.ObjectProp).IfNotNull(p => p.StringProperty);	0
19198803	19198753	Invalid object in JSon	JArray json = JArray .Parse(text);	0
9897941	9897920	Catching MessageBox result	// Confirm if the user really wants to delete the product\nDialogResult result = MessageBox.Show("Do you really want to delete the product \"" +     productName + "\"?", "Confirm product deletion", MessageBoxButtons.YesNo,  MessageBoxIcon.Warning);\nif (result == DialogResult.Yes)\n{\n    MessageBox.Show("deleted");\n}	0
11272056	11257700	How to find paragraphs that comes under a header 1 using Microsoft.Office.Interop.Word in C#?	//get the 'next' paragraph but only if it exists\nif (paragraph.Next() != null)\n{\n     MessageBox.Show("Next paragraph:" + paragraph.Next().Range.Text.ToString());\n}	0
5811183	5810968	Naming convention for windows control in C#	liquidHydrogenCapacityTextBox\nextraKetchupCheckBox\nfileOpenMenuItem\nfavoriteFormerNSyncMemberDropDownList	0
5449890	5449104	WPF comparing strings in separate files	var csv = new[] { "aa", "bb", "cc" };\nvar text = new[] { "bb", "ee", "ff", "cc", "bb" };\n\nIEnumerable<string> collectionToBind = text.Where(t => csv.Contains(t));	0
28383879	28383830	GroupBy in Enumerable method	var res = list.GroupBy(p => p.Country, p => p)\n    .Select(p => new Report\n    {\n         Country = p.Key,\n         SumAge = p.Sum(x => x.Age)\n    });	0
25848457	25614299	Can't update variable values from IronRuby	String before = "hello world";\nString after = "changed";\n\nScriptRuntime mRuntime = Ruby.CreateRuntime();\nScriptEngine mEngine = mRuntime.GetEngine("ruby");\nScriptScope scope = mEngine.CreateScope();\nString code = "self.msg = '" + after + "'.to_clr_string";\nScriptSource script = mEngine.CreateScriptSourceFromString(code,  SourceCodeKind.Statements);\nscope.SetVariable("msg", before);\nscript.Execute(scope);\nString result = scope.GetVariable("msg");	0
19150278	19149095	Making picturebox according to value in textbox	TxtCount.Text = count.ToString();\n\n            for (int i = 0; i < count; ++i)\n            {\n                PictureBox pb = new PictureBox();\n                pb.Location = new Point((80 * i) + 5, 30);\n                pb.Size = new Size(75, 75);\n                pb.BorderStyle = BorderStyle.Fixed3D;\n                pb.ImageLocation = "";\n                this.Controls.Add(pb);\n                pb.BringToFront();\n            };	0
7891420	7890587	Windows Azure: web application on several instances, authentication?	private void OnServiceConfigurationCreated(object sender, \n    ServiceConfigurationCreatedEventArgs e)\n{\n    var sessionTransforms =\n        new List<CookieTransform>(\n            new CookieTransform[] \n            {\n                new DeflateCookieTransform(), \n                new RsaEncryptionCookieTransform(\n                  e.ServiceConfiguration.ServiceCertificate),\n                new RsaSignatureCookieTransform(\n                  e.ServiceConfiguration.ServiceCertificate)  \n            });\n    var sessionHandler = new \n     SessionSecurityTokenHandler(sessionTransforms.AsReadOnly());\n    e.ServiceConfiguration.SecurityTokenHandlers.AddOrReplace(\n        sessionHandler);\n}	0
13093176	13093139	Site-Wide global variables	public class MyValues\n{\n    private readonly static MyValues instance = new MyValues();\n\n    private MyValues() { }\n\n    public static MyValues Instance\n    {\n        get { return instance; }\n    }\n\n    public string SomeValue { get; set; }\n\n    public int SomeOtherValue { get; set; }\n}	0
26236005	26217217	C# - HttpRequest asking for second login credentials	string encoded = Convert.ToBase64String(Encoding.GetEncoding("ISO-8859-1")\n    .GetBytes(userName + ":" + userPassword));\nHttpRequestMessage mess = new HttpRequestMessage(HttpMethod.Get, \n    new Uri("https://ssl.mywebsite.nl/"));\nmess.Headers.Add("Authorization", "Basic " + encoded);\nwebView.NavigateWithHttpRequestMessage(mess);	0
33079902	33079830	Get a particular instance of a class	protected override void Seed(RecipeApplication.Models.RecipeApplicationDb context)\n{\n    var defaultUOM = new UnitOfMeasureModel { Name = "Gram", Abbreviation = "g" };\n\n    if (!context.UnitOfMeasures.Any())\n    {\n        context.UnitOfMeasures.AddOrUpdate(\n            u => u.Id,\n            defaultUOM,\n            new UnitOfMeasureModel { Name = "Kilogram", Abbreviation = "kg"},\n            new UnitOfMeasureModel { Name = "Milligram", Abbreviation = "mg" }\n            );\n    }\n\n    if (!context.Ingredients.Any())\n    {\n        context.Ingredients.AddOrUpdate(\n            i => i.Id,\n            new IngredientModel { Name = "Italiaanse Ham", DefaultUOM = defaultUOM\n            );\n    }\n\n}	0
30922019	30921873	Getting all Employees under a Manager C#	IList<Employee> GetEmployees(Employee manager)\n{\n    var result = new List<Employee>();\n\n    var employees = _employeeDb.Employees\n                               .Where(e => e.ManagerEmployeeNumber == manager.EmployeeNumber)\n                               .ToList();\n\n    foreach (var employee in employees)\n    {\n        result.Add(employee);\n        result.AddRange(GetEmployees(employee));\n    }\n\n    return result;\n}	0
3428254	3428242	How do I truncate a list in C#?	var itemsOneThroughTwenty = myList.Take(20);\nvar itemsFiveThroughTwenty = myList.Skip(5).Take(15);	0
16359220	16359046	XML Deserialization with Parent Attribute	var items = XDocument.Parse(xml)\n                .Descendants("Item")\n                .Select(c => new Item(c.Parent.Attribute("Name").Value, \n                                      c.Attribute("Name").Value, \n                                      c.Attribute("Signature").Value))\n                .ToList();	0
11034847	11034774	Sorting XML With LINQ	// You need this namespace\nusing System.Xml.XPath;\n\n// use this in your query\norderby (string)s.XPathSelectElement(sortColumn)	0
8756160	8755745	Convert inheritance with interface from C# to VB.NET	Interface ICA\n    Property NumberA() As Integer\nEnd Interface\nInterface ICB\n    Property NumberB() As Integer\nEnd Interface\n\nClass A\n    Implements ICA\n    Public Property NumberA() As Integer Implements ICA.NumberA\n        '' etc\n    End Property\nEnd Class\n\nClass B\n    Inherits A\n    Implements ICA, ICB\n\n    Public Property NumberB() As Integer Implements ICB.NumberB\n        '' etc...\n    End Property\nEnd Class	0
30863318	30848579	Http Get Request for IpDBInfo using an IP Address	string key = "Your API key";\n        string ip = "IP address to check";\n        string url = "http://api.ipinfodb.com/v3/ip-city/?key=" + key + "&ip=" + ip;\n\n        HttpWebRequest webReq = (HttpWebRequest)WebRequest.Create(string.Format(url));\n\n        webReq.Method = "GET";\n\n        HttpWebResponse webResponse = (HttpWebResponse)webReq.GetResponse();\n\n        Stream answer = webResponse.GetResponseStream();\n\n        StreamReader response = new StreamReader(answer);\n\n        string raw = response.ReadToEnd();\n\n        char[] delimiter = new char[1];\n\n        delimiter[0] = ';';\n\n        string[] rawdata = raw.Split(delimiter);\n\n        ViewData["Response"] = "Country Code: " + rawdata[3] + " Country Name: " + rawdata[4] + " State: " + rawdata[5] + " City: " + rawdata[6];\n\n        response.Close();	0
19336441	19286042	Windows Phone 8 - Creating a web-style form with XAML	private void HandleUsernameKeyDown(object sender, System.Windows.Input.KeyEventArgs e)\n{\n    if (e.Key == Key.Enter || e.PlatformKeyCode == 0x0A)\n    {\n        e.Handled = true;\n        PasswordText.Focus();\n    }\n}	0
21280771	21280608	Need Generic Constructor in C#	public Error(Enum errorType, string errorMessage)\n{\n    ErrorCode = (int)(object)errorType;\n    ErrorMessage = errorMessage;\n}	0
24707400	24707247	Convert String with GMT foramt to Datetime	String inputString="Fri Jul 11 2014 01:30:00 GMT-0700 (Pacific Daylight Time)";\n// we have no need of the parenthetical, get rid of it\ninputString = Regex.Replace(inputString, " \\(.*\\)$", "");\n// exact string format ... 'GMT' is literal\nDateTime theDate = DateTime.ParseExact(inputString,"ddd MMM dd yyyy HH:mm:ss 'GMT'zzz",\n    System.Globalization.CultureInfo.InvariantCulture);	0
3779753	3779729	how I can show the sum of in a datagridview column?	int sum = 0;\nfor (int i = 0; i < dataGridView1.Rows.Count; ++i)\n{\n    sum += Convert.ToInt32(dataGridView1.Rows[i].Cells[1].Value);\n}\nlabel1.text = sum.ToString();	0
672622	672593	Creating a Parent Node for XML document in C#	XmlNode MYNODE = doc.CreateNode("element", "connectionStrings", "");\nMYNODE.InnerText = " ";	0
1423213	1423198	ASP .NET C# - Format a MySQL date field properly in a listview	DateTime dateTimeObject = Convert.ToDateTime("9/14/2009 12:00:00 AM");\ndateTimeObject.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture);	0
26248518	26247814	Split list of objects to sublist without linq	List<List<object>> newList = new List<List<object>>();\n    void SplitObj(int objectsPerPart)\n    {\n        if (BL == null || BL.Count < 1)\n            return;\n\n        List<object> current = new List<object>();\n        current.Add(BL[0]);\n        for (int i = 1; i < BL.Count; i++)\n        {\n            if (i % objectsPerPart == 0)\n            {\n                newList.Add(current);\n                current = new List<object>();\n            }\n            current.Add(BL[i]);\n        }\n    }	0
9276073	9275810	Merge separate DLL's into a single assembly for open source distribution	readme.txt	0
2499109	2499095	How to assign a shortcut key (something like Ctrl+F) to a text box in Windows Forms?	protected override bool ProcessCmdKey(ref Message msg, Keys keyData)\n{\n    if (keyData == (Keys.Control | Keys.S))\n    {\n        MessageBox.Show("Do Something");\n        return true;\n    }\n    return base.ProcessCmdKey(ref msg, keyData);\n}	0
2958449	2527499	Webbrowser control: Get element value and store it into a variable	using System.Windows.Forms;\n\nnamespace TestWebBrowser\n{\n    public partial class Form1 : Form\n    {\n        public Form1()\n        {\n            InitializeComponent();\n\n            webBrowser1.DocumentText = @"<html><body><table>\n    <tbody>\n    <tr>\n\n        <td><label class=""label"">Name</label></td>\n        <td class=""normaltext"">John Smith</td>\n    </tr>\n    <tr>    <td><label class=""label"">Email</label></td>\n        <td><span class=""normaltext"" id=""e1"">jsmith@hotmail.com</span></td>\n</tr>\n    </tr>\n    </tbody>\n</table>\n</body>\n</html>";\n        }\n\n        private void button1_Click(object sender, System.EventArgs e)\n        {\n            HtmlElement e1 = webBrowser1.Document.GetElementById("e1");\n            MessageBox.Show(e1.InnerText);\n        }\n    }\n}	0
26605053	26604836	C# data to Java	import static java.nio.file.StandardWatchEventKinds.*;\n\nPath dir = ...;\ntry {\n    WatchKey key = dir.register(watcher,\n                           ENTRY_CREATE,\n                           ENTRY_DELETE,\n                           ENTRY_MODIFY);\n} catch (IOException x) {\n    System.err.println(x);\n}	0
5739482	5739448	how to create a user's folder for a new registered user in asp.net MVC (C#)?	System.IO.Directory.CreateDirectory	0
10970659	10970626	How to set datasource of listbox from generic list of class	ListBox1.DataSource = ((List<Users>) Application["Users_On"]);\n  ListBox1.DataTextField = "Name";\n  ListBox1.DataBind();	0
16961462	16958493	Load an image from media library onto canvas with WriteableBitmap image?	if (e.TaskResult == TaskResult.OK)\n{\n    BitmapImage bi = new BitmapImage();\n    bi.SetSource(e.ChosenPhoto);\n    WriteableBitmap b = new WriteableBitmap(bi);\n    Image img = new Image();\n    img.Source = b;           \n    Canvas.SetLeft(img, 10);\n    Canvas.SetTop(img, 10);\n    area.Children.Add(img);    \n}	0
2457210	2448692	How to combine 2 linq statments with groupby clause into 1	var adjustmentChangeBySubBook =\n    from provision in\n        (from currentProvision in currentProvisions select new\n            {\n                currentProvision.SubBook,\n                CurrentUSD = currentProvision.ProvisionUSD,\n                PreviousUSD = 0\n            }).Concat\n        (from prevProvision in prevProvisions select new\n            {\n                prevProvision.SubBook,\n                CurrentUSD = 0,\n                PreviousUSD = prevProvision.ProvisionUSD\n            })\n    group provision by provision.SubBook into subBookGrouping select new\n    {\n        subBookGrouping.Key,\n        Value = subBookGrouping.Sum(t => t.CurrentUSD - t.PreviousUSD)\n    };	0
165891	165284	Flowlayout panel not display the scroll bar after some resizes	.PerformLayout()	0
27135883	27135690	how to reorder worksheet positions in C#	ws.Position = 1;	0
7313132	7313113	Need to join two strings if both contain values, or return one value if first is NULL	var recent = from p in dc.Properties\n        orderby p.modtime descending\n        where p.status == "Current"\n        select new\n       {\n            rsub = (p.subNumber).ToString(),\n            rnumber = (p.streetNumber).ToString(),\n            rnum = string.IsNullOrEmpty((p.subNumber).ToString()) ? (p.streetNumber).ToString() : (p.subNumber).ToString() + "/" + (p.streetNumber).ToString(),\n            rstreet = p.street,\n            rsuburb = p.suburb,\n            rurl = p.propertyURL,\n        };	0
21651607	21651420	How to bind Line.StrokeThickness property with Slider value in code behind?	Binding myBinding = new Binding("Value");\nmyBinding.Source = mySlider;\nmyLine.SetBinding(Shape.StrokeThicknessProperty, myBinding);	0
5974305	5974123	using SELECT results as INSERT INTO VALUES shows CLR type error	Insert DATA_TEMP( ITEM, Q1, Q2, Q3, Q4, TOTAL )\nSelect D2.ITEM\n    , Min( Case When QTR = 1 Then D1.AMOUNT End ) As Q1\n    , Min( Case When QTR = 2 Then D1.AMOUNT End ) As Q2\n    , Min( Case When QTR = 3 Then D1.AMOUNT End ) As Q3\n    , Min( Case When QTR = 4 Then D1.AMOUNT End ) As Q4\n    , Sum( AMOUNT ) As Total\nFrom DATA As D1\n    Join DATA_2 As D2\n        On D2.ID = D1.ID\nWhere ITEM = @item\n    And FY = @fy\n    And BU = @bu\n    And PERIOD = @per\nGroup By D2.ITEM	0
2403186	2403143	C# comparing two files regex problem	static void Compare(string alpha, string beta)\n    {\n        HashSet<string> alphaContent = new HashSet<string>();\n        StreamReader reader = new StreamReader(alpha);\n        while (!reader.EndOfStream)\n            alphaContent.Add(reader.ReadLine());\n        reader.Close();\n\n        reader = new StreamReader(beta);\n        while (!reader.EndOfStream)\n        {\n            string fullpath = reader.ReadLine();\n            string filename = Path.GetFileNameWithoutExtension(fullpath);\n            if (alphaContent.Contains(filename))\n            {\n                File.AppendAllText(@"C:\array_tech.txt", fullpath);\n            }\n        }\n        reader.Close();\n    }	0
4140518	4140484	C#, LInq, Entity Framework 4: Split a table in to a two dimensional array using Linq	IEnumerable<Category> items = ...;\nvar groups = items.GroupBy(x => x.classid);\nvar arrays = groups.Select(x => \n    x.Select(y => new { itemid = y.itemid, label = y.label }).ToArray()\n).ToArray();	0
12502949	12402385	How to ignore the White spaces and new lines in XML	XElement root = XElement.Load(file);\nvar catalogs = root.Descendants("catalog");\nvar books = catalogs.SelectMany(c => \n    c.Descendants("book").Select(book => new\n    {\n        Id = book.Attribute("id").Value,\n        Title = book.Descendants("title").First().Value\n    }))\n    //.OrderBy(b => b.Title)  // sort by title or id if you'd like.\n    .ToArray();	0
7697834	7697538	sending binary files through TCP sockets c	sockets[number].Receive(coming[current], bufferSize, 0);	0
15385528	15385355	How can 2 controllers communicate with 1 view in asp.net mvc	return View("commonView");	0
29988081	29980580	Deserialize JSON object property to string	class JsonConverterObjectToString : JsonConverter\n    {\n        public override bool CanConvert(Type objectType)\n        {\n            return (objectType == typeof(JTokenType));\n        }\n\n        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)\n        {\n            JToken token = JToken.Load(reader);\n            if (token.Type == JTokenType.Object)\n            {\n                return token.ToString();\n            }\n            return null;\n        }\n\n        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)\n        {\n            //serializer.Serialize(writer, value);\n\n            //serialize as actual JSON and not string data\n            var token = JToken.Parse(value.ToString());\n            writer.WriteToken(token.CreateReader());\n\n        }\n    }	0
26865921	26865591	Sending XML with AJAX POST request to ASP.NET page?	protected void Page_Load(object sender, EventArgs e)\n    {\n\n        Page.Response.ContentType = "text/xml";\n        System.IO.StreamReader reader = new System.IO.StreamReader(Page.Request.InputStream);\n        String xml = reader.ReadToEnd();\n        String xmlData = HttpUtility.UrlDecode(xml);\n        System.Diagnostics.Debug.WriteLine(xmlData);\n\n    }	0
20554632	20547968	Check range of integer in a custom control	public int LowerValue {\n  get { return LowerValue; }\n  set { if(valid) LowerValue = value; }\n}	0
12487652	12487369	What is SMTP Server Address and how to get SMTP Server Address?	// setup mail message\n        MailMessage message = new MailMessage();\n        message.From = new MailAddress("from e-mail");\n        message.To.Add(new MailAddress("to e-mail"));\n        message.Subject = "Message Subject";\n        message.Body = "Message Body";\n\n        // setup mail client\n        SmtpClient mailClient = new SmtpClient("smtp.gmail.com");\n        mailClient.Credentials = new NetworkCredential("youraccount@gmail.com", "yourGmailPassword");\n\n        // send message\n        mailClient.Send(message);	0
6774334	6774294	C# Variable Naming	string myString	0
1565557	1565541	How can I extract the URL of a Web Reference added to a C# project?	var url = myClass.Url;	0
8894298	8893568	How to solve confilct between two namespace?	using System.Windows.Forms;\nusing Cy.GlobalSettings.ChartSettings;\nusing CyFont = Cy.GlobalSettings.ChartSettings.Font // This is the full name of the Font class which is causing the conflict. \n\n\nFont y; // class from System.Windows.Forms\nCyFont x; // class from Cy.GlobalSettings.ChartSettings	0
20568838	20568070	Change DataGridView Cell Value Programmatically	void dgv_CellValidated(object sender, DataGridViewCellEventArgs e) {\n  string cellValue = dgv.Rows[e.RowIndex].Cells[e.ColumnIndex].FormattedValue.ToString();\n  if (cellValue.Contains('G') || cellValue.Contains('g')) {\n    dgv.Rows[e.RowIndex].Cells[e.ColumnIndex].Value = "abc";\n  }\n}	0
10025681	10025384	Install other apps with our setup - vs2010 Desktop App Deployment	namespace CLT\n{\n    [RunInstaller(true)]\n    public partial class ClientInstall : Installer\n    {\n        public ClientInstall()\n        {\n            InitializeComponent();\n        }\n\n        public override void Install(IDictionary stateSaver)\n        {\n                base.Install(stateSaver);\n                System.Diagnostics.Process.Start(@"\Powerpoint.exe");\n        }\n}	0
15128933	15087223	Listening to a WCF service from a Windows Forms Application	[ServiceContract(Namespace=ServiceContractNamespaces.ServiceContractNamespace,\n                 CallbackContract = typeof(ISupportTicketCallback))]\npublic interface ISupportTicketService\n{\n           [OperationContract]\n           int CreateSupportTicket (SupportTicket supportTicket);\n}\npublic interface ISupportTicketCallback\n{\n        [OperationContract]\n        void SupportTicketCreated(int supportTicketId);\n}	0
27187627	27187474	Using LINQ to build a new collection	var collection = visits.GroupBy(x => x.VisitDate)\n                       .Select(x => new VisitDuration\n                              {\n                                  VisitDate = x.Key,\n                                  Duration = Convert.ToInt32(x.Average(z => z.VisitDuration))\n                              });	0
22454300	22450735	how to show one product pic on page load	var images = (from p in _db.Tbl_Prods\n              join img in _db.Tbl_Imgs on p.ProdId equals img.ProdId \n              group img by p.ProdId into g\n              select new { g.Key, MaxImageId = g.Max(x => x.ImageId) })\n              .Select(x => x.MaxImageId).ToArray();\n\n var prods = (from p in  _db.Tbl_Prods\n              join img in _db.Tbl_Imgs on p.ProdId equals img.ProdId \n              where images.Contains(img.ImageId)\n              select new \n              { \n                     ProdId = x.ProdId,\n                     ProdCode = x.ProdCode,\n                     ProdName = x.ProdNameRu,\n                     ImgUrl = img.ImgUrl\n              });	0
6262119	6261733	Linkify URLs in string with Regex expression	var regex = new Regex("some valid regex");\nvar text = "your original text to linkify";\nMatchEvaluator evaluator = LinkifyUrls;\ntext = regex.Replace(text, evaluator);\n\n...\n\nprivate static string LinkifyUrls(Match m)\n{\n    return "<a href=\"" + m.Value + "\">" + m.Value + "</a>";\n}	0
10447319	10446142	how to insert / edit values from repeaters dynamically?	protected void btnInsert_Click(object sender, EventArgs e)\n  {\n    String connectionString = ConfigurationManager.ConnectionStrings["DbConnect"].ConnectionString;\n    String queryString = "";\n     using (SqlConnection connection = new SqlConnection(connectionString))\n    {\n        foreach (RepeaterItem item in Repeater1.Items)\n       {\n        TextBox Subject_Id = (TextBox)item.FindControl("Subject_Id");\n        TextBox Subject_Name = (TextBox)item.FindControl("Subject_Name");\n        TextBox Marks = (TextBox)item.FindControl("Marks");\n\n        queryString = "Insert into result VALUES (id='"+@Subject_Id+"',name='"+@Subject_Name+"',marks='"+@Marks+"')";\n\n        SqlCommand command = new SqlCommand(queryString, connection);\n\n        // execute the query to update the database\n        cmd.ExecuteNonQuery();\n        }\n    }\n    //call the function to load the gridview if it is lost on postback.\n  }	0
27471019	27470993	Parse string to object	public class MenuJson\n{\n    [JsonProperty("id")]\n    public string id { get; set; }\n\n    [JsonProperty("children")]\n    public List<MenuJson> children { get; set; }\n}\n\nvar list = JsonConvert.DeserializeObject<List<MenuJson>>(json);	0
1407778	1407140	Accessing application members?	var myApp = Application.Current as App;\nvar n = myApp.NameOfPropertyAdded;	0
20449760	20449517	Find every same letters in a word	public class Hangman\n{\n    string HangmanWord = "cookies";\n    string WordUserCanSee = "-------";\n\n    public Hangman()\n    {\n        IsThereA("o");\n        IsThereA("f");\n        IsThereA("k");\n        IsThereA("w");\n        IsThereA("i");\n        IsThereA("c");\n        IsThereA("s");\n        IsThereA("e");\n    }\n\n\n    public bool IsThereA(string guessLetter)\n    {\n        bool anyMatch = false;\n        for (int i = 0; i < HangmanWord.Length; i++)\n        {\n            if (HangmanWord.Substring(i, 1).Equals(guessLetter))\n            {\n                anyMatch = true;\n                WordUserCanSee = WordUserCanSee.Substring(0, i) + guessLetter + WordUserCanSee.Substring(i + 1);\n            }\n        }\n\n        return anyMatch;\n    }\n}	0
33061896	33061779	How to get Nationality of a Country asp.net c#	//Init your dictonary as like this\n        Dictionary<string, string> countryNationality = new Dictionary<string, string>() { { "India", "Indian" }, { "England", "British" } };\n        // Now access the value like this \n        string nationality = countryNationality["England"];//will give you British\n        string anotherNationality = countryNationality["India"];//will give you British	0
31019835	31018947	set default value for nulls in result of a linq join	var result= from a in tableA join b in tableB on b.tableAid equals a.id \n            into grp from c in grp.DefaultIfEmpty()\n            select new {id = a.id , name = a.name , number = c != null ? (c.number ?? 0) : 0 }	0
15600326	15600210	How to select an instance of a class or variable using (i)	Hand[] playerCards = new Hand[4]; // or however many players you have.\nfor (int i = 0; i < playerCards.length; i++) {\n   playerCards[i] = new Hand(cards);\n   // all of your initialization, bank, bet amount, etc.\n}	0
3265271	3265103	Serialize xmls element attributes to properties of child object	public class Vertex : Point\n{\n    [XmlIgnore]\n    public Point Normal { get; set; }\n\n    [XmlAttribute]\n    public float nX\n    {\n        get { return Normal.X; }\n        set { Normal.X = value; }\n    }\n\n    //etc\n}	0
19414379	19414351	C# Dynamic where for a collection	oc.Where(x => words.Any(w => x.SearchData.IndexOf(w) > -1))	0
8620661	8620629	String array in C#	List<string> this_is_a_list_of_strings = new List<string>();\nforeach (string line in assignment_lines)\n{\n    this_is_a_list_of_strings.AddRange(line.Split('='));\n}\nstring[] strArray = this_is_a_list_of_strings.ToArray();	0
34550163	34550119	C# - How to copy rows from table in SQL server and insert into DataTable?	DataTable dt = new DataTable();\n using (SqlConnection sqlConn = new SqlConnection(connectionString))\n {\n     using (SqlCommand cmd = new SqlCommand("SELECT * FROM Holidays", sqlConn))\n     {\n         SqlDataAdapter da = new SqlDataAdapter(cmd);\n         da.Fill(dt);\n     }\n }	0
9427550	9426673	Web app blocked while processing another web app on sharing same session	the session is getting shared across the two web apps	0
19784438	19784158	How to list and retrieve all IIS web server instances on a network?	Get-Service IIS* -computer ... #(all computers in the domain or on the network)	0
31687337	31687028	How to change visual state from DependencyPropertyChanged handler?	protected override void OnApplyTemplate()\n        {\n            ...\n            base.OnApplyTemplate();\n            if (IsSelected)\n            {\n                VisualStateManager.GoToState(this, "Selected", true);\n            }\n         }	0
4842690	4842676	Getting a particular Portion of Image (Picture)	Bitmap original = new Bitmap( @"C:\SomePath" );\nRectangle srcRect = new Rectangle( 0, 0, 64, 64 );\nBitmap cropped = (Bitmap)original.Clone( srcRect, original.PixelFormat );	0
20239177	20238951	How select data dividual character uppercase and lowercase in DataTable?	dt.CaseSensitive = True	0
17868469	17867996	Access Top Row In Gridview from DataTable When Button Clicked	GridView1.Rows[0].Cells[0].Text	0
244228	244219	Sort List<DateTime> Descending	docs.Sort((x, y) => y.StoredDate.CompareTo(x.StoredDate));	0
18667145	18666899	How to match a sequence in a List with Linq?	public bool SubsequenceEquals<T>(IEnumerable<T> masterList, IEnumerable<T> childList)\n{\n        // find all indexes \n        var matches = masterList.Select((s, i) => new {s, i})\n                                .Where(m => m.s.Equals(childList.First()))\n                                .Select (m => m.i);\n\n        return matches.Any(m => Enumerable.SequenceEqual(childList, masterList\n                                                                        .Skip(m)\n                                                                        .Take(childList.Count())\n                                                        ));\n}	0
32279735	32262272	How to use multiple datasets in rdlc c# report	DataSet dsr = new DataSet();\n_con = new SqlConnection(_strCon);\n\n_adp = new SqlDataAdapter("Select * from tbl_cad",_con);\nDataTable tbl1 = new DataTable();\ntbl1.TableName = "TableNameForReport";\n_adp.Fill( tbl1 );\n\n_adp = new SqlDataAdapter("Select * from OtherTable",_con);\nDataTable tbl2 = new DataTable();\ntbl2.TableName = "AnotherTableNameForReport";\n_adp.Fill( tbl2 );\n\ndsr.Tables.Add( tbl1 );\ndsr.Tables.Add( tbl2 );	0
4480265	4480245	Get keys as List<> from Dictionary for certain values	var values = ItemChecklist.Where(item => item.Value).Select(item => item.Key).ToList();	0
7135065	7135058	C# Message Box, variable usage	MessageBox.Show(string.Format ("You are right, it only took you {0} guesses!!!", numGuesses ), "Results", MessageBoxButtons.OK);	0
32323025	32322954	Formatting a float to string at constructor level	public string OpenPositionFormatted\n{\n    get { return convert(OpenPosition); }\n}	0
25788473	25787566	Ionic Zip Extract only particular folder	var existingZipFile = "name of the file.zip";\n        var targetDirectory = "name of the folder";\n\n        using (ZipFile zip = ZipFile.Read(existingZipFile))\n        {\n            foreach (ZipEntry e in zip.Where(x => x.FileName.StartsWith("Sub directory 1")))\n            {\n                e.Extract(targetDirectory);\n            }\n        }	0
7771757	7771718	Extact multiple filenames from multiple paths into multiple strings	var fileNames = myString.Split('|').Select(s => Path.GetFileName(s));	0
21107869	21107782	Email mask for MaskedTextBox in C#	bool IsValidEmail(string email)\n{\n    try {\n        var mail = new System.Net.Mail.MailAddress(email);\n        return true;\n    }\n    catch {\n        return false;\n    }\n}	0
4517585	4517548	How to access the files that are in USB device?	DirectoryInfo di = new DirectoryInfo(@"C:\");\nFileInfo[] fi = di.GetFiles();\nFileInfo[] fiFiltered = di.GetFiles("*.txt");\nFileInfo[] fiFilteredAndSearchOption = di.GetFiles("*.txt", SearchOption.AllDirectories);	0
653099	653087	datetime conversion c#	DateTime when = DateTime.ParseExact("Mon Mar 16 14:21:27 +0000 2009",\n    "ddd MMM dd HH:mm:ss zzzz yyyy",\n    CultureInfo.InvariantCulture);	0
30017875	30017773	Sort a bigger 2d-array in C#	string[][] array = new string[][]\n{\n    new [] {"cat", "dog"},\n    new [] {"bird", "fish"},\n};\n\nvar result = array.OrderBy(a => a[1]);	0
5940660	5940361	Trying to add a namespace with XmlTextWriter using a memorystream	writer.WriteStartElement(prefix, "ISBN", "urn:samples");	0
28953154	28952739	Read Excel file using OpenXML	using (SpreadsheetDocument doc = SpreadsheetDocument.Open(filePatah + "\\" + fileName, false))\n{\n   WorkbookPart workbookPart = doc.WorkbookPart;\n   WorksheetPart worksheetPart = workbookPart.WorksheetParts.First();\n   SheetData sheetData = worksheetPart.Worksheet.Elements<SheetData>().First();\n\n   ArrayList data = new ArrayList();\n   foreach (Row r in sheetData.Elements<Row>())\n   {\n      foreach (Cell c in r.Elements<Cell>())\n      {\n        if (c.DataType != null && c.DataType == CellValues.SharedString)\n        {\n            var stringId = Convert.ToInt32(c.InnerText); // Do some error checking here\n            data.Add(workbookPart.SharedStringTablePart.SharedStringTable.Elements<SharedStringItem>().ElementAt(stringId).InnerText);\n        }\n      }\n   }\n}	0
12270428	12269949	How do I transform an array of dimensions (100, 1) into 2 separate arrays in C#?	for (lngCounter = 0; lngCounter < arrData.Length; lngCounter++)\n            {\n                arrA[lngCounter] = arrData[lngCounter][0];\n                arrB[lngCounter] = arrData[lngCounter][1];\n            }	0
1534625	1533660	How can I use the EntityModelSchemaGenerator to generate less then my entire model?	EdmGen2 /RetrofitModel "Server=(local);Integrated Security=true;Initial Catalog=AdventureWorks;" "System.Data.SqlClient" "AVWorks"	0
15786692	15785091	Is there any implementation to Remove by Key and get the Value at the same time?	Dictionary.Remove()	0
7194568	7194532	string.format equivalence in java	String formatted = String.format("%s - (%s)", myparam1, myparam2);	0
31885391	31885161	Tell if Concurrent Queue updated without looping	while (true) {\n   var info = collection.Take();\n   doStuff(info);\n}	0
31273745	31273416	How to disable all resize possibilities for a window?	public partial class Form1 : Form\n{\n    public Form1()\n    {\n        InitializeComponent();\n        this.Resize += new EventHandler(Form1_Resize);\n    }\n\n    void Form1_Resize(object sender, EventArgs e)\n    {\n        if (WindowState == FormWindowState.Minimized)\n        {\n            this.WindowState = FormWindowState.Normal;\n        }\n\n    }\n}	0
22627920	22627683	Make a phone call from C#	using Microsoft.Phone.Tasks;\n\nPhoneCallTask phoneCallTask = new PhoneCallTask();\n\nphoneCallTask.PhoneNumber = "2065550123";\nphoneCallTask.DisplayName = "Gage";\nphoneCallTask.Show();\n\n\n\nhttp://msdn.microsoft.com/en-us/library/windowsphone/develop/hh394025(v=vs.105).aspx	0
26926643	26903786	Watin Internet Explorer how to start in-private mode?	//gen random url so we can find the window later\n    Random rnd = new Random();\n    int id = rnd.Next(1000, 10000); \n    string url = "id" + id+".com";\n    //opening explorer\n    Process.Start("IExplore.exe", "-private -nomerge " + url);\n    browser = Browser.AttachTo<IE>(Find.ByUrl(new Regex(url)));\n    browser.GoTo("http://www.google.com");	0
29431688	29428179	redirecting from c# class to a xaml page with parameters and catch them in the xaml page	private Page _selectedPage;\nprivate string _simpleString;\n\npublic string SimpleString\n{\n   get { /* ... */ }\n   set \n   {\n        _simpleStringProperty = value;\n        if (value.Equals("Pie"))\n        {\n            SelectedPage = new PieChart("test");\n        }\n        /* rest of the setter */\n   }\n}	0
3870981	3870918	replace a string within a range in C#	StringBuilder myStringBuilder = new StringBuilder(myString);\nmyStringBuilder.Replace("A", "B", 5000, 500);\nmyString = myStringBuilder.ToString();	0
6826577	6826390	how to convert Image to Data URI for Html with C#?	public static string GetDataURL(string imgFile)\n        {\n            return "<img src=\"data:image/" \n                        + Path.GetExtension(imgFile).Replace(".","")\n                        + ";base64," \n                        + Convert.ToBase64String(File.ReadAllBytes(imgFile)) + "\" />";\n        }	0
11797813	11796986	Using RegEx to read through a CSV file	public List<string> SplitCSV(string input, List<string> hot)\n    {\n\n        Regex csvSplit = new Regex("(([^,^\'])*(\'.*\')*([^,^\'])*)(,|$)", RegexOptions.Compiled);\n\n        foreach (Match match in csvSplit.Matches(input))\n        {\n            line.Add(match.Value.TrimStart(','));\n        }\n        return line; \n    }	0
26937534	26937222	In a Control extension, Override or addHandler?	sealed class MyDataGrid : DataGrid { ... }	0
4778896	4778886	How can I get computer name and IP address of local computer	textBox1.Text = "Computer Name: " + Environment.MachineName\n\ntextBox2.Text = "IP Add: " + Dns.GetHostAddresses(Environment.MachineName)[0].ToString();	0
1890436	1890427	C# Linq finding duplicate row	var qry =  from m in context.Collections\n           group m by new { m.city, m.name } into grp\n           where grp.Count() > 1\n           select grp.Key;	0
5488935	5488282	Money in SQL Server	Math.Round(value - 0.00005, 4, MidpointRounding.AwayFromZero));	0
27979097	27978653	C# - Name a radio button with a string and access its properties	Control[] ArrControls = this.Controls.Find("radioButtonTimer"+buttonID+"_CountDown");\nif(ArrControls.Where(c => (c as RadioButton).Checked).ToList().Count > 0)\n{\n  // Checked Radio Buttons\n}\nelse\n{\n\n}	0
2968916	2968857	Refactoring - Speed increase	var columnsToAdd = report.ReportDatas\n                    .SelectMany(r => r.ReportDataColumns)\n                    .Select(rdc => rdc.Name)\n                    .Distinct()\n                    .Where(name => !string.IsNullOrEmpty(name));	0
34509135	34508626	How to get and set property of an object which might be property of another object?	var property = constraint.GetType().GetProperty("Parameter"); \n\nif (property != null)\n{\n    var parameter = property.GetValue(constraint);\n    if (parameter != null)\n    {\n        var parameterName = parameter.GetType().GetProperty("Name").GetValue(parameter).ToString();\n        if (parameterName == "Length")\n        {\n            property.SetValue(constraint, myLengthParameter);\n        }\n    }        \n}	0
31124809	31123352	Set Download Location With EPPlus	using (ExcelPackage pck = new ExcelPackage())\n{\n    var ws = pck.Workbook.Worksheets.Add("Demo");\n    ws.Cells[1, 2].Value = "Excel Test";\n\n    var fileBytes = pck.GetAsByteArray();\n    Response.Clear();\n\n    Response.AppendHeader("Content-Length", fileBytes.Length.ToString());\n    Response.AppendHeader("Content-Disposition",\n        String.Format("attachment; filename=\"{0}\"; size={1}; creation-date={2}; modification-date={2}; read-date={2}"\n            , "temp.xlsx"\n            , fileBytes.Length\n            , DateTime.Now.ToString("R"))\n        );\n    Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";\n\n    Response.BinaryWrite(fileBytes);\n    Response.End();\n}	0
32478388	32478089	How to add items in unordered list?	HtmlGenericControl liControl;\n\nif (startPage > 1) {\n    liControl = new HtmlGenericControl("li");\n    liControl.InnerHtml = "First...";\n    pagenav.Controls.Add(liControl);\n}\n\nfor (int i = startPage; i <= endPage; i++) { \n    liControl = new HtmlGenericControl("li");\n    liControl.InnerHtml = i.ToString();\n    pagenav.Controls.Add(liControl);\n}\n\nif (endPage < totalPage) {\n    liControl = new HtmlGenericControl("li");\n    liControl.InnerHtml = "...Last";\n    pagenav.Controls.Add(liControl);\n}	0
24382429	24382114	Populate a gridview with user-input data	protected void Page_Load(object sender, EventArgs e)\n{\n  if (IsPostBack == false)\n  {\n    DataTable date = new DataTable();\n    date.Columns.Add("Column 1", typeof(string));\n    date.Columns.Add("Column 2", typeof(string));\n    Session["dte"] = date;\n  }\n}\n\nprotected void addbutton_Click(object sender, ImageClickEventArgs e)\n{\n  DataTable date = (DataTable)Session["dte"];\n  DataRow dr = date.NewRow();\n  dr["Column 1"] = TextBox1.Text.Trim();// Your Values\n  dr["Column 2"] = TextBox2.Text.Trim();// Your Values\n  date.Rows.Add(dr);\n  GridView1.DataSource = date;\n  GridView1.DataBind();\n }	0
897994	897038	When using a LINQ Where clause on a Dictionary, how can I return a dictionary of the same type?	Dictionary<string, string> getValidIds(\n  Dictionary<string, string> SalesPersons,\n  List<string> ids\n)\n{\n  HashSet<string> idsFast = new HashSet<string>(ids);\n  Dictionary<string, string> result = SalesPersons\n    .Where(kvp => idsFast.Contains(kvp.Key))\n    .ToDictionary(kvp => kvp.Key, kvp => kvp.Value)\n  return result;\n}	0
12081318	12081258	How to pause task execution	Task.Factory.StartNew(() =>\n                    {\n                        ExtractStuff(fileName);\n                    },TaskCreationOptions.LongRunning);	0
6364917	4776049	Syntax for virtual members	public virtual IList<GradeEntity> Grades { get; private set; }\n\npublic CandidateEntity()\n{\n     Grades = new List<GradeEntity>();\n}	0
23483339	23483275	Use of unassigned local variable 'TargetControl'	return Page.Master.FindControl(TargetControlID);	0
28495158	28277369	Receiving Windows Message in class library asynchronously in C#	while(!flag) // flag value will be set true  after processing wnd proc message.\n            {\n                Application.DoEvents();\n            }	0
5126936	4008322	Few GroupJoin in one query	ObjectQuery<DbDataRecord> query = new ObjectQuery<DbDataRecord>\n(\n"SELECT c.Name,c.City, d.Name FROM ContosoEntities.Customer as c " + \n"LEFT JOIN ContosoEntities.Products as d ON d.Name = c.Name " + \n"WHERE c.Country=@ctry", ent\n);\nquery.Parameters.Add(new ObjectParameter("ctry", "Australia"));	0
15159328	15159062	How to get value of a control which is in repeater item from dropdownlist's selecetedchanged event which in the same repeater item?	protected void ddlStatus_Changed(object sender, EventArgs e) \n    {\n        string value;\n        HiddenField comment = ((Control)sender).Parent.FindControl("hdnComment") as HiddenField;\n        if (comment != null) \n        {\n            value = comment.Value;\n        }\n    }	0
12769757	12769027	C#/asp.net geting error when sending data from one page to another	Page.PreviousPage.Form.FindControl("yourContentPlaceHolderID").FindControl("TextBox1");	0
25187792	25186701	How to acces text of textblock inside a dynamic stackpanel in wp8?	((sender as StackPanel).FindName("Name_Text") as TextBlock).Text	0
20066498	20065805	Setting null in list cause null value in other list	[Serializable]\n    public class temp\n    {\n       public int a;\n    }\n    class Program\n    {\n        public static T DeepClone<T>(T a)\n        {\n            using (MemoryStream stream = new MemoryStream())\n            {\n                BinaryFormatter formatter = new BinaryFormatter();\n                formatter.Serialize(stream, a);\n                stream.Position = 0;\n                return (T)formatter.Deserialize(stream);\n            }\n        }\n        static void Main(string[] args)\n        {\n            List<temp> list1 = new List<temp>();\n            list1.Add(new temp { a = 1 });\n            list1.Add(new temp { a = 2 });\n            list1.Add(new temp { a = 3 });\n            List<temp> list2 = DeepClone<List<temp>>(list1);\n            list1[1].a = 4;\n            Console.WriteLine(list2[1].a);\n            Console.ReadKey();\n        }\n    }	0
16736062	16735828	How to update multiple attributes on a collection?	var elements = document.Descendants("element");\n\nforeach (XElement e in elements)\n{\n if (element.Attribute("attribute1") != null)\n        element.Attribute("attribute1").Value = "whateverValue";\n    else\n        element.Add(new XAttribute("attribute1", "whateverValue"));\n}	0
18443898	18443877	Combine an absolute path with a relative path	string abs = "X:/A/B/Q";\nstring rel = "../../B/W";\nvar path = Path.GetFullPath(Path.Combine(abs,rel));	0
9566093	9566015	Concatenate strings to make Picturebox name	for (int i = 0; i < 10; i++) \n{ \n    if (Textbox.Text[i].ToString() == "1")\n    {\n        Control[] c = this.Controls.Find("PBr1_" + i.ToString(), true);\n        if(c != null && c.Length > 0) c[0].Tag = "cb.png";\n    }\n}	0
7077945	7077835	Eval() in ASP. How to pass values on redirect	if (String.IsNullOrEmpty(HttpContext.Current.Request.QueryString["GroupID"]) == false) {\n    String groupId = HttpContext.Current.Request.QueryString["GroupID"];\n}	0
1546610	1546203	How to register a module to ruby?	require 'C:/.../my_awesome_class.dll'\nMyAwesomeClass.do_something	0
9777208	9777085	Replace a part of an element in a list of strings	var groupQuery = l.Select(x => x.Split(new[] { ' ' })).GroupBy(x => x[0]);\nvar sumQuery = groupQuery.Select(x => new { x.Key, Total = x.Select(elem => int.Parse(elem[1])).Sum() });\nforeach (var total in sumQuery)\n{\n    Console.WriteLine("{0}: {1}", total.Key, total.Total);\n}	0
23055816	23007916	One to many mapping in Entity framework with fluent api	this.HasRequired(t => t.class2)\n    .WithRequiredDependent()\n    .Map(m => m.MapKey("IdClass2ColumnName "));	0
15788327	15788223	Cannot bind List View with Data Template	Command="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type Window}}, Path=AddToPlaylistCommand}"	0
4508020	4507931	How determine if a string has been encoded programmatically in C#?	&amp;lt;p&amp;gt;test&amp;lt;/p&amp;gt;	0
23989023	23988845	Discard scale transform of Camera in Viewport3D	var m11 = TransformationMatrix.M11;\nvar m12 = TransformationMatrix.M12;\nvar m13 = TransformationMatrix.M13;\nvar length = Math.Sqrt(m11 * m11 + m12 * m12 + m13 * m13);\nvar factor = 1 / length;\nTransformationMatrix.Scale(new Vector3D(factor, factor, factor));	0
23030549	23030001	Split a line from a CSV to a List<Key, Value>	var lookup = dataRow.Skip(1)\n    .Select((data, index) => new { lookup = index % 2, index = index, data = data})\n    .ToLookup(d => d.lookup);\n\nvar rights = lookup[0].Join(lookup[1],\n        system => system.index + 1,\n        username => username.index,\n        (system, username) => new\n        {\n            system = system.data,\n            useraname = username.data\n        })\n        .Where(d => !string.IsNullOrEmpty(d.system))\n        .ToDictionary(d => d.system, d => d.useraname);	0
16055592	16055519	How to avoid calling virtual function in constructor?	public class Venue\n{\n    private accommodations_ = new HashSet<Accommodation>();\n\n    public Venue()  { }\n\n    public virtual ICollection<Accommodation> Accommodations \n    {\n        get { return accommodations_; }\n        set { accommodations_ = value; }\n    }\n}	0
8301689	8301648	encapsulating method for list of objects	public class ToJson<T>{\n\n  public string MyModelToJson (List<T> TheListOfMyModel) {\n\n  string ListOfMyModelInJson = "";\n\n  JavascriptSerializer TheSerializer = new ....\n  TheSerializer.RegisterConverters(....\n\n  ListOfMyModelInJson = TheSerializer.Serialize(TheListOfMyModel);\n  return ListOfMyModelInJson;\n  }\n}	0
6925539	6925287	Handling release key in custom panel control	const int WM_KEYDOWN = 0x100;\nconst int WM_KEYUP = 0x101;\n\nprotected override bool ProcessKeyPreview(ref Message m)\n{\n    if (m.Msg == WM_KEYDOWN && (Keys)m.WParam == Keys.ControlKey)\n    {\n        //Do something\n    }\n    else if (m.Msg == WM_KEYUP && (Keys)m.WParam == Keys.ControlKey)\n    {\n        //Do something\n    }\n\n    return base.ProcessKeyPreview(ref m);\n}	0
9824727	9824647	C# Replace last letters with another in a String	string network = "11000010101000000000010000000";\nnetwork = network.Substring(0, network.Length - 8) + "11111111";	0
11105644	11105154	Dropdownlist populated from datasource - values are inaccessible from code behind	if (Request["ddl_last"] != null)\n    val = Request["ddl_last"];	0
16250020	16249936	How split mp3 using Naudio?	string nMP3Folder = "FOLDER PATH";\nstring nMP3SourceFilename = "SOURCE MP3 FILENAME";\nstring nMP3OutputFilename = "YOUR OUTPUT MP3 FILENAME";\n\nusing (Mp3FileReader rdr = new Mp3FileReader(nMP3Folder + nMP3SourceFilename))\n{\n    int count = 1;\n    Mp3Frame objmp3Frame = reader.ReadNextFrame();\n    System.IO.FileStream _fs = new System.IO.FileStream(nMP3Folder + nMP3OutputFilename, System.IO.FileMode.Create, System.IO.FileAccess.Write);\n\n    while (objmp3Frame != null)\n    {\n        if (count > 500) //retrieve a sample of 500 frames\n            return;\n\n        _fs.Write(objmp3Frame.RawData, 0, objmp3Frame.RawData.Length);\n        count = count + 1;\n        objmp3Frame = rdr.ReadNextFrame();\n     }\n\n     _fs.Close();\n}	0
13354696	13354661	How to display the tick of the timer in C#	var sw = Stopwatch.StartNew();\n//100 lines of code... \nlabel1.Text = sw.Elapsed.ToString();	0
5687820	5687192	How to get the contact photo of a Google account using Google Contacts Data API by C#	Stream s = cr.Service.Query(contact.PhotoUri);\nImage img = Image.FromStream(s);	0
27744396	27744270	Converting JSON to List	return JsonConvert.DeserializeObject<Models.RootObject>(result);	0
1097217	1097154	Read a string stored in a resource file (resx) with dynamic file name	Dictionary<string, string> resourceMap = new Dictionary<string, string>();\n\npublic static void Func(string fileName)\n{\n    ResXResourceReader rsxr = new ResXResourceReader(fileName);        \n    foreach (DictionaryEntry d in rsxr)\n    {\n        resourceMap.Add(d.Key.ToString(),d.Value.ToString());           \n    }        \n    rsxr.Close();\n}\n\npublic string GetResource(string resourceId)\n{\n    return resourceMap[resourceId];\n}	0
30997082	30996593	How to filter datagridview using datetime picker C#	cmd.CommandText = "Select * from grn1 where date = @YourDate";\ncmd.Parameters.Add("@YourDate", SqlDbType.DateTime).Value = dateTimePicker2.Value;	0
7583905	7583860	Resharper 6 create auto property by default	Auto property	0
11310209	11310164	How do i check if a set time equals the system Time	int hours = System.DateTime.Now.Hour;\nint minutes = System.DateTime.Now.Minute;\n\nif(Convert.Toint32(txtHours.Text) == hours && Convert.Toint32(txtMinutes.Text) == minutes)\n{\n  // same time \n}\nelse\n{\n  // time not same\n}	0
25707245	25707224	C# Updating mysql rows between two dates	commandA.CommandText = "UPDATE trips SET vanid=null WHERE vanid='4' AND tripdate BETWEEN '2014-09-06' AND '2050-12-31'";\ncommandA.ExecuteNonQuery();\nconnectionA.Close();	0
11173648	11173632	Parsing data have blank array field showing	string[] words = \n    parseText.Split(returnChar, StringSplitOptions.RemoveEmptyEntries);	0
22856766	22856363	Wonder action from MessageBox in windowsphone	protected override void OnBackKeyPress(System.ComponentModel.CancelEventArgs e)\n{   e.Cancel=true; \n    string caption = "Stop music and exit?";\n    string message = "If you want to continue listen music while doing other stuff, please use Home key instead of Back key. Do you still want to exit?";\n    if(MessageBox.Show(message, caption, MessageBoxButton.OKCancel)==MessageboxResult.Ok)\n    {\n       //exit;\n    }\n    else\n    {\n      //do what ever you like\n    }\n    base.OnBackKeyPress(e);\n}	0
22337272	22337129	Iterate through properties of a custom enum	var list = typeof(Sex).GetFields(BindingFlags.Static | BindingFlags.Public)\n            .Select(f => (Sex)f.GetValue(null))\n            .ToList();\n\nforeach(var sex in list)\n{\n    Console.WriteLine(sex.ToString() + ":" + sex.GetDescription());\n}	0
9202777	9202467	Generating all the increasing digit numbers	static void Main()\n{\n    WriteNumbers(3);\n}\n\nstatic void WriteNumbers(int digits, int number = 0)\n{\n    int i = (number % 10) + 1;\n    number *= 10;\n    for (; i <= 9; i++)\n    {\n        if (digits == 1)\n            Console.WriteLine(number + i);\n        else\n            WriteNumbers(digits - 1, number + i);\n    }\n}	0
17013642	17012682	PictureBox does not show Grid drawn in a method	public void CreateMyGrid(Graphics g) \n{\n    for (int c = 0; c < columns; c++)\n    {\n\n        for (int r = 0; r < rows; r++)\n        {\n            g.DrawRectangle(pen1, cellSize * c, cellSize * r, cellSize, cellSize);\n            Cell newCell = new Cell(rows * columns, new Vector(c, r));\n            newCell.rectangle = new Rectangle(cellSize * c,\n                cellSize * r,\n                cellSize,\n                cellSize);\n            gridList.Add(newCell);\n        }\n    }\n\n    foreach (Cell cell in gridList)\n    {\n        if (cell.positionCR.X == start.X && cell.positionCR.Y == start.Y)\n        {\n            g.DrawImage(potato, cell.rectangle.X + 1, cell.rectangle.Y + 1);\n        }\n\n        if (cell.positionCR.X == goal.X && cell.positionCR.Y == goal.Y)\n        {\n            g.DrawImage(cake, cell.rectangle.X + 1, cell.rectangle.Y + 1);\n        }\n    }\n\n}\n\nprivate void pictureBox1_Paint(object sender, PaintEventArgs e){\n     CreateMyGrid(e.Graphics);\n}	0
26015684	25801522	How to get the data when I select a datagridview cell or column	try\n         {\n             cn.Open();\n             string query = "select employee_id,Employee_Name,Image_of_Employee from Employee_Details where employee_id='" + dataGridView1.SelectedCells[0].Value.ToString() + "'";\n             SqlCommand cmd = new SqlCommand(query, cn);\n             SqlDataReader sdr;\n             sdr = cmd.ExecuteReader();\n             if (sdr.Read())\n             {\n                 string aa = (string)sdr["employee_id"];\n                 string bb = (string)sdr["employee_name"];\n                 txtEmployeeID.Text = aa.ToString();\n                 txtnameofemployee.Text = bb.ToString();\n\n                 byte[] img=(byte[])sdr["Image_of_employee"];\n                 MemoryStream ms=new MemoryStream(img);\n                 ms.Seek(0,SeekOrigin.Begin);\n                 pictureBox1.Image=Image.FromStream(ms);   cn.Close();\n             }\n\n\n         }\n         catch (Exception e1)\n         {\n             MessageBox.Show(e1.Message);\n         }	0
5834543	5834250	De-serialize JSON using JSON.net on WP7	{\n "Question":"How old am i?",\n "Answers":[\n   "A":"20",\n   "B":"23",\n   "C":"25",\n   "D":"26",\n   "Z":"D"]\n}	0
11083686	11081760	Upload JSON via WebClient	myService.Headers.Add("Content-Type", "application/json");	0
8055956	4670566	parameters not update in sql statement	string query = "select count(*) \n                  from MODEL m \n                  join KOLEKCJA ko on m.SEZON = ko.sezon \n             left join PRODUCENCI p on p.PRODUCENT_ID = m.PRODUCENT_ID \n             left join KRAJ k on k.KOD = m.KRAJ_POCH \n                 where ko.SEZON       like ? \n                   and m.DO_PRODUKCJI like ? \n                   and k.KOD          like ? \n                   and p.PRODUCENT_ID like ? \n                   and m.MODEL_ID     like ?";\n\nOdbcCommand comm = new OdbcCommand();\ncomm.Connection = con;\ncomm.CommandText = query;\ncomm.CommandType = CommandType.Text;\ncomm.Parameters.AddWithValue("ko.SEZON", sezon);\ncomm.Parameters.AddWithValue("m.DO_PRODUKCJI", do_produkcji);\ncomm.Parameters.AddWithValue("KOD", kraj);\ncomm.Parameters.AddWithValue("PRODUCENT_ID", fabryka);\ncomm.Parameters.AddWithValue("MODEL_ID", model);\n\nresult = (int)comm.ExecuteScalar();	0
4354705	4351603	Get selected value from combo box in c# wpf	ComboBoxItem typeItem = (ComboBoxItem)cboType.SelectedItem;\nstring value = typeItem.Content.ToString();	0
15212264	15212209	Calculating with TimeSpan and DateTime	OpeningTime <= DateTime.Now.TimeOfDay <= ClosingTime	0
20682643	20682547	Open Windows Phone ApplicationBar from code-behind	ApplicationBar = new ApplicationBar();\n    ApplicationBar.Mode = ApplicationBarMode.Default;\n    ApplicationBar.Opacity = 1.0; \n    ApplicationBar.IsVisible = true;\n    ApplicationBar.IsMenuEnabled = true;\n\n    ApplicationBarIconButton button1 = new ApplicationBarIconButton();\n    button1.IconUri = new Uri("/Images/YourImage.png", UriKind.Relative);\n    button1.Text = "button 1";\n    ApplicationBar.Buttons.Add(button1);\n\n    ApplicationBarMenuItem menuItem1 = new ApplicationBarMenuItem();\n    menuItem1.Text = "menu item 1";\n    ApplicationBar.MenuItems.Add(menuItem1);	0
7871700	7871675	How to make async pause in C#?	System.Timers.Timer _timer = new  System.Timers.Timer();\n_timer.Elapsed += new ElapsedEventHandler(_timer_Elapsed);\n//30 seconds\n_timer.Interval = 30000;\n_timer.Start();\n\nprivate void _timer_Elapsed(object sender, ElapsedEventArgs e)\n{\n    //do your logic\n}	0
10269572	10269527	Unable to view any received data	RichTextbox1.Text += yourInput;	0
786136	785607	How to bind the Selected Item to a Model with the Infragistics XamDataGrid?	public ListCollectionView ElementsView {get;set;}\n\n// In the constructor:\nthis.ElementsView = new ListCollectionView(Elements);	0
33584618	33583689	Using MEF to Import Types that Inherit from a given Interface	[Export(typeof(ITestExplorer))]\n[Export(typeof(ICoreDataProvider))]\npublic class TestExplorerViewModel : Tool, ITestExplorer, IDataErrorInfo, IDisposable\n{\n    // Implementation.\n}\n\n[Export(typeof(ITicker))]\n[Export(typeof(ICoreDataProvider))]\npublic class TickerViewModel : Tool, ITicker, IDataErrorInfo\n{\n    // Implementation.\n}	0
5750662	5750639	Parse XML file uploaded through asp:FileUpload	XmlDocument myDoc = new XmlDocument();\nmyDoc.Load(fu_MyFile.FileContent);	0
3981406	3981277	Use unmanaged FindFirstVolume to enumerate volumes with .NET in C#	[DllImport( "kernel32.dll", EntryPoint = "FindFirstVolume", SetLastError = true, CallingConvention = CallingConvention.StdCall )]\npublic static extern int FindFirstVolume(\n  StringBuilder lpszVolumeName,\n  int cchBufferLength );\n\n\n[DllImport( "kernel32.dll", EntryPoint = "FindNextVolume", SetLastError = true, CallingConvention = CallingConvention.StdCall )]\npublic static extern bool FindNextVolume(\n  int hFindVolume,\n  StringBuilder lpszVolumeName,\n  int cchBufferLength );	0
8930767	8930711	send pdf statement without saving on application server	mail.Attachments.Add(new Attachment(memoryStream, "example.txt", "text/plain"));	0
12243849	12243820	Regular expression for filenames that doesn't exclude whitespaces	Regex r = new Regex(@"[\w ]+\.\w+$");	0
4122313	4122001	Add Checkbox to Paragraph	PrintDialog pd = new PrintDialog();\npd.ShowDialog();\nFlowDocument doc = new FlowDocument();\nParagraph ph = new Paragraph();\nStackPanel sp = new StackPanel();\nBlockUIContainer buc = new BlockUIContainer(sp);\nph.Inlines.Add(new Bold(new Run("TODO\n")));\n\nforeach (CheckBox cb in box.Items)\n{\n    int value = Convert.ToInt32("0x6F", 16);\n    string stringValue = Char.ConvertFromUtf32(value);\n    CheckBox bt = new CheckBox();\n    bt.IsChecked = false;\n    bt.Content = cb.Content;\n    //ph.Inlines.Add(new Run(bt + " " + cb.Content.ToString()));\n    sp.Children.Add(bt);\n }\n\n        doc.Name = "FlowDoc";\n        doc.Blocks.Add(ph);\n        doc.Blocks.Add(buc);\n IDocumentPaginatorSource idpSource = doc;\n pd.PrintDocument(idpSource.DocumentPaginator, "Hello WPF Printing.");	0
10601423	10601313	How do I calculate similarity of two integers?	public static int Compare(int i1, int i2)\n{\n    int result = 0;\n    while(i1 != 0 && i2 != 0)\n    {\n        var d1 = i1 % 10;\n        var d2 = i2 % 10;\n        i1 /= 10;\n        i2 /= 10;\n        if(d1 == d2)\n        {\n            ++result;\n        }\n        else\n        {\n            result = 0;\n        }\n    }\n    if(i1 != 0 || i2 != 0)\n    {\n        throw new ArgumentException("Integers must be of same length.");\n    }\n    return result;\n}	0
2033108	2033072	Ensure a whitespace exists after any occurance of a specific char in a string	// rule: all 'a's must be followed by space.\n// 'a's that are already followed by space must\n// remain the same.\nString text = "banana is a fruit";\ntext = Regex.Replace(text, @"a(?!\s)", x=>x + " ");\n// at this point, text contains: ba na na is a fruit	0
6716310	6716301	True Parallel Downloads	using System;\nusing System.Linq;\nusing System.Net;\nusing System.Threading.Tasks;\n\nclass Program\n{\n    static void Main()\n    {\n        var urls = new[] \n        { \n            "http://google.com", \n            "http://yahoo.com", \n            "http://stackoverflow.com" \n        };\n\n        var tasks = urls\n            .Select(url => Task.Factory.StartNew(\n                state => \n                {\n                    using (var client = new WebClient())\n                    {\n                        var u = (string)state;\n                        Console.WriteLine("starting to download {0}", u);\n                        string result = client.DownloadString(u);\n                        Console.WriteLine("finished downloading {0}", u);\n                    }\n                }, url)\n            )\n            .ToArray();\n\n        Task.WaitAll(tasks);\n    }\n}	0
21603238	21603101	Display the current variable value while looping	private void button1_Click(object sender, EventArgs e)\n{\n    button1.Enabled = false;\n    string IDs = ID.Text;\n    new System.Threading.Thread(() =>\n    {\n        string[] eachIDs = Regex.Split(IDs, "\n");\n        foreach (var eachID in eachIDs)\n        {\n            getContent(eachID);               \n            titleBox.BeginInvoke((Action) delegate { titleBox.Text = "Done"; });  \n        }\n    }).Start();\n}\n\nprivate void getContent(string value)\n{\n    label1.BeginInvoke((Action) delegate { label1.Text = value; });        \n    Thread.Sleep(5000);\n}	0
11842610	11841770	Find a dropdown control in the last row of a repeater	protected void rpFilter_PreRender(object sender, EventArgs e)\n{\n    Repeater RpFilter = (Repeater)FindControl("RpFilter");\n\n    foreach (RepeaterItem item in RpFilter.Items)\n    {\n        if (RpFilter.Items.Count > 0)\n        {\n            RepeaterItem rptItem = RpFilter.Items[RpFilter.Items.Count - 1];\n\n            DropDownList ddlOperator = (DropDownList)rptItem.FindControl("ddlOperator");\n            ddlOperator.Visible = false;\n        }\n    }	0
17966104	17965962	HTTP response code on button click	if (httpRes.StatusCode == HttpStatusCode.Found || httpRes.StatusCode == HttpStatusCode.Found)	0
14317726	14317583	Passing DTO to my ViewModels constructor to map properties	public static class ProductMappingExtensions\n{\n    public static ProductFormModel ToViewModel(this ProductDto dto)\n    {\n        // Mapping code goes here\n    }\n}\n\n// Usage:\n\nvar viewModel = dto.ToViewModel();	0
4737299	4735437	Convert decimal to byte array	Encoding.ASCII.GetBytes((double.Parse((X / (1024.0 * 1024 * 1024)).ToString("0.00")) * 100).ToString())	0
9101032	9100473	How Get relative path	this.Page.ResolveUrl\nthis.Page.ResolveClientUrl\n\n\nthis.Page.ResolveUrl("~/Uploads/Picture/Commodities/1390/11/TumbDesert.jpg");\nthis.Page.ResolveClientUrl("~/Uploads/Picture/Commodities/1390/11/TumbDesert.jpg");	0
3393645	3393634	Calling Constructor from another Constructor	public class Class1\n{\n   public Class1()\n   {\n\n   }\n   public Class1(int a)\n   {\n\n   }\n}\npublic class Class2 :Class1\n{\n   public Class2(int a) : base(a)\n   {\n\n   }\n   public Class2(): this(2)\n   {\n   }\n\n}	0
8202124	8200021	Getting a proper rotation from a vector direction	Vector2 pixelpos = new Vector2(0, 1);\nfloat rotation = (float)(Math.Atan2(pixelpos.Y, pixelpos.X) / (2 * Math.PI));	0
8910167	8907490	SerialPort not receiving any data	ComPort.Handshake = Handshake.None;	0
16670378	16670056	Numbers formatting in C#	static void Main(string[] args)\n    {\n        double smallNumber = -1.01;\n        double smallNumberMoreDigits = -1.0001;\n        double bigNumber = -100000.001;\n        double longNumber = 2.2347894612789;\n\n        Thread.CurrentThread.CurrentCulture = new CultureInfo("ru", false);            \n\n        Console.Out.WriteLine(smallNumber.ToString("#,0.####"));\n        Console.Out.WriteLine(smallNumberMoreDigits.ToString("#,0.####"));\n        Console.Out.WriteLine(bigNumber.ToString("#,0.####"));\n        Console.Out.WriteLine(longNumber.ToString("#,0.####"));\n\n        Console.Read();\n    }	0
5288360	5288226	Async WebRequest Timeout Windows Phone 7	public static T SafeLimex<T>(Func<T> F, int Timeout, out bool Completed)   \n   {\n       var iar = F.BeginInvoke(null, new object());\n       if (iar.AsyncWaitHandle.WaitOne(Timeout))\n       {\n           Completed = true;\n           return F.EndInvoke(iar);\n       }\n         F.EndInvoke(iar); //not calling EndInvoke will result in a memory leak\n         Completed = false;\n       return default(T);\n   }	0
6613394	6613259	C# predicate that returns whether a boxed value type is the default for that type	class Program\n{\n    static void Main(string[] args)\n    {\n        Console.WriteLine("1 = " + IsDefault(1));\n        Console.WriteLine("0 = " + IsDefault(default(int)));\n\n        Console.WriteLine("1.0 = " + IsDefault(1.0));\n        Console.WriteLine("0.0 = " + IsDefault(default(double)));\n\n        Console.WriteLine("Today = " + IsDefault(DateTime.Today));\n        Console.WriteLine("1.1.1 = " + IsDefault(default(DateTime)));\n\n        //Console.WriteLine(IsDefault(""));\n        //Console.WriteLine(IsDefault(default(string)));\n\n        Console.ReadKey();\n    }\n\n    static bool IsDefault(object boxedValueType)\n    {\n        if (boxedValueType == null) throw new ArgumentNullException("boxedValueType");\n\n        var t = boxedValueType.GetType();\n        if (!t.IsValueType) throw new ArgumentOutOfRangeException("boxedValueType");\n\n        object def = Activator.CreateInstance(t);\n        return boxedValueType.Equals(def);\n    }\n}	0
26513277	26507887	How to upload only the new items to the server without updating/deleting the existing items using Microsoft Sync Framework	((SqlSyncProvider)syncOrchestrator.LocalProvider).ChangesSelected += SelectOnlyNewRows;\n\nvoid SelectOnlyNewRows(object sender, DbChangesSelectedEventArgs e)\n{\n  foreach (DataTable table in e.Context.DataSet.Tables)\n  {\n    for (int i = table.Rows.Count - 1; i >= 0; i--)\n    {\n      DataRow row = table.Rows[i];\n\n      // We are only interested in the new rows.\n      if (row.RowState != DataRowState.Added)\n        table.Rows.Remove(row); // Delete the row so it doesn't get sent.\n    }\n  }\n}	0
15267310	15267197	Tic Tac Toe - Detecting win, lose, or draw	if (winning_line == 0 || winning_line > 1)	0
20767978	20767947	Trying to move picture control on timer	private void textBox1_KeyDown(object sender, System.Windows.Forms.KeyEventArgs e)\n  {\n     // Determine whether the keystroke is a number from the top of the keyboard. \n     if (e.KeyCode == Keys.Down)\n     { \n        direction = "Down";\n     }	0
21045056	21044702	Initialize base class without copy constructor from derived class constructor	public sealed class DerivedTool : IToolWrapper {\n    private Tool _tool;\n\n    public DerivedTool(String filename) : base() {\n        _tool = LoadFromFile(filename) as Tool;\n    }\n\n    public static implicit operator Tool(DerivedTool dt)\n    {\n        return dt._tool;\n    }\n}	0
5249072	5248961	WPF execute a function before a particular event occurs?	base.IsExpanded = value;	0
3063467	3053799	Splash screen moves up before closing	MySplash.Visible = False\nSystem.Windows.Forms.Application.DoEvents	0
7271718	7271666	Get attribute without iteration	WebClientAttribute attrib = (WebClientAttribute)\n    Attribute.GetCustomAttribute(propertyInfo, typeof(WebClientAttribute));	0
2891363	2891346	convert Graphics to Image in c#	Graphics g = Graphics.FromImage(image);	0
28936058	21478830	how to create multiple table in SQLite using properties in windows phone 8	public class Info\n{\n    public string firstName { get; set; }\n    public string lastName { get; set; }\n    public string imageUrl { get; set; }\n    [PrimaryKey, AutoIncrement]\n    public int Id { get; set; }\n    [Ignore]\n    public DetailInfo objDetailInfo{ get; set; }\n}\n\npublic class DetailInfo\n{\n    public string phoneno { get; set; }\n    public string address { get; set; }\n}\n\npublic void createtable()\n{\n   SQLite.SQLiteConnection db= new SQLite.SQLiteConnection(dbPath);\n   db.CreateTable<Info>();\n   db.CreateTable<DetailInfo>();\n}	0
1148539	1147957	with tinyMCE, can you get it to output bbcode tags only?	tinyMCE.init({\n    theme : "advanced",\n    mode : "textareas",\n    plugins : "bbcode",\n    theme_advanced_buttons1 : "bold,italic,undo,redo,link,unlink,image,cleanup",\n    theme_advanced_buttons2 : "",\n    theme_advanced_buttons3 : "",\n    theme_advanced_toolbar_location : "bottom",\n    theme_advanced_toolbar_align : "center",\n    theme_advanced_styles : "Code=codeStyle;Quote=quoteStyle",\n    content_css : "bbcode.css",\n    entity_encoding : "raw",\n    add_unload_trigger : false,\n    remove_linebreaks : false\n});	0
1897484	1897458	Parallel Sort Algorithm	private void QuicksortSequential<T>(T[] arr, int left, int right) \nwhere T : IComparable<T>\n{\n    if (right > left)\n    {\n        int pivot = Partition(arr, left, right);\n        QuicksortSequential(arr, left, pivot - 1);\n        QuicksortSequential(arr, pivot + 1, right);\n    }\n}\n\nprivate void QuicksortParallelOptimised<T>(T[] arr, int left, int right) \nwhere T : IComparable<T>\n{\n    const int SEQUENTIAL_THRESHOLD = 2048;\n    if (right > left)\n    {\n        if (right - left < SEQUENTIAL_THRESHOLD)\n        {\n\n            QuicksortSequential(arr, left, right);\n        }\n        else\n        {\n            int pivot = Partition(arr, left, right);\n            Parallel.Do(\n                () => QuicksortParallelOptimised(arr, left, pivot - 1),\n                () => QuicksortParallelOptimised(arr, pivot + 1, right));\n        }\n    }\n}	0
10912287	10912180	Returning an html file from the controller	public ActionResult downloadFile()\n{\n    var path = "somename.htm";\n\n    StreamReader reader = new StreamReader(path);\n\n    var fileBytes = System.IO.File.ReadAllBytes(path);            \n\n    FileContentResult file = File(fileBytes, "text/html");\n\n    return file;\n}	0
15237562	15214840	Using mutiple context in EF 5 for LINQ instead of one large context	using FFInfo.DAL.Tables;\nusing System.Data.Entity;\n\nnamespace FFInfo.DAL\n{\n    public class SiteNavigation : Base<SiteNavigation>\n    {\n        public DbSet<Navigation> Navigation { get; set; }\n        public DbSet<Section> Sections { get; set; }\n        public DbSet<Locale_Section> SectionTranslations { get; set; }\n    }\n}	0
24407906	24407362	Linq Filter Array of Delimited Strings	var test =\n    FieldsToReplace\n        .Where(x => x.Split(',')\n            .Any(y => y.Equals(prop.Name)))\n        .ToArray();	0
19534008	19395105	WPF PngBitmapEncoder: how to disable background transparency?	public static BitmapSource RenderToBitmap(\n    this UIElement element, double scale, Brush background)\n{\n    var renderWidth = (int)(element.RenderSize.Width * scale);\n    var renderHeight = (int)(element.RenderSize.Height * scale);\n\n    var renderTarget = new RenderTargetBitmap(renderWidth, renderHeight,\n                                              96, 96, PixelFormats.Default);\n    var sourceBrush = new VisualBrush(element);\n\n    var drawingVisual = new DrawingVisual();\n    var drawingContext = drawingVisual.RenderOpen();\n\n    var rect = new Rect(0, 0, element.RenderSize.Width, element.RenderSize.Height);\n\n    using (drawingContext)\n    {\n        drawingContext.PushTransform(new ScaleTransform(scale, scale));\n        drawingContext.DrawRectangle(background, null, rect); // here\n        drawingContext.DrawRectangle(sourceBrush, null, rect);\n    }\n\n    renderTarget.Render(drawingVisual);\n\n    return renderTarget;\n}	0
19308803	19307610	Uploading a .txt file to an FTP server	FtpWebRequest request = (FtpWebRequest)WebRequest.Create("ftp://ftp_address/new_file_name_here");	0
14008154	14008094	How to create an Crystal Report from a XML (XML is from a Web Service) in C#	using System.Xml;\nusing System.Xml.Linq;\n\nvar doc = XDocument.Parse(trx.GetCardTrx("xxxxx", "xxxx", "xxx", "", dateTimePicker1.Text, dateTimePicker2.Text, "", "", "", "", "", "", "", "", "", "", "", "FALSE", "", "", "", "", "", "", "", "", "", "", ""));\n\n  var data = new DataSet();\n  var context = new XmlParserContext(null, new XmlNamespaceManager(new NameTable()), null, XmlSpace.None);\n  var reader = doc\n  data.ReadXml(reader);\n\n  var report = new ReportDocument();\n\n  report.SetDataSource(data);\n  this.crystalReportViewer1.ReportSource.ReportSource = report;	0
26005053	26004676	Passed reference getting a value of subclass	static void Main(string[] args)\n    {\n        subhold h = new subhold();\n        h.aa = 88;\n        Console.WriteLine("In main " + h.aa);\n        thismethod(h);\n        Console.WriteLine("In main2 " + h.aa);\n        Console.WriteLine("In main3 " + h.ss);  //no ERROR\n\n        Console.ReadKey();\n    }	0
25665278	25665077	How to execute only the logic inside the onclick event of asp.net button	public void RaiseCallbackEvent(String eventArgument)\n{\n    // Processes a callback event on the server using the event \n    // argument from the client.\n}	0
3974318	3974253	How to calling a function in a .net dll through an interface loaded through reflection	var assm = Assembly.Load("ClassLibrary1");\n    var type = assm.GetType("ClassLibrary1.Class1");\n    var instance = Activator.CreateInstance(type) as IFace;\n    string[] strings = instance.GetStrings();	0
22766652	22765745	Alternative to std::string in C#	static public string DeMangleCode(string argMangledCode)\n{\n    Encoding enc = Encoding.GetEncoding(1252);\n    byte[] argMangledCodeBytes = enc.GetBytes(argMangledCode);\n    List<byte> unencrypted = new List<byte>();\n    for (int temp = 0; temp < argMangledCodeBytes.Length; temp++)\n    {\n        unencrypted.Add((byte)(argMangledCodeBytes[temp] ^ (434 + temp) % 255));\n    }\n    return enc.GetString(unencrypted.ToArray());\n}	0
21570044	21569920	Data GridView C# hide a column at run time	{\n    grdShowDeatils.DataSource = objShowCampaignStats.GetCapmaignsStatsDetails();\n    grdShowDeatils.Columns[1].Visible = false;\n}	0
25177494	24884809	Get description from iCal occurence	List<DayClass> days = new List<DayClass>();\n\n        IICalendar cal = iCal.iCalendar.LoadFromFile(icsFilePfad).FirstOrDefault();\n        if (cal != null)\n        {\n            foreach (var even in cal.Events)\n                days.Add(new DayClass(even.Start.Date, even.Description));\n        }	0
14609982	14487774	Optimize Populating Nested Accordions	DefaultCategoryRepository.CreateFrom(project.tDefaultCategory)	0
22635228	22634916	How to create a list from returned odata data	List<Course> CourseList = new List<Course>();\n        foreach (var item in container)\n        {\n            Course obj = new Course();\n            obj.Name = item.Name;\n            obj.Description = item.Description;\n            obj.Guid = item.Guid;\n            CourseList.Add(obj);\n        }	0
4222731	4222705	Dictionary Casting	OldDictionary.ToDictionary(x => ((int)x.Key, x => x.Value);	0
3405070	3404647	How do I do set the Authorization header of a GoogleLogin request using the new WCF REST HttpClient API	client.DefaultHeaders.Authorization = new Credential("GoogleLogin auth=" + auth);	0
6993959	6993660	Accessing Excel cells by name instead of "coordinates" like A1	private static void Main(string[] args)\n{\n    string FileName = Path.Combine(Path.GetDirectoryName(System.Windows.Forms.Application.ExecutablePath), "Book2.xlsx");\n\n    Application excelApp = new Application();\n    Workbooks excelWorkbooks = excelApp.Workbooks;\n    Workbook report = excelWorkbooks.Open(FileName, 0, false, 5, "", "", true, XlPlatform.xlWindows, "", true, false, 0, false, false, false);\n\n    var y = report.Names.Item("M_Leitung").RefersToRange.Value;\n\n    Console.WriteLine(y);\n    excelWorkbooks.Close();\n    excelApp.Quit();\n}	0
32913096	32912893	How to send an email on Postal using an email address from the database Asp.Net MVC	order.StaffID = 5;\ndb.Orders.Add(order);\ndb.SaveChanges();\n\n//select hospital from database.\nHospital hospital = db.Hospitals.First(h => h.HospitalId == order.HospitalId);\n\ndynamic email = new Email("Example");\nemail.To = hospital.Email; // this is where you set the email you are sending to. \nemail.Send();	0
643578	643080	Print without Printer selection dialog	myReportDocument.PrintOptions.PrinterName = "PRINTER_NAME";\nmyReportDocument.PrintToPrinter(copies, collate, startPage, endPage);	0
25702822	25702375	Delete selected row from datagrid view and update mysql database in C#	private void button60_Click(object sender, EventArgs e)\n{\n    foreach (DataGridViewCell oneCell in dataGridView1.SelectedCells)\n    {\n        if (oneCell.Selected)\n        {\n            dataGridView1.Rows.RemoveAt(oneCell.RowIndex);\n            int loannumber = dataGridView1.Rows[oneCell.RowIndex].Cells['index of loannumber column in datagridview'].Value; // assuming loannmber is integer\n            string username = dataGridView1.Rows[oneCell.RowIndex].Cells['index of username column in datagridview'].Value; // assuming username is string\n            /* Now create an object of MySqlConnection and MySqlCommand\n             * and the execute following query\n             */\n            string query = string.Format("DELETE FROM table_name WHERE loannumber = {0} AND username = '{1}'", loannumber, username);\n        }\n    }\n\n}	0
9081482	9081407	How To Write To Console From Background Thread's Event Loop?	Console.WriteLine()	0
34188953	34188417	Database application. Adding data to a logged in user only visible to the user logged in	var id = User.Identity.GetUserId();\nvar user = db.Users.Include(u => u.TvShows).Single(u => u.Id == id);	0
1254470	1253657	How to implement sorting functionality in gridview?	private string GetSortDirection(string column)\n{\n\n\n    string sortDirection = "DESC";\n\n\n    string sortExpression = ViewState["SortExpression"] as string;\n\n    if (sortExpression != null)\n    {\n\n        if (sortExpression == column)\n        {\n            string lastDirection = ViewState["SortDirection"] as string;\n            if ((lastDirection != null) && (lastDirection == "DESC"))\n            {\n                sortDirection = "ASC";\n            }\n        }\n    }\n\n\n    ViewState["SortDirection"] = sortDirection;\n    ViewState["SortExpression"] = column;\n\n    return sortDirection;\n}\n\n protected void GridView1_Sorting(object sender, GridViewSortEventArgs e)\n{\n\n    DataTable dtbl = ((DataSet)Session["myDataSet"]).Tables[0];\n    dtbl.DefaultView.Sort = e.SortExpression + " " + GetSortDirection(e.SortExpression);\n    GridView1.DataSource = dtbl;\n    GridView1.DataBind();	0
27486640	27485996	How to use async/await with hub.On in SignalR client	_hub.On<Message>("SendMessageToClient", async i => await OnMessageFromServer(i.Id, i.Message))	0
6771264	6676636	Retrieve Connection point names of a Visio shape in C#	Visio.Shape shape = // get the shape\n\nList<string> listOfNames = new List<string>();\n\n// Loop through all the connection point rows in the shape.\nshort iRow = (short) Visio.VisRowIndices.visRowConnectionPts;\nwhile (shape.get_RowExists(\n    (short) Visio.VisSectionIndices.visSectionConnectionPts, \n    iRow, \n    (short) 0) != 0)\n{\n    // Get a cell from the connection point row.\n    Visio.Cell cell = shape.get_CellsSRC(\n        (short) Visio.VisSectionIndices.visSectionConnectionPts,\n        iRow,\n        (short) Visio.VisCellIndices.visCnnctX);\n\n    // Ask the cell what row it is in.\n    listOfNames.Add(cell.RowName);\n\n    // Next row.\n    ++iRow;\n}	0
7799699	7799666	How to detect the current URL and then forward based on it	if (window.location.href.indexOf('page.aspx') > -1)\n{\n    var value = document.getElementById('<%= myText.ClientID %>').value;\n    window.location.href = 'myotherpage?txtvalue=' + encodeURIComponent(value);\n}	0
19631066	19630968	How do i add a string to the List on the start of the List?	imagesSatelliteUrls.Insert(0, "Group 1");	0
19568126	19553741	select a random link from generated search results in C#	private void DownloadRandomLink(string searchTerm)\n{\n    string fullUrl = "http://www.google.com/#q=" + searchTerm;\n    WebClient wc = new WebClient();\n    wc.DownloadFile(fullUrl, "file.htm");\n    Random rand = new Random();\n    HtmlDocument doc = new HtmlDocument();\n    doc.Load("file.htm");\n    var linksOnPage = from lnks in doc.DocumentNode.Descendants()\n                      where lnks.Name == "a" &&\n                            lnks.Attributes["href"] != null &&\n                            lnks.InnerText.Trim().Length > 0\n                      select new\n                          {\n                              Url = lnks.Attributes["href"].Value,\n                              Text = lnks.InnerText\n                          };\n    if (linksOnPage.Count() > 0)\n    {\n        int randomChoice = rand.Next(0, linksOnPage.Count()-1);\n        var link = linksOnPage.Skip(randomChoice).First();\n        // do something with link...\n    }\n}	0
5721154	5720763	C# traversing class members to look for a specific condition	var type = this.GetType();\nvar fundNoProperties = type.GetProperties()\n    .Where(p => p.Name.StartsWith("FUNDNO"));\nforeach (var info in fundNoProperties)\n{\n    string orderNumber = info.Name.Replace("FUNDNO", "");\n    var fundTypeInfo = type.GetProperty("FUNDTYPE" + orderNumber);\n    if (info.GetValue(this, null).ToString() == "999" &&\n        fundTypeInfo.GetValue(this, null).ToString() == "F")\n    {\n        var currRate = type.GetProperty("CURRATE" + orderNumber);\n        return currRate.Name + currRate.GetValue(this, null).ToString();\n    }\n}	0
17522381	17522209	How to resize multiple images	private void button1_Click(object sender, EventArgs e)\n{\n    DialogResult dr = this.openFileDialogDosyaAc.ShowDialog();\n    if (dr == System.Windows.Forms.DialogResult.OK)\n    {\n        // Read the files\n        foreach (String file in openFileDialogDosyaAc.FileNames) \n        {\n            //resize and save\n        }\n    }\n}	0
14652917	14149239	How to get alternate single words during dictation in SAPI 5.4 using C#?	public void OnSpeechRecognition(int StreamNumber, object StreamPosition, SpeechRecognitionType RecognitionType, ISpeechRecoResult Result)\n{\n    int NUM_OF_ALTERNATES = 5; // Number of alternates sentences to be read\n    string recognizedSentence = Result.PhraseInfo.GetText(0, -1, true);\n\n    // Get alternate sentences\n    int elementCount = Result.PhraseInfo.Elements.Count();\n    for (int i = 0; i < elementCount; ++i)\n    {\n          ISpeechPhraseAlternates phraseAlternates = Result.Alternates(NUM_OF_ALTERNATES, i, 1);\n    }\n}	0
7815646	7815633	What's equivalent to TRUNCATE TABLE in SQL Server?	TRUNCATE TABLE schema.tablename;\nGO	0
23328397	23328336	Combining two separate pieces of code to work together in C#	class Program\n{\n    static void Main(string[] args)\n    {\n        StrokeScribeClass ss = new StrokeScribeClass();\n\n        ss.Alphabet = enumAlphabet.DATAMATRIX;\n        ss.DataMatrixMinSize = 16;\n        ss.ECI = 0;\n        ss.UTF8 = false;\n\n        Console.Write("Input : ");\n        string txt;\n        txt = Console.ReadLine();\n\n        ss.Text = txt;\n        int w = ss.BitmapW;\n        int h = ss.BitmapH;\n        ss.SavePicture(txt + ".bmp", enumFormats.BMP, w * 2, h * 2);\n        System.Console.Write(ss.ErrorDescription);\n\n        WriteTextFile.Second(txt);\n    }\n}\n\n\nclass WriteTextFile\n{\n    static void Second(string fileText)\n    {\n        System.IO.File\n          .WriteAllText(@"C:\Users\Chad\Desktop\studio07\rinhoceros\20140428\WriteText.txt", fileText);\n    }\n}	0
31053785	31052656	Remove header and footer when printing from WebBrowser control	using Microsoft.Win32;\n//...............................\n\npublic  void IESetupFooter()\n{\n\n    string strKey  =  "Software\\Microsoft\\Internet Explorer\\PageSetup";\n    bool bolWritable = true;\n    string strName = "footer";\n        object oValue = "Test Footer";\n    RegistryKey oKey  = Registry.CurrentUser.OpenSubKey(strKey,bolWritable);\n    Console.Write (strKey);\n    oKey.SetValue(strName,oValue);\n    oKey.Close();\n}	0
10179697	10179615	Sort a GenericList<T> by date property	var list = list.OrderBy(x => x.PaymentDate).ToList();	0
6888067	6887985	Deleting of files from isolated storage isn't working.	storage.FileExists("FlashCardApp\\" + item.FileName);	0
22442215	22442116	Interpreting a new line in string	string puretext = textBox1.Text.Replace(Environment.NewLine, ""); //Ignore newline(s)\nfor (int i = 0; i < puretext.Length; i++)\n{\n    if (stringTocolor.ContainsKey(puretext[i]))\n    {\n         array[i] = stringTocolor[puretext[i]];\n    }\n    //give alert if wrong key\n    else\n    {\n         MessageBox.Show("Wrong Colour input at index " + i + " of textbox string!");\n    }\n}	0
6729184	6729047	How do I install multiple setups in a single installation?	Custom actions	0
23081759	23081561	unable to convert this query in lambda expression	int linkto=Convert.ToInt32(Session["login_user_Id"]);\nvar list=de.User_Details.Where(y => y.Leader_User_Id==linkto).Select(y => y.User_Id);\nlvTimesheet.DataSource = de.TimeSheetDetailViews.Where(x => x.Link_To == linkto || list.Contains(x.Link_To)).ToList();	0
3616194	3616139	Is it possible to add child nodes to the added custom nodes	TreeNode nodeA = nodeACH.Nodes.Add("A");\n\nTreeNode nodeB = node1.Nodes.Add("A");\n\nTreeNode nodeC = node1.Nodes.Add("B");	0
2967640	2967596	Searching with Linq	var closestRecord = _records.MinBy(rec => Math.Abs(rec.Frame - frameNumber));	0
7055802	7055722	Paint a method from another class	e.Graphics	0
7744419	7744302	find string using c#?	string input = "http://example.com/TIGS/SIM/Lists/Team Discussion/DispForm.aspx?ID=1779";\n        string given = "http://example.com/TIGS/SIM/Lists";\n        System.Text.RegularExpressions.Regex regex = new System.Text.RegularExpressions.Regex(given + @"\/(.+)\/");\n        System.Text.RegularExpressions.Match match = regex.Match(input);\n        Console.WriteLine(match.Groups[1]); // Team Discussion	0
24445803	24430408	DevExpress GroupRow - get information about DataRows belonging to that GroupRow	List<object> GetGroupNames(int groupRowVisibleIndex){\n  List<object> result = new List<string>();\n  int childCount = ASPxGridView1.GetChildRowCount(groupRowIndex);\n\n  for(int i = 0; i < childCount; i ++)  \n    result.Add(ASPxGridView1.GetChildRowValues(groupRowVisibleIndex, i, "CarName"));\n}	0
25021575	24915887	ASP.NET Chart: How to plot series points using for loop	// BIND DATA TO CHART\n        for (int i = 0; i < 43; i++)\n        {\n            //TIME STUFF FOR SQL\n            int startBin = 14400;\n            int endBin = 15300;\n            TimeSpan stime = TimeSpan.FromSeconds(startBin + (i * 900));\n            TimeSpan etime = TimeSpan.FromSeconds(endBin + (i * 900));\n            string xAxisStart = string.Format("{0:D2}:{1:D2}:{2:D2}", stime.Hours, stime.Minutes, stime.Seconds);\n            string xAxisStop = string.Format("{0:D2}:{1:D2}:{2:D2}", etime.Hours, etime.Minutes, etime.Seconds);\n\n            //TARGET SERIES \n            RepairedChart.Series["REPAIRED"].Points.AddXY(xAxisStart, getRepaired2(xAxisStart, xAxisStop));\n            RepairedChart.Series["TARGET"].Points.AddXY(xAxisStart, getScheduleRepairTarget(xAxisStart, xAxisStop));\n        }	0
24789099	24788654	Converting a curl command to a .NET http request	var client = new HttpClient();\n\nclient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);\n\nclient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));\n\nvar anonString = new { name = "test name" };\nvar json = JsonConvert.SerializeObject(anonString);\n\nawait client.PutAsync("URL", new StringContent(json)).ConfigureAwait(false);	0
26911245	26863525	Latency issues with self-hosting a simple NancyFX HelloWorld application running under Mono	# /etc/nginx/virtual.d/nancydemo.conf\n\nserver {\n  listen 80;\n  server_name nancydemo.local;\n  root /media/sf_dev/nancydemo/bin/Debug;\n\n  location / {\n    proxy_pass http://127.0.0.1:1234;\n  }\n}	0
6491634	6491578	How to know if a folder of file is being used by another process?	public static bool IsFileInUse(string fileFullPath, bool throwIfNotExists)\n{\n    if (System.IO.File.Exists(fileFullPath))\n    {\n        try\n        {\n            //if this does not throw exception then the file is not use by another program\n            using (FileStream fileStream = File.OpenWrite(fileFullPath))\n            {\n                if (fileStream == null)\n                    return true;\n            }\n            return false;\n        }\n        catch\n        {\n            return true;\n        }\n    }\n    else if (!throwIfNotExists)\n    {\n        return true;\n    }\n    else\n    {\n        throw new FileNotFoundException("Specified path is not exsists", fileFullPath);\n    }\n}	0
4086480	4030013	Socket Programming - Sending/Receiving hex and strings	s.write("\x02\x00".bytes)\ns.write("\x05\x00\x00\x00".bytes)	0
11466058	11465928	How to insert foreign key value in Child table in c#	SqlCommand scmd = new SqlCommand("insert into Customer (custname,contact)values(@custname,@contact); SELECT SCOPE_IDENTITY()", conn);\n        scmd.Parameters.AddWithValue("@custname", cusname.Text);\n        scmd.Parameters.AddWithValue("@contact", contact.Text);\n        int custId = Convert.ToInt32(scmd.ExecuteScalar());\n\n        SqlCommand scmd1 = new SqlCommand("insert into  _order (item,qauntity,cust_Id) VALUES(@item,@qauntity,@custId)", conn);\n        scmd1.Parameters.AddWithValue("@item", item.Text);\n        scmd1.Parameters.AddWithValue("@qauntity", qauntity.Text);\n        scmd1.Parameters.AddWithValue("@custId", custId);\n        scmd1.ExecuteNonQuery();	0
4622919	3588294	Way to get AutoComplete working in a DataGridViewComboBoxColumn?	void grdPerformanceScenario_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)\n    {\n        if (e.Control is ComboBox)\n        {\n            (e.Control as ComboBox).AutoCompleteMode = AutoCompleteMode.Suggest;\n            (e.Control as ComboBox).AutoCompleteSource = AutoCompleteSource.ListItems;\n        }\n    }	0
14903482	14903395	parse a string to look for a phrase in C#	var re = new System.Text.RegularExpressions.Regex(@"NDC\:\s(\d{11})");\nvar phrase = "Rx: RX15046522B Brand: LEVOTHYROXINE SODIUM Generic: LEVOTHYROXINE SODIUM NDC: 00378180001 Barcode: 0378180001 Strength: 25 mcg Form: Tablet Color: orange Marking: Shape: oblong";\nif (re.IsMatch(phrase))\n{\n    var match = re.Match(phrase);\n    // entire NDC string\n    context.Response.Write(match.Value);\n    // just the number\n    context.Response.Write(match.Groups[1].Value);\n}	0
1403542	1403524	C# - Trimming string from first null terminator and onwards	string TrimFromZero(string input)\n{\n  int index= input.IndexOf('\0');\n  if(index < 0)\n    return input;\n\n  return input.Substring(0,index);\n}	0
23392347	23391455	PerformanceCounter reporting higher CPU usage than what's observed	new PerformanceCounter("Processor", ...);	0
8068294	8068133	Importance of the key size in the Rfc2898DeriveBytes (PBKDF2) implementation	aes.Key = deriveBytes.GetBytes (16); // 16 * 8 = 128 bits	0
23693136	23693106	Use a MessageBox to get a user input?	string input = \n    Microsoft.VisualBasic.Interaction.InputBox("My Prompt", \n                                               "The Title", \n                                               "Desired Default", \n                                               -1, -1);\nint listSize;\nbool success = int.TryParse(input, out listSize);	0
31559819	31559451	how to use the displayed text from combobox when it's filled by a query	combobox.Text;	0
28025132	28024794	Concatenation of a Complicated String Causing Issues	public string oldCode;\n    public int counter = 0;\n    string[] AffUrl = new string[100];\n    string[] ImgUrl = new string[100];\n    private void button1_Click(object sender, EventArgs e)\n    {\n\n        AffUrl[counter] = textBox1.Text;\n        ImgUrl[counter] = textBox2.Text;\n\n        string code = @"<div style=""float:left;padding-right:30px;padding-bottom:30px;"">\n<div>\n  <img src=""" + ImgUrl[counter] + @""" height=""200px"" width=""200px"" />\n</div>\n<div>\n  <button onclick=""myFunction()"">Try it</button>\n  <script type=""text/javascript"">\n    function myFunction" + counter + @"() {\n      var btn = document.createElement(""BUTTON"");\n      window.open(""" + AffUrl[counter] + @""", ""_self"")\n    }\n  </script>\n</div>\n </div>";\n        if (counter == 0)\n        {\n            oldCode = code;\n        }\n        oldCode = string.Concat(code, oldCode);\n        counter++;\n\n        richTextBox1.Text = oldCode;\n    }\n}	0
19827041	19572054	Mono Gtk Window require focus for input	windowObj.FocusOutEvent += (obj, args) => windowObj.Present();	0
12210616	12210424	Reflection get object property to sort a list	PropertyInfo pi1 = typeof(x).GetProperty(sortColumn);\nPropertyInfo pi2 = typeof(y).GetProperty(sortColumn);\n\n//With sortColumn = "Login";\nif (sortDir == "ASC")\n{\n    filteredList.Sort((x, y) => string.Compare(pi1.GetValue(x, null), pi2.GetValue(y, null), true));\n}\nelse\n{\n    filteredList.Sort((x, y) => string.Compare(pi2.GetValue(y, null), pi1.GetValue(x, null), true));\n}	0
20632946	20632826	Multiple values against same condition	private static readonly string[] AllKeys = new[] {"Low", "High", "Mean", "StdDev"};\n\n\nif (currentElement == null || ALlKeys.Any(k => gridRow[k].ToString() == string.Empty)) {\n     ...\n}\nif (newRow.Length != 0) {\n    foreach (var key in AllKeys) {\n        AddColorList(currentElement, opid, currentLow, key, newRow, listCollectionLow);\n    }\n}	0
5332931	5332919	How to return linq query into single object	Enumerable.Single()	0
962453	962449	Array of Labels	Label[] labels = new Label[10];\nlabels[0] = new Label();\nlabels[0].Text = "blablabla";\nlabels[0].Location = new System.Drawing.Point(100, 100);\n...\nlabels[9] = new Label();\n...	0
31566890	31566483	How to reroute click event to a double click?	var newMouseEvent = new MouseButtonEventArgs(Mouse.PrimaryDevice, 0, MouseButton.Left) \n{ \n    RoutedEvent = Control.MouseDoubleClickEvent\n};\nmyTextBox.RaiseEvent(newMouseEvent);	0
18341034	18340804	how to determine maxReceivedMessageSize for a list of up to 2000 items of a given class	bool selected - 1 byte\nstring account - 100 bytes\nstring email - 100 bytes\nstring PDFfileName - 100 bytes\nstring PDFpassword - 100 bytes\nDateTime reportDate - 8 bytes\nint sendStatus - 4 bytes\nstring sendStatusDesc - 100 bytes\nDateTime sendStatusDate - 8 bytes\nstring parameters - 100 bytes\nstring extensions - 100 bytes\nTotal - 721 bytes	0
25070223	25070212	Selecting the whole data after joining in linq	var Query = from x in Table_1\n            join y in Table_2\n            on x.id equals y.id\n            where x.Country.Equals("X Country")\n            select new {x,y};	0
10089071	10087905	Is app.config file a secure place to store passwords?	class SecureStringManager\n{\n    readonly Encoding _encoding = Encoding.Unicode;\n\n    public string Unprotect(string encryptedString)\n    {\n        byte[] protectedData = Convert.FromBase64String(encryptedString);\n        byte[] unprotectedData = ProtectedData.Unprotect(protectedData,\n            null, DataProtectionScope.CurrentUser);\n\n        return _encoding.GetString(unprotectedData);\n    }\n\n    public string Protect(string unprotectedString)\n    {\n        byte[] unprotectedData = _encoding.GetBytes(unprotectedString);\n        byte[] protectedData = ProtectedData.Protect(unprotectedData, \n            null, DataProtectionScope.CurrentUser);\n\n        return Convert.ToBase64String(protectedData);\n    }\n}	0
1972834	1972830	C# Custom Serialization - Using TypeConverter	[Serializable]	0
3104925	3104883	Trouble passing a parameter to a class in C#	dataGridView1.Rows.Clear();\n        try\n        {\n            foreach (string fileNames in fileDrive)\n            {\n\n                if (regEx.IsMatch(fileNames))\n                {\n                    string fileNameOnly = Path.GetFileName(fileNames);\n                    string pathOnly = Path.GetDirectoryName(fileNames);\n\n                    DataGridViewRow dgr = new DataGridViewRow();\n                    filePath.Add(fileNames);\n                    dgr.CreateCells(dataGridView1);\n                    dgr.Cells[0].Value = pathOnly;\n                    dgr.Cells[1].Value = fileNameOnly;\n                    dataGridView1.Rows.Add(dgr);\n\n                    new SanitizeFileNames().FileCleanup(fileNames);\n                }\n\n                else\n                {\n                    continue;\n                }\n\n            }\n        }	0
32406464	32406282	Send Email async method	public Task void SendEmailAsyn() { \n    return Task.Factory.StartNew(() => { SendEmail(); });\n}	0
21565092	21565053	Finding the length of the longest continuous series of positive numbers in an array	int counter = 0;\n    int longestCounter = 0;\n    for (int i = 0; i < array.Length; i++)\n    {\n        if (array[i] > 0) counter++;\n        else\n        {\n            if ( counter > longestCounter ) longestCounter = counter;\n            counter = 0; \n        }\n    }\n    if ( counter > longestCounter ) longestCounter = counter;	0
12792844	12792683	Removing from ListBox inside of a Timer	public void timerElapsed(object sender, ElapsedEventArgs e)\n{\n    this.Invoke(new Action(() => listBoxItems.Remove(itemToBeRemoved)));\n}	0
17173446	17173360	SQLDataAdapter adding a where clause	using (SqlDataAdapter a = new SqlDataAdapter("SELECT * FROM TEST_TABLE WHERE ID = @filter", conn))\n{\n    int filter = ID;\n    a.SelectCommand.Parameters.AddWithValue("@filter", filter);	0
749867	749841	Running a windows service in a console	private static ManualResetEvent m_daemonUp = new ManualResetEvent(false);\n\n[STAThread]\nstatic void Main(string[] args)\n{\n    bool isConsole = false;\n\n    if (args != null && args.Length == 1 && args[0].StartsWith("-c")) {\n        isConsole = true;\n        Console.WriteLine("Daemon starting");\n\n        MyDaemon daemon = new MyDaemon();\n\n        Thread daemonThread = new Thread(new ThreadStart(daemon.Start));\n        daemonThread.Start();\n        m_daemonUp.WaitOne();\n    }\n    else {\n        System.ServiceProcess.ServiceBase[] ServicesToRun;\n        ServicesToRun = new System.ServiceProcess.ServiceBase[] { new Service() };\n        System.ServiceProcess.ServiceBase.Run(ServicesToRun);\n    }\n}	0
12394339	12394285	How to clean HTML from any special tag via Regex in C#?	HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();\ndoc.LoadHtml(html);\n\nforeach (var font in doc.DocumentNode.Descendants("font").ToArray())\n{\n    font.Remove();\n}	0
1016187	1016141	Creative ways to converting a Collection of objects to a javascript array in c#	using System;\nusing System.Linq;\nusing System.Collections.Generic;\n\nusing Newtonsoft.Json;\n\nclass Users\n{\n    public string Name {get; set;}\n    public int UserID {get; set;}\n    public Users(string Name, int UserID)\n    {\n        this.Name = Name;\n        this.UserID = UserID;\n    }\n}\n\n    List<Users> users = new List<Users>();\n    users.Add(new Users("John", 1));\n    users.Add(new Users("Mary", 2));\n    ...     \n\n    string json = JsonConvert.SerializeObject(from user in users select user.UserID);\n}	0
2995554	2995516	LINQ: how to transform list by performing calculations on every element	List<MyObject> objects = new List<MyObject>();\n\n// Populate list.\n\nobjects.ForEach(obj => {\n  obj.v1 += obj.dv1;\n  obj.v2 += obj.dv2;\n});	0
19436940	19436372	For Each File in Folder, Include XML	public static XDocument AggregateMultipleXmlFilesIntoASingleOne(string parentFolderPath, string fileNamePrefix)\n{\n    return new XDocument(\n        new XElement("OpenTag", \n            Directory.GetFiles(parentFolderPath)\n                .Where(file => Path.GetFileName(file).StartsWith(fileNamePrefix))\n                .Select(XDocument.Load)\n                .Select(doc => new XElement(doc.Root))\n                .ToArray()));\n}	0
21092237	21092138	Add space per 4 characters with RegEx	string test = "BE45898287271283";\ntest = Regex.Replace(test, ".{4}", "$0 ").Trim();	0
2363346	2362535	Property grid item and DoubleClick	public override StandardValuesCollection GetStandardValues(ITypeDescriptorContext context)\n{\n    StandardValuesCollection ret;\n    Type tpProperty = context.PropertyDescriptor.PropertyType;\n\n    if (tpProperty == typeof(bool))\n        ret = new StandardValuesCollection(new object[] { true, false });\n    else if (tpProperty == typeof(bool?))\n        ret = new StandardValuesCollection(new object[] { true, false, null });\n    else\n        ret = new StandardValuesCollection(new object[0]);\n\n    return ret;\n}	0
3556140	3555879	Wait as long for 100 miliseconds for data returned from method else throw exeception	public static T EvaluateAsync<T> (this Func<T> func, Timespan timeout)\n{\n  var result = func.BeginInvoke(null, null);\n\n  if (!result.AsyncWaitHandle.WaitOne(timeout))\n       throw new TimeoutException ("Operation did not complete on time.");\n\n  return func.EndInvoke(result);\n}\n\nstatic void Example()\n{\n   var myMethod = new Func<int>(ExampleLongRunningMethod);\n\n  // should return\n  int result = myMethod.EvaluateAsync(TimeSpan.FromSeconds(2));\n\n  // should throw\n  int result2 = myMethod.EvaluateAsync(TimeSpan.FromMilliseconds(100));\n}\n\nstatic int ExampleLongRunningMethod()\n{\n  Thread.Sleep(1000);\n  return 42;\n}	0
28886794	28882343	Xamarin Forms Windows Phone MasterDetailPage - Remove default ApplicationBar icon	protected override void OnElementPropertyChanged(object sender, PropertyChangedEventArgs e)\n{\n    var app = (MainPage)((PhoneApplicationFrame)Application.Current.RootVisual).Content;\n    var applicationBar = app.ApplicationBar;\n    applicationBar.Buttons.Clear();\n    base.OnElementPropertyChanged(sender, e);\n}	0
1686761	1686712	Catch DllNotFoundException from P/Invoke	[DllImport("kernel32.dll", SetLastError=true)]\npublic static extern IntPtr LoadLibrary(string lpFileName);\n\n[DllImport("kernel32.dll", SetLastError=true)]\nstatic extern bool FreeLibrary(IntPtr hModule);\n\n[DllImport("kernel32.dll", CharSet=CharSet.Ansi, ExactSpelling=true, SetLastError=true)]\npublic static extern IntPtr GetProcAddress(IntPtr hModule, string procName);	0
17120978	17120948	Alternative to Regex: How to use IsLetter or IsDigit methods and specify number of letters and numbers required	public static bool IsValid(string source)\n{\n    //this will not affect the original as strings are immutable\n    source = source.Trim(); \n    if (source.Length != 12) return false;\n    return source.Take(4).All(char.IsLetter)\n         && source.Skip(4).All(char.IsDigit);\n}	0
15104758	15104010	ServiceStack Deserializing	JsConfig.IncludePublicFields = true;	0
20232672	20141647	Accessing virtual directory(mapped drive) via c#/asp.net webpage with IIS7	net use L: \\ServerB\sharedfolder /persistent:yes	0
2973254	2973232	Dumping to Console works like a charm, but not to a file, C#	r = new FileInfo(Path.Combine(destpath,f.Name));\n    r.Create();	0
22978760	22978748	how to get current Mainpage instance in wp8	var currentPage = ((PhoneApplicationFrame)Application.Current.RootVisual).Content;	0
10293643	10293602	c# WebApplication save as in directory	string path = HttpContext.Current.ApplicationInstance.Server.MapPath("~/user_uploads");\nstring fn = System.IO.Path.GetFileName(FileUpload1.PostedFile.FileName);   \nFileUpload1.PostedFile.SaveAs(System.IO.Path.Combine(path, fn));           \n//FileUpload1.PostedFile.SaveAs(path  + fn);	0
1692765	1566054	Is it possible to provide a resize indication (resizer-grip) on a form without adding a status bar?	form.SizeGripStyle = System.Windows.Forms.SizeGripStyle.Show	0
14855924	14855274	Compare strings with a wildcard	private static bool CompareStrings(string str1, string str2)\n    {\n        var ar1 = Regex.Matches(str1, @"[\d%]+").Cast<Match>().Select(m => m.Value).ToArray();\n        var ar2 = Regex.Matches(str2, @"[\d%]+").Cast<Match>().Select(m => m.Value).ToArray();\n\n        if (ar1.Length != ar2.Length)\n            return false;\n\n        // Check wildcards and numbers\n        for (int i = 0; i < ar1.Length; i++)\n            if (ar1[i] != ar2[i] && ar1[i] != "%" && ar2[i] != "%")\n                return false;\n\n        // Remove wildcards and numbers to check the other characters\n        if (Regex.Replace(str1, @"[\d%]+", String.Empty) != Regex.Replace(str2, @"[\d%]+", String.Empty))\n            return false;\n\n       return true;\n    }	0
13974230	13974210	Using gmail address to send out emails with Postal	enableSsl="true"	0
20507858	20507703	C# How to get the name of the property being set	public class MyObject : DatabaseObject\n{\n    public string FieldX\n    {\n        get { return GetValue(() => FieldX); }\n        set { SetValue(() => FieldX, value); }\n    }\n\n    public int FieldY\n    {\n        get { return GetValue(() => FieldY); }\n        set { SetValue(() => FieldY, value); }\n    }\n}\n\npublic class DatabaseObject\n{\n    public T GetValue<T>(Expression<Func<T>> field)\n    {\n         string fieldName = GetFieldName(field);\n         // Code that actually gets the right value\n    }\n\n    public void SetValue<T>(Expression<Func<T>> field, T value)\n    {\n         string fieldName = GetFieldName(field);\n         // Code that actually sets the value in the right place\n    }\n\n    private static string GetFieldName<T>(Expression<Func<T>> field)\n    {\n        return ((MemberExpression)field.Body).Member.Name;\n    }\n}	0
20266004	20240827	How to select last value from each run of similar items?	/// <summary>\n/// Given a list, return the last value from each run of similar items.\n/// </summary>\npublic static IEnumerable<T> WithoutDuplicates<T>(this IEnumerable<T> source, Func<T, T, bool> similar)\n{\n    Contract.Requires(source != null);\n    Contract.Requires(similar != null);\n    Contract.Ensures(Contract.Result<IEnumerable<T>>().Count() <= source.Count(), "Result should be at most as long as original list");\n\n    T last = default(T);\n    bool first = true;\n    foreach (var item in source)\n    {\n        if (!first && !similar(item, last))\n            yield return last;\n\n        last = item;\n        first = false;\n    }\n\n    if (!first)\n        yield return last;\n}	0
3441865	3441786	C# Foreach XML node	var list = (from download in xDoc.Descendats("slot")\n            select new Download\n                    {\n                        Filename = (string) download.Element("filename"),\n                        Size = (string) download.Element("size"),\n                        Status = (string) download.Element("status")\n                    }).ToList();	0
4574046	4573984	listview, checkbox, c#	var list = listView1.CheckedIndices.Cast<int>().ToList();	0
16941678	16941464	How to create a calendar event. Ics with pre filled recipient email?	Response.Write("ATTENDEE;CN=\"Toto Tutu\";RSVP=TRUE:mailto:toto.tutu@test.com");	0
19505332	19505193	Accessing a RichTextBox inside a TabControl	// The first control would be your richtextbox if that's the only control in\n// the tabpage.\nvar richTextBox = (RichtTextBox)tabControl1.TabPages[index].Controls[0];	0
12124033	12122678	Configure Group Policy	Group Policy	0
24283115	24282968	How to determine which parameter set caused the test to fail?	Assert.AreEqual(expected, actual, \n  string.Format("Poof on parameters:{0}, {1}",in1,in2));	0
17058220	17058022	How to loop this object without IEnumerable	for (int x = 0; x < results.Count; x++ ) //typecast x a get error to loop the results\n{\n  TableRow tr = new TableRow();\n  Table1.Rows.Add(tr);\n\n  GetErrors value = results[x];\n\n  TableCell tc = new TableCell();\n  tc.Text = results[x].FWWDIR_ROW + results[x].FWWDIR_ERR_INVOICE + results[x].FWWDIR_ERR_ACCOUNT;\n  tr.Cells.Add(tc);// = new TableCell();\n}	0
32079415	32057031	Sql server deadlock with insert, select, delete	var tran = connection.BeginTransaction(IsolationLevel.Serializable);\nvar userIds = connection.Query<string>("select UserId from UserInLounge with (updlock) where LoungeId = @loungeId", new { loungeId }, tran).ToList();	0
460746	460733	How to pass Page as ref parameter to a function	Page tmp = Page;\nSetupUserPermission.SetupUserRights(ref tmp, Convert.ToInt32(UserId));\nPage = tmp;	0
772062	772041	Using c++ library in c#	[DllImport("yourdll.dll")]\npublic static extern int ExportToCall(int argument);	0
19480467	19480417	Regex C# - match any YouTube.com URI	var youtubeHosts=new string[]{"youtube","youtube-nocookie","youtu.be"};\nUri uri=new Uri(path);\nbool isValid=youtubeHosts.Any(x=>uri.Host==x);	0
6815904	6672127	Getting user e-mail with facebook C# sdk	var client = new FacebookClient();\ndynamic me = client.Get("me");\nstring firstName = me.first_name;\nstring lastName = me.last_name;\nstring email = me.email;	0
16646968	16646785	How to kill multiple processes	DataSet ds = new DataSet();// SQL STUFF\nSqlConnection con = new SqlConnection(ConnectionString);\nSqlDataAdapter da = new SqlDataAdapter("SELECT ProcessName FROM ApplicationProcesses", con);\n// since you start from SqlDataAdapter I'm continue from there..           \nda.Fill(ds, "ProcessNames");\n// get the process in the database to a array\nstring[] preocesArray = ds.Tables["ProcessNames"]\n        .AsEnumerable()\n        .Select(row => row.Field<string>("ProcessName"))\n        .ToArray();\n\n// kill the process if it is in the list \nvar runningProceses = System.Diagnostics.Process.GetProcesses();\nfor (int i = 0; i < runningProceses.Length; i++)\n{\n    if (preocesArray.Contains(runningProceses[i].ProcessName))\n    {\n        runningProceses[i].Kill(); //KILLS THE PROCESSES\n    }\n}	0
3429058	3429043	How could I group duplicates from a collection?	var grps = from r in resultList\n        group r by r.Guid into g\n        select new { guid = g.Key, Names = String.Join(" and ", g) };\nforeach(var g in grps)\n  Console.WriteLine("GUID {0} has the names {1}", g.guid, g.Names);	0
3247181	3148844	Many-To-Many Relationship in Code-First EF4	modelBuilder.Entity<Post>().HasMany(p => p.Tags).WithMany();	0
31666079	31666048	DateTime Subtract Minutes in C#	var dif_minutes = dt1.Subtract(dt2).Minutes; // dif_minutes = 2	0
21924222	21924137	Loop for creating different threads spawns multiple of the same one	// int minRange, maxRange; - declare inside loop instead!!\nfor (int i = 0; i < numThreads; i++)\n{\n    var i2 = i;\n    int minRange = worldlength / numThreads * i;\n    int maxRange = worldlength / numThreads * (i + 1);\n    tasks[i] = (Task.Factory.StartNew(() => \n            Threads.advance(minRange, maxRange, i2.ToString())));\n}	0
33157255	33157225	How to check if an integer includes a certain number in c#	int number = 17;\nint digit = 7;\nbool result = number.ToString().Contains(digit.ToString());	0
29355243	29354923	Count each columns in linq with left join c#	var query = \n    from t in table1\n    let t2 = table2.Where (t2=> t2.column1 == t2.column2)\n    group new{t, t2} by 0 into g\n    select new{\n        column1 = g.Count()\n        column2 = g.SelectMany(e => e.t2).Count()\n    }	0
28260468	28257221	Cyrillic in HelpProvider	ToolTip toolTip1 = new ToolTip();\ntoolTip1.Show("??????? ?????", this.gaParametersText)	0
33598529	33531854	Unable to select multiple rows on infragistics ultrawingrid with a check box column	private void grdPayVis_AfterSelectChange(object sender, AfterSelectChangeEventArgs e)\n{\n    if (e.Type == typeof(UltraGridRow))\n    {\n        foreach (UltraGridRow row in this.grdPayVis.Selected.Rows)\n        {\n            row.Cells["Select"].Value = true; // Or some value appropriate to your scenario\n        }\n\n        this.grdPayVis.UpdateData();\n    }	0
24821911	24821797	get new entered DataGridView cell value using c#	private void gridViewTimes_CellLeave(object sender, DataGridViewCellEventArgs e)\n{\n    if(dataGridView1.Rows[e.RowIndex].Cells[0].Value != null)\n    {\n        string value = dataGridView1.Rows[e.RowIndex].Cells[0].Value.ToString();\n    }\n}	0
26169240	26169083	Sorting ListBox With Multiple Fields By Date	var dates = listBox2.Items.Cast<object>().Select( item => \n     (from z in task.tblContractProcessRequests\n      where z.RequestID == Int32.Parse(item.ToString()) && z.RequestTypeID == 1\n      select z).Single() ).OrderByDescending(d => d.RequestTime);\n\n\n foreach (var date in dates) \n {\n    listBox3.Items.Add( date.RequestID + " - " + date.RequestTime);\n }	0
19946682	19931288	How to get access to an active Page in Silverlight 4?	MainPage page = Application.Current.RootVisual as MainPage;\nLoadedPage myPage = page.frame.Content as LoadedPage;	0
27482373	27482302	Refer .NET assembly based on compiler switch	Assembly.LoadFrom	0
5228574	5228530	Get count of object from list?	var groups = collection.GroupBy(x => x.Id);\nforeach(var group in groups) {\n    Console.WriteLine("Count for Id {0}: {1}", group.Key, group.Count());\n}	0
5659960	5647551	How to format numbers or text in Silverlight DataGrid columns?	void gridView_AutoGeneratingColumn(object sender, DataGridAutoGeneratingColumnEventArgs e)\n{\n    if (e.PropertyType == typeof(DateTime))\n    {\n         DataGridBoundColumn obj = e.Column as DataGridBoundColumn;\n         if (obj != null && obj.Binding != null)\n              obj.Binding.StringFormat = "{0:d}";\n    }\n}	0
16301220	16287184	Pull SecurityToken from SAML Assertion	SecurityToken token;\nusing (StringReader sr = new StringReader(assertion))\n{\n    using (XmlReader reader = XmlReader.Create(sr))\n    {\n        if (!reader.ReadToFollowing("saml:Assertion"))\n        {\n            throw new Exception("Assertion not found!");\n        }\n        SecurityTokenHandlerCollection collection = SecurityTokenHandlerCollection.CreateDefaultSecurityTokenHandlerCollection();\n        token = collection.ReadToken(reader.ReadSubtree());\n    }\n}	0
3780699	3780669	WPF: How do I set the content of a Paragraph in Code?	var paragraph = new Paragraph();\nparagraph.Inlines.Add(new Run(yourString));\nflowDocument.Blocks.Add(paragraph);	0
7195046	7194371	Showing error message from Pl/sql proc to the client	try\n    {\n      cmd.CommandText = "DELETE FROM myable";\n      cmd.ExecuteNonQuery();\n    }\n    catch (OracleException ex)\n    {\n       //Put your ORA-20001 logic here, or call a common method as shown\n       HandleOracleException(ex);\n    }	0
6097743	6097442	Fetch data from RSS and bind to a asp control	internal class RssItem\n    {\n        public DateTime Date;\n        public string Title;\n        public string Description;\n        public string Link;\n    }\n\nXmlDocument xmlDoc = new XmlDocument();\nprivate Collection<RssItem> feedItems = new Collection<RssItem>();\nxmlDoc.Load("URL of the RSS Feeds");\nParseRssItems(xmlDoc);\n\nprivate void ParseRssItems(XmlDocument xmlDoc)\n        {\n            this.feedItems.Clear();\n            foreach (XmlNode node in xmlDoc.SelectNodes("rss/channel/item"))\n            {\n                RssItem item = new RssItem();\n                this.ParseDocElements(node, "title", ref item.Title);\n                this.ParseDocElements(node, "description", ref item.Description);\n                this.ParseDocElements(node, "link", ref item.Link);\n                string date = null;\n                this.ParseDocElements(node, "pubDate", ref date);\n                DateTime.TryParse(date, out item.Date);\n                this.feedItems.Add(item);\n            }\n        }	0
15538672	15538478	C# Windows Form Application - Send email using gmail smtp	try\n{\n    MailMessage message = new MailMessage();\n    SmtpClient smtp = new SmtpClient();\n\n    message.From = new MailAddress("from@gmail.com");\n    message.To.Add(new MailAddress("to@gmail.com"));\n    message.Subject = "Test";\n    message.Body = "Content";\n\n    smtp.Port = 587;\n    smtp.Host = "smtp.gmail.com";\n    smtp.EnableSsl = true;\n    smtp.UseDefaultCredentials = false;\n    smtp.Credentials = new NetworkCredential("from@gmail.com", "pwd");\n    smtp.DeliveryMethod = SmtpDeliveryMethod.Network;\n    smtp.Send(message);\n}\ncatch (Exception ex)\n{\n    MessageBox.Show("err: " + ex.Message);\n}	0
23686692	23685938	Checking a column value when updating a gridview asp.net	GridViewRow row = GridView1.Rows[e.RowIndex];\nstring price = ((TextBox)(row.Cells[3].Controls[0])).Text;	0
12932911	12932910	How can I tell if my application has been bundled with Mono instead of executed with Mono?	IsBundled = (typeof(int).Assembly.Location == "mscorlib.dll");	0
11596205	11593577	Regex - Order Multiline SQL String	var sql = @"CREATE TABLE [dbo].[Table1] (\n            [Id] [int] NOT NULL,\n            [Title] [nvarchar](255) NULL\n        )\n\n        ALTER TABLE [dbo].[Table1] ADD\n            CONSTRAINT [PK_Table1] PRIMARY KEY CLUSTERED ([Id])\n\n        INSERT INTO [dbo].[Table1] ([Id], [Title]) VALUES ('Home', NULL)\n\n        CREATE TABLE [dbo].[Table2] (\n            [Id] [int] NOT NULL,\n            [Title] [nvarchar](255) NULL\n        )\n        ";\nvar statementOrder = new[] { "CREATE", "ALTER", "INSERT" };\nvar statements = from statement in Regex.Split(sql, "\n\r")\n              let trimStatement = statement.Trim()\n              let statementType = trimStatement.Substring(0, trimStatement.IndexOf(' '))\n              orderby Array.IndexOf(statementOrder, statementType)\n              select trimStatement;\nvar newSql = String.Join("\n\r", statements.ToArray());	0
20794180	20794093	Is any one part of a GUID more unique than the rest?	400465a7-6533-4cd0-bfec-6e74ac75a830\ndb849123-e4a2-4883-b489-2e5b8f7f0b73\n644aec02-cc95-4fcf-a792-4e57b2509f69\n78a9f2db-0328-4dc4-9c08-41cc51e342ca\nad04a2dd-1661-4c6f-8ac0-7593e1255402\n3ee1362c-d55e-451b-8617-353389802ba8\n95816697-ce79-4425-a3aa-fe4d3d6824a7\na0b52b4f-165f-4284-96d9-a46b32e53e6d\n23ee49d5-c689-4807-ab1b-f837de3b3914\n5987747d-7910-405c-987a-e7d45a2cb1de	0
5292770	5292660	Problem with string as reference parameter when method takes Object C#	public static void Swap<T>(ref T a, ref T b) \n{\n    T t = b;     \n    b = a;     \n    a = t; \n}	0
13614461	13613740	Obtain a collection of generic types from PagedCollectionView	public interface ISelectable\n{\n   pubilc bool IsSelected { get; }\n}\n\npublic class ItemType<T> : ISelectable\n{\n   ...\n}\n\nvar objects = Source.SourceCollection\n   .OfType<ISelectable>()\n   .Where(t => t.IsSelected);	0
21443926	21443866	Try catch when opening a text file for read	StreamReader readProfile;\ntry\n{\n    readProfile = new System.IO.StreamReader(ProDirectory.ToString() + @"\" + myProFile.ToString());\n}\ncatch (Exception ex)\n{\n    datalogger.Fatal(DateTime.Now.ToString() +  ":  Error while attempting to read file - " + ProDirectory.ToString() + @"\" + myProFile.ToString() + " The error is - "  + ex.ToString());\n    // whatever you want to do with readProfile here. Of course, if the issue was that it couldn't create it, it still won't have been created...\n}	0
24807801	24807766	Regular Expression to get aggregates of a formula	(?:SUM|AVG|COUNT|MAX|MIN)(?:\([^)(]*\))	0
20023664	20022890	Adding an event handler for MapPolygon in Bing Map for Windows Store	private void initMap()\n    {\n        myMap.Credentials = "---";\n        myMap.ZoomLevel = 9.5;\n        myMap.Center = new Bing.Maps.Location(35.1,33.3);\n        myMap.ShowNavigationBar = false;\n        myMap.MapType = Bing.Maps.MapType.Aerial;\n\n        Pushpin pushpin = new Pushpin();\n        MapLayer.SetPosition(pushpin, new Location(35.34028, 33.31917));\n        myMap.Children.Add(pushpin);\n        pushpin.Tapped += pushpin_Tapped;\n    }\n\n    void pushpin_Tapped(object sender, TappedRoutedEventArgs e)\n    {\n        Pushpin tmp = (Pushpin)sender;\n        tmp.Text = "ABC";\n    }	0
3739746	3739739	How to select the first three elements of a IEnumerable object?	var items = new List<int>(){ 1, 2, 3, 4, 5 };\nvar results = items.Take(3);	0
9847529	9845019	BitmapImage: Accessing closed StreamSource	public static byte[] BufferFromImage(BitmapImage img)\n    {\n        byte[] result = null;\n\n        if (img != null)\n        {\n            using(MemoryStream memStream = new MemoryStream())\n            {\n                JpegBitmapEncoder encoder = new JpegBitmapEncoder();\n                encoder.Frames.Add(BitmapFrame.Create(img));\n                encoder.Save(memStream);\n\n                result = memStream.ToArray();\n            }\n\n        }\n\n        return result;\n    }	0
13730954	13730693	single global variable asp.net	/Users/Edit.aspx?userID=123\n/Users/Edit.aspx?userID=789	0
15669828	15669782	select max between two columns in linq	(from pro in Products.ToList()\nlet max = Max(pro.DateSend, pro.DateEdit)\nselect max).Max()\n\n\nstatic DateTime? Max(DateTime? a, DateTime? b)\n{\n    if (!a.HasValue && !b.HasValue) return a;  // doesn't matter\n\n    if (!a.HasValue) return b;  \n    if (!b.HasValue) return a;\n\n    return a.Value > b.Value ? a : b;\n}	0
30532698	30510052	How to read a PowerPoint document and store its slides into Slide objects?	Sub Example()\n\nDim oPres As Presentation\nDim oSl As Slide\nDim sFileName As String\nDim aSlides() As Slide\n\nsFileName = "c:\somefolder\mypres.pptx"\n\n' Open the presentation\nSet oPres = Presentations.Open(sFileName)\n\n' Prepare an array to hold slide objects\nReDim aSlides(1 To oPres.Slides.Count)\n\n' Add each slide in the presentation to the array\nFor Each oSl In oPres.Slides\n    Set aSlides(oSl.SlideIndex) = oSl\nNext\n\n' Now you have an array of slides\n' Do what you will with it\n\nEnd Sub	0
27013691	26866856	Open file in intranet from another server - ASP.Net C#	protected void Page_Load(object sender, EventArgs e)\n{\n    if (Request.QueryString.AllKeys.Contains("path"))\n    {\n        string path = Server.UrlDecode(Request.QueryString["path"]);\n        if (!(new FileInfo(path).Exists))\n            return;\n\n        using (FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read))\n            {\n                SetStream(fs);\n            }\n    }\n}\n\nprivate void SetStream(Stream stream)\n{\n    byte[] bytes = new byte[(int)stream.Length];\n    stream.Read(bytes, 0, (int)stream.Length);\n    Response.Buffer = true;\n    Response.Clear();\n    Response.AddHeader("content-disposition", "attachment; filename=" + Server.UrlDecode(Request.QueryString["name"]));\n    Response.BinaryWrite(bytes);\n    Response.Flush();\n}	0
22634227	22633565	Can I have a where clause that works on a grandchild in a LINQ query?	var data = (from ex in context.exams\n           join t in context.tests on ex.Id equals test.ExamID\n           join ut in context.userTests on t.Id equals ut.TestId\n           where ut.UserId = 123\n           select new {ex, ut}).ToList();	0
2616153	2616024	Is there any way for getting the direction of writing in specific culture?	bool isRightToLeft = new CultureInfo("fa-IR").TextInfo.IsRightToLeft;	0
1970580	1970514	Populate a TreeView with a string directory	private void button1_Click(object sender, EventArgs e)\n{\n    FolderBrowserDialog dialog = new FolderBrowserDialog();\n    if (dialog.ShowDialog() != DialogResult.OK) { return; }\n\n    this.treeView1.Nodes.Add(TraverseDirectory(dialog.SelectedPath));\n\n}\n\n\nprivate TreeNode TraverseDirectory(string path)\n{\n    TreeNode result = new TreeNode(path);\n    foreach (var subdirectory in Directory.GetDirectories(path))\n    {\n        result.Nodes.Add(TraverseDirectory(subdirectory));\n    }\n\n    return result;\n}	0
1549339	1302771	Can I use StructureMap to return all implementations of a generic interface for a specific type parameter	ObjectFactory.Initialize(x =>\n{\n    x.Scan(scan =>\n    {\n        scan.TheCallingAssembly();\n        scan.WithDefaultConventions();\n        scan.AddAllTypesOf<IValidator<Person>>();\n        scan.AddAllTypesOf<IValidator<Address>>();\n    });\n});\n\nvar PersonValidators = ObjectFactory.GetAllInstances<IValidator<Person>>();	0
25858421	25858365	XML CultureInfo loading data incorrectly	this.damage = float.Parse(reader.Value, CultureInfo.InvariantCulture);	0
18147504	5780888	Casting interfaces for deserialization in JSON.NET	public class Visit : IVisit\n{\n    /// <summary>\n    /// This constructor is required for the JSON deserializer to be able\n    /// to identify concrete classes to use when deserializing the interface properties.\n    /// </summary>\n    public Visit(MyLocation location, Guest guest)\n    {\n        Location = location;\n        Guest = guest;\n    }\n    public long VisitId { get; set; }\n    public ILocation Location { get;  set; }\n    public DateTime VisitDate { get; set; }\n    public IGuest Guest { get; set; }\n}	0
21287992	21287876	Regex to extract Address from js code	\(new\sGLatLng\(          #Start of the match\n(?<Lat>\-?\d{1,3}.\d+)    #Latitude\n,\n(?<Long>\-?\d{1,3}.\d+)\) #Longitude   \n,\n'(?<Address>.+)'          #The address\n(?=,icon_near\))          #Positive LookAhead. The regex end just before ',icon_near)	0
3924292	3924268	find if an integer exists in a list of integers	bool isInList = intList.IndexOf(intVariable) != -1;	0
13095099	13094875	Generate random text files at a specific speed in C#	var start = DateTime.Now;\nint bytesSaved=0;\ndouble desiredSpeed = (25*1024*1024)/60;\n\nwhile(true)\n{\n  int latency = bytesSaved/(DateTime.Now-start).TotalSeconds - desiredSpeed;\n  if(latency>0) \n    {          \n      Thread.Sleep(100);\n      continue;\n    }\n\n  bytesSaved +=SaveDataChunk(latency);     \n\n}	0
24376975	24376907	How can I do this replacement in C# with Regex Library?	String input  = "13.0  3.53  2.29  31.67";\nString result = Regex.Replace(input, @"^(\d+)[\d.]*", "$1:00");\n//=> "13:00  3.53  2.29  31.67"	0
31228897	31191516	Getting Facebook albums details in C#	dynamic result = fb.Get("me/albums?fields=name");\nforeach(dynamic album in result.data){....}	0
5918799	5918796	Can I iterate through an array in C# using something like a foreach	string[] arr = {"a", "aa", "aaa"};\n\nforeach(string item in arr)\n{\n    Console.WriteLine("array element: " + item);\n}	0
12432897	12431607	How to extract last word in richtextbox in c#	int i = 0;\n    private void richTextBox1_KeyUp(object sender, KeyEventArgs e)\n     {\n    if (e.KeyCode == Keys.Space)            {\n        string str = new string(arr); \n        MessageBox.Show(str);\n        Array.Clear(arr, 0, arr.Length);\n        i = 0;\n    }\n    else if (e.KeyCode == Keys.Back)\n       {\n        i--;\n        if (i < 0)\n        {\n            i = 0;\n        }\n        arr[i] = ' ';\n\n\n    }\n\n    else\n    {\n        arr[i] = (char)e.KeyValue;\n\n        i++;\n    }\n    }*	0
25710818	25710756	How to express array type in c# object	public class RootObject\n{\n    public List<int> xy { get; set; }\n    public List<List<string>> cell { get; set; }\n}	0
15371055	15297460	How to add user input from textbox into an array or arraylist	public partial class Test : System.Web.UI.Page\n{\n    [Serializable]\n    class Recipient\n    {\n        public string name { get; set; }\n    }\n\n    protected void Page_Load(object sender, EventArgs e)\n    {\n\n    }\n\n    protected void btnEnter_Click(object sender, EventArgs e)\n    {\n        Recipient recipients = new Recipient();\n\n        List<string> recipient = (List<string>)ViewState["recipientList"];\n\n\n        if (recipient == null)\n        {\n            recipient = new List<string>();\n        }\n        recipients.name = txtFName.Text.Trim();\n        recipient.Add(recipients.name);\n        ViewState["recipientList"] = recipient;\n\n        if (recipient.Count == 1)\n        {\n            lblFName.Text = recipient[0];\n        }\n\n        if (recipient.Count == 2)\n        {\n            lblFName1.Text = recipient[1];\n        }\n\n    }	0
11242178	11242092	Copy subsection of a multidimensional array	// This is a jagged array. It has 3 rows, each of which is an int[] in its own right.\n// Each row can also have a different number of elements from all the others, so if\n// a[i][N] is valid for some i and N, a[x][N] is not necessarily valid for other x != i\nvar a = new int[3][];\n\n// To populate the array you need to explicitly create an instance for each sub-array\nfor (int i = 0; i < 3; i++)\n{\n      a[i] = new[] { i, i + 3 };\n}\n\n// And now this is possible:\nvar b = a[2];	0
17043575	17043379	Is there any way to prevent my application from running on Windows 7 machines?	if (Environment.OSVersion.ToString().Contains("Microsoft Windows NT 6.1"))\n{\n    //code to execute if running win 7\n}	0
8090813	8090790	C# dealing with objects	var students = new Student[]\n        {\n            new Student(82495, "Carlton", "Blanchard"),\n            new Student(20935, "Charlotte", "O'Keefe"),\n            new Student(79274, "Christine", "Burns"),\n            new Student(79204, "Edward", "Swanson"),\n            new Student(92804, "Charles", "Pressmann")\n        };\n\n        IEnumerable<Student> pupils = from studs\n                                      in students  \n                                      where stds.id = youridvaruabble/value\n                                      select studs;	0
8053290	8052488	detailsview with multiple dropdownlists	protected void ddlClienti_SelectedIndexChanged(object sender, EventArgs e) \n{ \n    edsContatti.WhereParameters[0].DefaultValue = ((DropDownList)sender).SelectedValue;\n    // Call DataBind to reload the DataSource based on the new WHERE clause\n    edsContatti.DataBind();\n    // Since you're using a DetailsView, you have to find the nested control within it\n    DropDownList ddlContatti = (DropDownList)DetailsView1.FindControl("ddlConcatti");\n    // And then call DataBind on it as well\n    detailsView1.DataBind();\n}	0
20714507	20714464	Problems with Regex in C#	^\s*\#include\s	0
26301571	26300621	How to override a type already registered in LightInject using a new instance passed to the constructor?	using LightInject;\n\nclass Program\n{\n    static void Main(string[] args)\n    {\n        var container = new ServiceContainer();\n        container.Register<Bar>();\n        container.Register<Foo>();\n        container.Register<Bar, Foo>((factory, bar) => new Foo(bar), "FooWithRuntimeArgument");            \n        var instance = container.GetInstance<Foo>();            \n        var instanceWithRuntimeArgument = container.GetInstance<Bar, Foo>(new Bar(), "FooWithRuntimeArgument");\n    }\n}\n\npublic class Foo\n{                \n    public Foo(Bar bar) {}        \n}\n\npublic class Bar {}	0
10751689	10734996	How to remove partucular list of querystring from current page url querystring in c#2.0	string excludeList = "cid,intcid,del";\n\nstring getFinalString = Regex.Replace(Regex.Replace(Regex.Replace(Request.Url.Query, @"^\?", "&"), "&(" + excludeList.Replace(",", "|") + ")=[^&]*", "", RegexOptions.IgnoreCase), "^&", "?");	0
22331191	22331104	Downloading JSON through WebClient	MessageBox.Show( a.Error.ToString() );	0
3932680	3932190	Need help with making label of repeater visible and link button hidden in code behind	rptAdd.FindControl("labelBull").Visible = true;	0
20520237	20520118	Add root, before merging two XML-Files	XDocument doc1 = XDocument.Load("N:\File.xml");\nXDocument doc2 = XDocument.Load("N:\File2.xml");\nXDocument merged = new XDocument(new XElement("root", doc1.Root, doc2.Root));\nmerged.Save("N:\Merged.xml");	0
26738484	26735926	Reduce size of image after Scan?	using (ImageFactory imageFactory = new ImageFactory(preserveExifData:true))\n{\n    imageFactory.Load(inStream)\n                .Quality(80)\n                .Save(outStream);\n}	0
12494672	12494451	Validate Xml with Xsd and update Xml	var schemaSet = new XmlSchemaSet();  \nschemaSet.Add(null, "schema1.xsd");  \n// add further schemas as needed  \nschemaSet.Compile();  \n\nvar xmlSampleGenerator= new XmlSampleGenerator(schemaSet, new XmlQualifiedName("Test"));  \n\nvar doc = new XmlDocument();  \nusing (XmlWriter writer = doc.CreateNavigator().AppendChild())  \n{  \n   xmlSampleGenerator.WriteXml(writer);  \n}	0
4546577	4546566	Assembly needs to be redeployed into GAC every time its user app is changed	public static void Main(string[] args)\n    {\n        if ((((args == null) || (args.Length != 1)) || (args[0] == "-?")) || (args[0] == "-h"))\n        {\n            Usage();\n        }\n        else\n        {\n            try\n            {\n                Console.WriteLine(Assembly.LoadFrom(args[0]).FullName.ToString());\n            }\n            catch (Exception exception)\n            {\n                Console.WriteLine("Exception: {0}", exception.ToString());\n                Usage();\n            }\n        }\n    }	0
5422178	5394644	Spell checking library for Windows Mobile 6.x	public static class InputContext\n    {\n        private enum SHIC_FEATURE : uint\n        {\n            RESTOREDEFAULT = 0,\n            AUTOCORRECT = 1,\n            AUTOSUGGEST = 2,\n            HAVETRAILER = 3,\n            CLASS = 4\n        }\n\n        [DllImport("aygshell.dll")]\n        private static extern int SHSetInputContext(IntPtr hwnd, SHIC_FEATURE dwFeature, ref bool lpValue);\n\n        public static void SetAutoSuggestion(IntPtr handle, bool enable)\n        {\n            SHSetInputContext(handle, SHIC_FEATURE.AUTOSUGGEST, ref enable);\n            SHSetInputContext(handle, SHIC_FEATURE.AUTOCORRECT, ref enable);\n        }\n    }	0
23911083	23910658	C# winforms webbrowser control, scroll with up and down keys	private void webBrowser1_PreviewKeyDown(object sender, PreviewKeyDownEventArgs e)\n{\n    if (e.KeyCode == Keys.Down || e.KeyCode == Keys.Up || e.KeyCode == Keys.Left || e.KeyCode == Keys.Right)\n    {\n        e.IsInputKey = true;\n        return;\n    }\n\n}	0
23380052	23366757	Read response header using RestSharp API in C#	response.Headers.ElementAt(i).Name.ToString();    \nresponse.Headers.ElementAt(i).Value.ToString();	0
8835610	8835568	Listbox manual DrawItem big font size	private void listBox1_MeasureItem(object sender, MeasureItemEventArgs e)\n{\n     e.ItemHeight = listBox1.Font.Height;\n}	0
9957728	9957615	How two ItemSources can be bound to a ListBox item?	from englishText in xml1\nfrom finnishText in xml2\nselect new DictLanguage() { EnglishText = englishText, FinnishText = finnishText };	0
9297945	9271147	Find DataGrid Column and Row Index based on cell value of column	dg.CurrentCell = new DataGridCellInfo(dg.Items[0],dg.Columns[0]);	0
16848333	16847840	Using JSON.NET to add a boolean property	string pref = "path_of_the_preferences_file";\nstring _pref = string.empty;\nusing (StreamReader reader = new StreamReader(pref, Encoding.UTF8))\n{\n    _pref = reader.ReadToEnd();\n}\n\n// REFORMAT JSON.DATA\nJObject json = JObject.Parse(_pref);\nvar extension1 = json["extensions"]["settings"]["extension1"];\n\nvar a = extension1.Children();\nJProperty cond_it = null;\n\nforeach (var b in a)\n{\n    if (b.ToString().ToLower().Contains("cond_it"))\n    {\n        cond_it = (JProperty)b;\n\n        break;\n    }\n}\n\nif (cond_it != null)\n{\n    var b = cond_it.Value.SelectToken("location").Parent;\n    b.AddAfterSelf(new JProperty("blacklist", true));\n}	0
27794298	27786030	Pre Selecting checkboxs in RadListView in Telerik	radListView1.Items[0].CheckState = ToggleState.On;	0
7690739	7689751	How to format the Timestamp data when using TraceOptions.Timestamp	TraceOptions.DateTime	0
14978595	14978198	Viewstate Problems loading dynamic Controls (with ListBox)	protected override object SaveViewState()\n{\n    var a = this.ControlsList;\n    var b = base.SaveViewState();\n    if (a.Count == 0 && b == null)\n        return null;\n\n    return new System.Web.UI.Pair(a, b);\n}\n\nprotected override void LoadViewState(object savedState)\n{\n    if (savedState == null)\n        return;\n\n    var pair = (System.Web.UI.Pair)savedState;\n    if (pair.First != null)\n    {\n        foreach (var id in (IList<string>)pair.First)\n        {\n            // add the control\n        }\n    }\n\n    if (pair.Second != null)\n        base.LoadViewState(pair.Second);\n}	0
32440971	3625304	Don't overwrite file uploaded through FileUpload control	var fileName = file.FileName;\nvar extension = Path.GetExtension(fileName);\nvar nameWithoutExtension = Path.GetFileNameWithoutExtension(fileName);\n\nvar i = 1;\nwhile (File.Exists(uploadFolder + fileName))\n{\n    fileName = nameWithoutExtension.Trim() + " (" + i + ")" + extension;\n    i++;\n}\n\nfile.SaveAs(uploadFolder + fileName);	0
22685218	22684526	Custom control dynamic size C#	public override Font Font\n{\n    get\n    {\n        return base.Font;\n    }\n    set\n    {\n        textBox1.Font = base.Font = value;\n        if (Font.Height != this.Height)\n        {\n            this.Height = Font.Height;\n            textBox1.Size = new Size(this.Width - (_textboxMargin * 2 + _borderWidth * 2), this.Height - (_textboxMargin * 2 + _borderWidth * 2));\n            textBox1.Location = new Point(_textboxMargin, _textboxMargin);\n        }\n    }\n}\n\nprotected override void OnResize(EventArgs e)\n{\n    if (this.Height < Font.Height)\n        this.Height = Font.Height;\n\n    base.OnResize(e);\n}	0
6500348	6500272	How to define a variable that can be used everywhere?	Properties.Settings.Default.(Whatever variable you want to access)	0
15508289	15508262	string.format if else statement	String.Format("{0}", x == null ? "<null>": (x == 0 ? "True" : "False"))	0
14850014	14847618	Retrieve the offset of <span> tag in web browser control C#	void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)\n    {\n        List<HtmlElement> spanelement = new List<HtmlElement>();\n        foreach (HtmlElement span in webBrowser1.Document.GetElementsByTagName("span"))\n        {\n            spanelement.Add(span);\n            //Or Add Offset\n            //spanelement.Add(span.OffsetRectangle.Top;);\n        }\n    }	0
10081544	10081523	How to access an column with special characters using DataTable.Select()?	var rows = dt.Select("","[# of Students] desc");	0
16278927	16278654	Make a page on website accessible after logging in	readonly SqlConnection sqlCon = new SqlConnection(ConfigurationManager.ConnectionStrings["VerbaLinksConString"].ToString());\n\n try\n {\n    SqlCommand cmd  = new SqlCommand("Select txt_Password from table where txt_user_name = '"+txtUserName.Text+"' and txt_Pwd = '"+txtPassword.Text+"'",sqlCon);\n   sqlCon.Open();\n   SqlDataReader dr = cmd.ExecuteReader();\n   If(dr.Read())\n   {\n     Response.Redirect("HomePage.aspx");\n   }\n   else\n   {\n     Response.Write("Either userId or Password is wrong");\n   }\n   SqlCon.Close(); \n}\nCatch(SqlException ex)\n {\n\n }	0
10783379	10782415	mapping DB data to List of lists	List<A> aList = dataTable.AsEnumerable()\n    .GroupBy(row => row.Field<int>("A_Id"))\n    .Select(grp => new A {\n        Id = grp.Key,\n        Name = grp.First().Field<DateTime>("A_Date"),\n        Bs = grp.Select(m => new B { Id = m.Field<int>("B_Id"), Name = m.Field<string>("B_Name") }).ToList(),\n    })\n    .ToList()	0
31857214	31857026	DateTime.TryParseExact fails	DateTime? Result = null;\nDateTime test = DateTime.Now.Date;\nif (DateTime.TryParseExact(value, "dd/MM/yyyy", System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.None, out test))\n    Result = test;	0
16413747	16413722	how to safely trigger an event	var handler = ActionDataReceived;\nif (handler != null)\n{\n    handler(this, new ActionEventArgs(logMessage));\n}	0
750222	750204	Accessing similar named properties in a loop	for(int eventIndex = 0; eventIndex < NUM_EVENTS; eventIndex++)\n    {\n        PropertyInfo eventPropertyInfo = \n            this.GetType().GetProperty("Event" + eventIndex);\n\n        if (eventPropertyInfo.GetValue(this, null) == yourValue)\n        {\n             //Do Something here\n        }\n    }	0
32377124	32370527	Arranging minimised child windows on MDI	[DllImport("user32.dll")]\n    private static extern bool SetWindowPos(IntPtr hWnd, IntPtr hWndInsertAfter, int X, int Y, int cx, int cy, uint uFlags);\n\n    public FormA() {\n        Button btn = new Button { Text = "asdf" };\n        Controls.Add(btn);\n        IsMdiContainer = true;\n        var f1 = new Form { Text = "Form1", TopLevel = false, MdiParent = this};\n        var f2 = new Form { Text = "Form2", TopLevel = false, MdiParent = this};\n        var f3 = new Form { Text = "Form3", TopLevel = false, MdiParent = this};\n        f1.Show();\n        f2.Show();\n        f3.Show();\n        btn.Click += delegate {\n            //this.LayoutMdi(MdiLayout.ArrangeIcons);\n            //f1.Bounds = new Rectangle(50, 50, 100, 30);\n             int top = 100;\n             SetWindowPos(f1.Handle, IntPtr.Zero, f1.Left, top, f1.Width, f1.Height, 0);\n        };\n   }	0
11659381	11658786	Replace Ninject with Simple Injector	container.Register<ITypeMapFactory, TypeMapFactory>();\ncontainer.RegisterAll<IObjectMapper>(MapperRegistry.AllMappers());\ncontainer.RegisterSingle<ConfigurationStore>();\ncontainer.Register<IConfiguration>(() => \n    container.GetInstance<ConfigurationStore>());\ncontainer.Register<IConfigurationProvider>(() => \n    container.GetInstance<ConfigurationStore>());\ncontainer.Register<IMappingEngine, MappingEngine>();	0
2682240	2682216	C# DateTime, is this method regional setting safe?	string LastsuccessfuldownloadDateTime = DateTime.UtcNow.AddDays(-91).ToString(\n    DateFormatString, CultureInfo.InvariantCulture);	0
21776174	21775932	Auto-Implemented Property Classes as Parameter	public void ThisMethod<T>(T mySet) where T : MySetBaseClass\n{\n    ...\n}	0
9734717	1192171	How can I change the table adapter's command timeout	using System;\nusing System.Data.SqlClient;\nusing System.Reflection;\n\nnamespace CSP\n{\n    public class TableAdapterBase : System.ComponentModel.Component\n    {\n        public TableAdapterBase()\n        {\n            SetCommandTimeout(GetConnection().ConnectionTimeout);\n        }\n\n        public void SetCommandTimeout(int Timeout)\n        {\n            foreach (var c in SelectCommand())\n                c.CommandTimeout = Timeout;\n        }\n\n        private System.Data.SqlClient.SqlConnection GetConnection()\n        {\n            return GetProperty("Connection") as System.Data.SqlClient.SqlConnection;\n        }\n\n        private SqlCommand[] SelectCommand()\n        {\n            return GetProperty("CommandCollection") as SqlCommand[];\n        }\n\n        private Object GetProperty(String s)\n        {\n            return this.GetType().GetProperty(s, BindingFlags.NonPublic | BindingFlags.GetProperty | BindingFlags.Instance).GetValue(this, null);\n        }\n    }\n}	0
1756103	1756080	foreach loop with textbox names	Size newSize = new Size(27, 20);\nforeach (Control c in this.Controls)\n{\n   if (c is TextBox && c.Name.EndsWith("txt2"))\n   {\n      c.Size = newSize;\n   }\n}	0
6806126	6806100	Calling PeerGroupCreateInvitation from C#	[DllImport("p2p.dll")] \npublic static extern uint PeerGroupCreateInvitation( \n                IntPtr hGroup,  /* Updated with @RedDude's suggestion */\n                [MarshalAs(UnmanagedType.BStr)] string pwzIdentityInfo, \n                int pftExpiration, // 32 bit, not 64 bit \n                int cRoles, \n                ref Guid pRoles, \n                out IntPtr ppwzInvitation);	0
18206471	18204687	Rewriting method declaration	static MethodDeclarationSyntax \n    RewriteMethodDeclaration(MethodDeclarationSyntax method, string name)\n{\n    var type = Syntax.ParseTypeName("dynamic");\n    var identifier = Syntax.Identifier(String.Format(" {0}", name));\n    var p = Syntax.Parameter(\n        new SyntaxList<AttributeListSyntax>(),\n        new SyntaxTokenList(),\n        type,\n        identifier,\n        null);\n    var parameters = method.ParameterList.AddParameters(p);\n    return method.WithParameterList(parameters);\n}	0
17718542	17717756	Compressing Files With C# By Winrar	string somepath = "D:\\ExcelFiles";\n        string zippath = "D:\\ExcelFiles\\some.zip";\n        string[] filenames =\n        System.IO.Directory.GetFiles(somepath, "Mark*.xlsx", SearchOption.AllDirectories);\n\n        using (ZipFile zip = new ZipFile())\n        {\n            foreach (String filename in filenames)\n            {\n\n                ZipEntry e = zip.AddFile(filename, "");\n\n            }\n            zip.Save(zippath);\n        }	0
4567960	4564389	Need help configuring SQL Server CE connections string in Fluent NHibernate	return Fluently.Configure()\n                        .Database(MsSqlCeConfiguration.Standard.ShowSql().ConnectionString(c => c.Is("data source=" + path)))\n                        .Mappings(m => m.FluentMappings.AddFromAssemblyOf<Project>())\n                        .BuildSessionFactory();	0
207262	207256	How do I match part of a string only if it is not preceded by certain characters?	((?!SIGSEC)\w{3}(?:SEC|PRI))	0
17963623	17962754	Show tooltip in LineSeries WinForms Chart?	series.ToolTip = string.Format("Name '{0}' : X - {1} , Y - {2}", chartPoint.SetName, "#VALX{F2}",\n                                               "#VALY{F2}");\n        mainChartControl.GetToolTipText += ChartControlGetToolTipText;\n\n private void ChartControlGetToolTipText(object sender, ToolTipEventArgs e)\n    {\n    }	0
607706	606642	Help needed for 'cross-thread operation error' in C#	public delegate void MyDelegate(Message msg);\nvoid foo_MessageReceived(Message message)\n{ \n   if (InvokeRequired)\n   {\n      BeginInvoke(new MyDelegate(foo_MessageReceived),new object[]{message});\n   }\n   else\n   {\n      label1.Text = message.Body;\n   }\n}	0
13442553	13442387	How to refactor sql query in a foreach	foreach(var x_tmp in db.tblX.Where(x => rlist.Where(r => r.indexOf("_") != -1).Select(r => Convert.ToInt32(r.Split('_')[1])).Contains(x.x_id)))\n     x_tmp = someNumber;\ndb.SaveChanges();	0
18065278	18064955	How to remove Duplicates from two List except few elements which may be duplicate also?	List<string> wordstoKeep = new List<string>() { "ASCB", "Arinc" };\n\nforeach (string str in listB)\n{\n    int index = listA.FindIndex(x => x.Equals(str, StringComparison.OrdinalIgnoreCase));\n    if (index >= 0)\n    {\n       if (!wordstoKeep.Any(x => x.Equals(str, StringComparison.OrdinalIgnoreCase)))\n           listA.RemoveAt(index);\n    }\n    else\n       listA.Add(str);\n}	0
25831499	25831462	how to make the text box show the date directly without putting the cursor and tap in the keybaord	private void Form_Load(object sender, EventArgs e)\n{\n     DateTime d = DateTime.Now; rdate.Text = d.ToString();\n}	0
25830576	25830532	How to add a new unique string to text file	var lines = File.ReadAllLines(@"C:\Temp.txt");\nif(lines.Any(x=>x == word)\n{\n    //There is a word in the file\n}\nelse\n{\n    //Thee is no word in the file\n}	0
17723171	17722985	Unable to Split the string accordingly	string actual = "Doc1;Doc2;Doc3;12";\nint lstindex = actual.LastIndexOf(';');\nstring strvalue = actual.Substring(0, lstindex);\nstring id = actual.Substring(lstindex + 1);	0
14395038	14394647	Uploading image to server with ASIFormDataRequest	- (NSString*) stringFromImage:(UIImage*)image\n{\n    if(image){\n        NSData *dataObj = UIImagePNGRepresentation(image);\n        return [dataObj base64Encoding];\n    } else {\n        return @"";\n    }\n}\n\n- (UIImage*) imageFromString:(NSString*)imageString\n{\n    NSData* imageData =[NSData dataWithBase64EncodedString:imageString];\n    return [UIImage imageWithData: imageData];\n\n}	0
21281188	21281025	Factory Returns Interface	public class RequestFactory : IRequestFactory\n{\n    public ISupportHardwareEnquiry CreateSupportHardwareEnquiry()\n    {\n        return new SupportHardwareEnquiry();\n    }\n\n\n    public IRequest CreateAlternateDriverEnquiry()\n    {\n        return new AlternateDriverEnquiry();\n    }\n}	0
16260947	16260822	Solution for Calling Clients from Server Application	YesIamAlive()	0
5691325	5690352	How would I safely get these JSON values from an API response if I don't know the keys?	var dates = (JObject)x["release_dates"];\nforeach (var date in dates)\n{\n    ReleaseDate releaseDate = new ReleaseDate();\n\n    releaseDate.Type = (string)date.Key;\n\n    var tmpDate = ((string) date.Value).Substring(0, ((string) date.Value).Count());\n    releaseDate.Date = DateTime.Parse(tmpDate);\n\n    movie.ReleaseDates.Add(releaseDate);\n}	0
16568164	16568037	How can I set a panel to be always on top when changing tabpages in C#?	private void Form1_Load(object sender, EventArgs e)\n    {\n        Point pt = panel1.PointToScreen(new Point(0, 0));\n        panel1.Parent = this;\n        panel1.Location = this.PointToClient(pt);\n        panel1.BringToFront();\n    }	0
909735	876749	Open PDF file in RichTextBox in WPF	using PdfLib;\nnamespace WindowsFormsApplication1{\npublic partial class ViewerForm : Form{\n    public ViewerForm()\n    {\n     InitializeComponent();\n     PdfLib.AxAcroPDF axAcroPDF1;\n     axAcroPDF1.LoadFile(@"C:\Documents and Settings\jcrowe\Desktop\Medical Gas\_0708170240_001.pdf");\n     axAcroPDF1.Show(); }\n\n    private void richTextBox1_TextChanged(object sender, EventArgs e)\n    {   } } }	0
3229376	3229346	How to get HTML code of a .NET control	StringBuilder content = new StringBuilder();\nStringWriter sWriter = new StringWriter(content);\nHtmlTextWriter htmlWriter = new HtmlTextWriter(sWriter);\npnlMyPanel.RenderControl( htmlWriter );	0
7286508	7286477	Possible to specify directory path with a wildcard?	foreach (string directory in Directory.GetDirectories(sourcePath, "di*"))\n{\n    // whatever\n}	0
12341864	12341687	save a byte[] with 32 entries to localSettings in Metro Style App	byte[] passbyte = new byte[32];\n\n// Store\nlocalSettings.Values["password"] = passbyte;\n\n// Fetch\nvar passwordsecure = localSettings.Values["password"] as byte[];	0
1270397	1270383	How to convert code page ascii to code page 1255	serialPort.Encoding = Encoding.GetEncoding(1255);	0
31703735	31703576	Any way to see how last reboot was executed?	Log = "System"\nSource = "EventLog"\nFilter EventLogEntry for EventID == 6008	0
13038969	13037817	Disconnect from Microsoft Excel Interop without crashing host C# program	private static Microsoft.Office.Interop.Excel.Application xlApp = null;\n            private static Microsoft.Office.Interop.Excel.Workbook xlWb = null;\n            private static Microsoft.Office.Interop.Excel.Worksheet xlWs = null;\n\n\n            //Your code and operations\n\n\n            xlWb.SaveAs(filePath, XlFileFormat.xlExcel8, Missing.Value, Missing.Value, Missing.Value, Missing.Value, XlSaveAsAccessMode.xlNoChange,\n                        Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value);\n            xlApp.Quit();\n\n            Marshal.ReleaseComObject(xlWs);\n            Marshal.ReleaseComObject(xlWb);\n            Marshal.ReleaseComObject(xlApp);	0
6436281	6436239	How to cast objects to double with minimum casting	double sum = new[] { obj1, obj2, obj3, obj4 }.Cast<double>().Sum();	0
11560226	11559931	Creating Windows Service with Scheduler?	static Timer timer; \nstatic object locker = new object(); \n\npublic void Start() \n{ \n    var callback = new TimerCallback(DoSomething); \n    timer = new Timer(callback, null, 0, 300000); \n} \n\npublic void DoSomething() \n{ \n    if (Monitor.TryEnter(locker)) \n    { \n       try \n       { \n           // my processing code \n       } \n       finally \n       { \n           Monitor.Exit(locker); \n       } \n    } \n}	0
2598371	2593477	Mocking lambda in rhino mocks	repository.Expect(action => action.Find<Entity>(x => x.ID == 0))\n          .IgnoreArguments()\n          .Return(entities)\n          .Repeat\n          .Any();	0
19454483	19454065	C# browser automation that will work on server	var driver = OpenQA.Selenium.PhantomJS.PhantomJSDriver();	0
917358	893752	InvalidOperationException - When ending editing a cell & moving to another cell	private void dataGridView1_CellEndEdit(object sender, DataGridViewCellEventArgs e)\n{\n    ...................................................;\n    if (toUpdate)\n    {\n        foreach(DataRow row in dt.Rows)\n        {\n            if ( (int)row["ID"] == id)\n            {\n                row[columnName] = value;\n            }\n        }\n\n        this.BeginInvoke(new MethodInvoker(Refresh_dataGridView1));\n    }\n}	0
11438721	11438631	Silverlight run DispatchTimer only once	DispatcherTimer clock = new DispatcherTimer();\nclock.Interval = TimeSpan.FromSeconds(10);\nclock.Tick += (object sender, EventArgs e) =>\n{\n    clock.Stop();\n    // Some code here\n};\nclock.Start();	0
2955001	2954962	Decimal to binary conversion in c #	int value = 8;\nstring binary = Convert.ToString(value, 2);	0
22898120	22897092	update cell in datagrid wpf	dgInvoices.Items.Refresh();	0
34456938	34456895	How to change textbox values dynamically	private void txtPrice_TextChanged(object sender, EventArgs e)\n    {\n          int rate = 0;\n          int qty = 0;\n\n          Int32.TryParse(txtRate.Text, out rate);\n          Int32.TryParse(txtQty.Text, out qty);\n\n          int total = rate * qty\n\n          // Set the new textBox value\n          // txtTotal should be your textbox value (what you have called it)\n          txtTotal.Text = total.toString()\n    }	0
25584021	25583917	C# same method, but different parameters: with ref and without	public void method (ref int a)\n{\n    //do some stuff\n}\n\npublic void method(int a)\n{\n    method(ref a);  //do the same stuff of method(ref int a)\n}	0
13110455	13110422	Importing Images into Image boxes	Image myImage = new Image();\nmyImage.Source = new BitmapImage(new Uri("myPicture.jpg", UriKind.RelativeOrAbsolute));	0
16969245	16968004	get the url <img src=''> a rss feed and open on <image> in xaml Windos Phone	using System.Text.RegularExpressions;\n...\nImage = Regex.Match(s.Summary.Text, @"<img\s+src='(.+)'\s+border='0'\s+/>").Groups[1].Value,	0
1752505	1752499	C# testing to see if a string is an integer?	string x = "42";\nint value;\nif(int.TryParse(x, out value))\n  // Do something	0
7075927	7070522	Outlook 2010 VSTO - Standard Office icon in a Form Region	Sub OnAction(control As IRibbonControl, id As String, index As Integer)\n    If (control.Tag = "large") Then\n        id = Strings.Mid(id, 3)\n    End If\n\n    Dim form As New ControlInfoForm\n    form.nameX.Caption = "imageMso: " & id\n    Set form.Image1.Picture = Application.CommandBars.GetImageMso(id, 16, 16)\n    Set form.Image2.Picture = Application.CommandBars.GetImageMso(id, 32, 32)\n    form.Show\nEnd Sub	0
9807809	9806332	Image to byte[], Convert and ConvertBack	public class BytesToImageConverter : IValueConverter\n{\n    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)\n    {\n        MemoryStream stream = new MemoryStream((Byte[])value);\n        WriteableBitmap bmp = new WriteableBitmap(173, 173);\n        bmp.LoadJpeg(stream);\n        return bmp;\n    }\n\n    public object ConvertBack(object value, Type targetType, object parameter,\n                                System.Globalization.CultureInfo culture)\n    {\n        throw new NotImplementedException();\n    }\n}	0
2134230	2120439	Handler for Custom Attached Event	public delegate void DropEventHandler(object sender, DropEventArgs e);\n\n    public static readonly RoutedEvent DropEvent = EventManager.RegisterRoutedEvent(\n        "Drop", RoutingStrategy.Bubble, typeof(DropEventHandler), typeof(DragDropHelper));	0
10904708	10904603	Get Windows service dependencies using C#	StringBuilder sb = new System.Text.StringBuilder();\nforeach (var svc in System.ServiceProcess.ServiceController.GetServices())\n{\n    sb.AppendLine("============================");\n    sb.AppendLine(svc.DisplayName);\n    foreach (var dep in svc.DependentServices)\n    {\n        sb.AppendFormat("\t{0}", dep.DisplayName);\n        sb.AppendLine();\n    }\n}\n\nMessageBox.Show(sb.ToString());	0
2614725	2614469	How to backup database (SQL Server 2008) in C# without using SMO?	if (saveFileDialog1.ShowDialog() == DialogResult.OK)\n{\n    string connStr = "Data Source=M1-PC;Initial Catalog=master;Integrated Security=True;Pooling=False";\n\n    using(SqlConnection conn = new SqlConnection(connStr))\n    {\n       string sqlStmt = String.Format("BACKUP DATABASE LA TO DISK='{0}'", saveFileDialog1.FileName);\n\n       using(SqlCommand bu2 = new SqlCommand(sqlStmt, conn))\n       {\n           conn.Open();\n           bu2.ExecuteNonQuery();\n           conn.Close();\n\n           MessageBox.Show("ok");\n       }\n    }\n}	0
20908405	20908064	How to read id with loop from list in asp.net	var result = new int[DataList.Count*2];\n    for (int i = 0; i < DataList.Count; i++)\n    {\n        result[i * 2] = DataList[i].Id;\n        result[i * 2 + 1] = DataList[i].LinkedUserId;\n    }	0
1671512	1671294	C# Lock WinForm Controls	private void enableControlsMove()\n{\n    foreach (Control theControl in panel1.Controls)\n    {\n        Console.WriteLine(theControl.Name);\n\n        theControl.MouseDown += new MouseEventHandler(theControl_MouseDown);\n        theControl.MouseUp += new MouseEventHandler(theControl_MouseUp);\n        theControl.MouseMove += new MouseEventHandler(theControl_MouseMove);\n    }\n}\n\nprivate void disableControlsMove()\n{\n    foreach (Control theControl in panel1.Controls)\n    {\n        Console.WriteLine(theControl.Name);\n\n        theControl.MouseDown -= theControl_MouseDown;\n        theControl.MouseUp -= theControl_MouseUp;\n        theControl.MouseMove -= theControl_MouseMove;\n    }\n}	0
32079368	32079067	Linq: Join 2 tables that share one column name (with different data)	var query = from cost in COSTS\n                join credit in CREDITS\n                on cost.IdCredit equals credit.IdCredit into joined\n                from j in joined.DefaultIfEmpty()\n                select new SearchCredit\n                {\n                    CreditLabel = j.Label,\n                    CostLabel = cost.Label\n                };	0
11551580	11545479	MongoDb Change order of array elements	XDB = db.locations;\nvar iter = XDB.find()\n\ndo {\n    var doc = iter.next();\n    var newdoc = {};\n    newdoc.Coordinates = [];\n    for ( var k in doc.Coordinates ) {\n        var newpair = { Latitude: doc.Coordinates[k].Latitude, \n                        Longitude: doc.Coordinates[k].Longitude } ;\n        newdoc.Coordinates.push(newpair);\n    }\n    XDB.update({_id: doc._id}, newdoc );\n} while ( iter.hasNext() );	0
7145470	7145446	How do you return an integer from a database using c#?	var reader = dba.QueryDatabase(sqlQuery);\nif(reader.Read())\n{\n  return reader.GetInt32(0);\n}\n// else error\nthrow new Exception("no result found");	0
32101604	32097016	How do I connect to a Azure Worker Role with tcp endpoint? Tech help needed with Tcp and Azure	IPAddress ipAddress = IPAddress.Parse("13.71.112.31");\n    int port = 10;\n    TcpClient client = new TcpClient();\n\n    try\n    {\n        client.Connect(ipAddress, port);\n            if (client.Connected) // now true\n            {	0
16800973	16800946	How do I return the enum value that matches a given string?	var t = (Types)Enum.Parse(typeof(Types), "two");	0
5888050	5887982	autocomplete display distinct items	if(!suggestions.Contains(itemName))\n  suggestions.Add(itemName);	0
33912527	33912379	how to parse time in timespan which is in hh:mm:ss tt format in c#	string s = "5:19:41 PM";\nDateTime t = DateTime.ParseExact(s, "h:mm:ss tt", CultureInfo.InvariantCulture); \n//if you really need a TimeSpan this will get the time elapsed since midnight:\nTimeSpan ts = t.TimeOfDay;	0
9703420	9535698	Access to a GridCheckboxColumn	CheckBox checkboxfacturable = (CheckBox)dataItem["facturable"].Controls[0]; \nLabel label = (Label)dataItem["typedestickets"].Controls[0];	0
22426683	22426652	How to scan and display the expired products in an inventory system	DateTime CurrentDate = DateTime.Now;\nstring query = "select * from inventory where Exp\n                       < (Select DATEADD(day,5,@CurrentDate))";\nSqlCommand command = new SqlCommand(query);\ncommand.Parameters.AddWithValue(@CurrentDate ,CurrentDate);\nSqlDataAdapter m_da = new SqlDataAdapter(command , MySqlConnection);	0
20032481	20031535	OpenGL warning from a .NET program	err:[0xc784]:d3d_surface:D:\tinderbox\add-4.3\src\VBox\Additions\WINNT\Graphics\Wine_new\wined3d\surface.c 6245: Surface 000000001CCDFB30 does not have any tp to date location.	0
7435973	7435793	C# insert into Table from Dataset	using (SqlBulkCopy copy = new SqlBulkCopy(\n   {   \n                copy.ColumnMappings.Add("dtcolumnname", "sqlcolumnname");\n\n\n        copy.DestinationTableName = "TABLE";\n        copy.WriteToServer(table);\n    }	0
1413351	1404953	C# Assign a Variable to a Class call	using Me = GPS.devise.coordinates;	0
4529877	4529816	SQL Server 2008 R2 connection string	Data Source=myServerAddress;Initial Catalog=myDataBase;Integrated Security=SSPI;	0
19736975	19736035	How to align floating point numbers in C# (left padding)	label.Text = number.ToString("0.00").PadLeft(6,'\x2007');	0
3712749	3712732	How to create a generic List with a dynamic object type	Type listT = typeof(List<>).MakeGenericType(new[]{type});\nobject list = Activator.CreateInstance(listT);	0
16918499	16918341	unable to clear a textbox data	private void textBox1_KeyPress(object sender, KeyPressEventArgs e)\n    {\n        if (char.IsDigit(e.KeyChar) == false)\n        {\n            count++;\n        }\n        if (count == 1)\n        {\n            textBox1.Text = ("");\n            count = 0;\n            e.Handled = true; // this bit fixes it\n        }\n    }	0
28631870	28631801	How to Check for valid input c#	return calculateDart1();	0
18270877	18270363	Substrings using regex grouping in C#	// string strTargetString = @"Acceptance :DT_Ext_0062-12_012ed2 [Describe]";\n// string strTargetString = @"Acceptance : DT_Ext_0062-12_012 (ed.2) , Describe";\nstring strTargetString = @"Acceptance of : DT_Ext_0062-12_012 (ed.2) , Describe to me";\n\n const string strRegex = @"\.*:\s*(DT_Ext_\d{4}-\d{2}_\d{3})\s*\W*(ed)\.?(\d+)(\W*[,])?(.*)";\n\n\nRegexOptions myRegexOptions = RegexOptions.IgnoreCase | RegexOptions.Multiline | RegexOptions.CultureInvariant;\nRegex myRegex = new Regex(strRegex, myRegexOptions);\n\n\nforeach(Match myMatch in myRegex.Matches(strTargetString))\n{\n    if(myMatch.Success)\n    {\n        // Add your code here\n        var value = new {\n            Value1 = myMatch.Groups[1].Value,\n            Value2 = myMatch.Groups[2].Value,\n            Value3 = myMatch.Groups[3].Value,\n            Value4 = myMatch.Groups[5].Value,\n        };\n    }\n}	0
10658411	10657078	WCF - Implementing a ServiceHostFactory to use into IIS context (svc file)	private IEnumerable<Type> GetContractType(Type serviceType) \n{ \n    if (HasServiceContract(serviceType))\n    { \n        yield return serviceType; \n    } \n\n    var contractInterfaceTypes = serviceType.GetInterfaces() \n        .Where(i => HasServiceContract(i));\n\n    foreach (var type in contractInterfaceTypes)\n    {\n        yield return type;\n    }\n\n    // if you want, you can also go to the service base class,\n    // interface inheritance, etc.\n} \n\nprivate static bool HasServiceContract(Type type) \n{ \n    return Attribute.IsDefined(type, typeof(ServiceContractAttribute), false); \n}	0
26015242	26014707	split strings and assign them to dictionary	var regexp = new Regex(@"(?<category>\w+?)\{(?<entities>.*?)\}");\nvar d = new Dictionary<string, List<string>>();\n\n// you would replace this list with the lines read from the file\nvar list = new string[] {"Flowers{Tulip|Sun Flower|Rose}"\n                         , " Gender{Female|Male}"\n                         , "Pets{Cat|Dog|Rabbit}"};\n\nforeach (var entry in list)\n{\n    var mc = regexp.Matches(entry);\n    foreach (Match m in mc)\n    {\n        d.Add(m.Groups["category"].Value\n            , m.Groups["entities"].Value.Split('|').ToList());\n    }\n}	0
24714580	24713611	Select attribute from xml element	XDocument ManifestDocument = XDocument.Load("YourXmlFile.xml");\n\nvar myquery = ManifestDocument.Elements().Attributes("SymbolicName").First();//the XAttribute\n\nstring myvalue = ManifestDocument.Root.Attribute("SymbolicName").Value;//the value itself\n\nvar secondquery = ManifestDocument.Descendants().Attributes("SymbolicName").First();//another way to get the XAttribute	0
2528872	2521247	How to read an IIS 6 Website's Directory Structure using WMI?	"Select * from Win32_directory where drive ='"+ DriveLetter +":' and Path ='%" + MyPath + "%'";	0
17300859	17295489	How to add number of records in a grid from devexpress	gridView1.OptionsView.ShowFooter = true;	0
20137819	20137555	Writing a recursive function in C#	public bool AreParenthesesBalanced(string input) {\n  int k = 0;\n  for (int i = 0; i < input.Length; i++) {\n      if (input[i] == '(') k++;\n      else if (input[i] == ')'){\n        if(k > 0)  k--;\n        else return false;\n      }\n  }\n  return k == 0;\n}	0
14374780	13620479	How to scalling Secondary axis (AxisY2) in Line chart of MS Chart?	chart1.ChartAreas["Area"].AxisY2.ScaleView.Zoomable = true;\nchart1.ChartAreas["Area"].AxisY2.ScaleView.Zoom(ScaleMinValue, ScaleMaxValue);	0
8215297	8215197	How to insert line break in big text file	try\n    {\n        using (StreamReader sr = new StreamReader(@"C:\bigfile.txt"))\n        {\n            using (StreamWriter sw = new StreamWriter(@"C:\bigfilelinebreak.txt"))\n            {\n                char [] buf = new char[40];\n                int read = sr.ReadBlock (buf, 0, 40);\n                while (read != 0)\n                {\n                    sw.Write(buf, 0, read);\n                    sw.WriteLine();\n                    read = sr.ReadBlock (buf, 0, 40);\n                }\n            }\n        }\n    }	0
1859523	1859507	Displaying numbers without decimal points	double x = 12;\ndouble y = 12.1;\ndouble z = 12.11;\nConsole.WriteLine(x.ToString(?0.#?));\nConsole.WriteLine(y.ToString(?0.#?));\nConsole.WriteLine(z.ToString(?0.#?));	0
3634739	3634694	Sorting a List<T> by DateTime	customers.Sort((x, y) => x.DateOfBirth.CompareTo(y.DateOfBirth));	0
7851966	7851684	How to use moq to test code that calls protected helpers	mockClass.Protected().Setup<bool>("HelperMethod").Returns(false);	0
15165050	15145037	Prevent Race Condition in Efficient Consumer Producer model	if (dataToSend.IsEmpty)\n{\n     //Declare that we are no longer the consumer.\n     Interlocked.Decrement(ref RunningWrites);\n\n     //Double check the queue to prevent race condition A\n     if (Queue.IsEmpty)\n         return;\n     else\n     {   //Race condition A occurred. There is data again.\n\n         //Let's try to become a consumer.\n         if (Interlocked.CompareExchange(ref RunningWrites, 1, 0) == 0)\n               continue;\n\n         //Another thread has nominated itself as the consumer. Our job is done.\n         return;\n     }                                    \n}\n\nbreak;	0
3913486	3913371	SqlBulkCopy from a List<>	SqlBulkCopy.WriteToServer	0
3476654	3476397	How can I switch radio button to yes or no without selection	private void DataGrid1_ItemDataBound(object sender, System.Web.UI.WebControls.DataGridItemEventArgs e)\n{\nif(e.Item.ItemType==System.Web.UI.WebControls.ListItemType.EditItem)\n\nRadioButton rBtnTest = e.Item.FindControl("radiobutton id") as RadioButton;\n// Check condition and if it's true\nif(your_condition == true)\n rBtnTest.Checked = true;\nelse\n rBtnTest.Checked = false;\n}	0
1645100	1645077	C# Lambda puzzling behaviour	a = b = c = d = 10;	0
14742993	14742547	Select all in DataGridViewCell	// Update CurrentCell to the provided Cell\n// Can be skipped if Cell is actually the CurrentCell\nCell.DataGridView.CurrentCell = Cell;\n\n// Change the grid's CurrentCell to edit mode and select text\nCell.DataGridView.BeginEdit(true);	0
5450005	5449997	convert ushort[] grayscale values to byte[]	byte value = (byte)(array[index] >> 8);	0
31886393	31879522	Downloading file via FTP fails (only downloads portion of file)	byte[] buffer = new byte[bufferSize];\nint bytesRead;\nwhile ((bytesRead = reader.Read(buffer, 0, buffer.Length)) > 0)\n{\n    fileWrite.Write(chunk, 0, bytesRead);\n    totalBytes += bytesRead;\n    Console.WriteLine("BytesRead: " + bytesRead + " -- TotalBytes: " + totalBytes);\n}	0
9670641	9670507	How a Multi Monitor application can detect a missing monitor	int index;\nint upperBound; \nScreen [] screens = Screen.AllScreens;\nupperBound = screens.GetUpperBound(0);\nfor(index = 0; index <= upperBound; index++)\n{\n// For each screen, add the screen properties to a list box.\n   listBox1.Items.Add("Device Name: " + screens[index].DeviceName);\n   listBox1.Items.Add("Bounds: " + screens[index].Bounds.ToString());\n   listBox1.Items.Add("Type: " + screens[index].GetType().ToString());\n   listBox1.Items.Add("Working Area: " + screens[index].WorkingArea.ToString());\n   listBox1.Items.Add("Primary Screen: " + screens[index].Primary.ToString());\n}	0
32199907	32199655	Can't iterate through a combobox from a focused textbox	private void txtbox_KeyDown(object sender, KeyEventArgs e) {\n  // Use "e.Modifiers == Keys.None" \n  // if you want just Down Arrow and not, say, Alt + Down; Shift + Down etc.\n  if ((e.KeyCode == Keys.Down) && (e.Modifiers == Keys.None)) {\n    // We don't need default behaviour whatever it is\n    e.Handled = true;\n    ComboBox combo = sender as ComboBox;\n\n    // If selected index is not the last one, select the next item\n    if (combo != null)\n      if (combo.SelectedIndex < (combo.Items.Count - 1))    \n        combo.SelectedIndex += 1;\n  }\n}	0
17922508	17922308	use latest version of ie in webbrowser control	try\n{\n    var IEVAlue =  9000; // can be: 9999 , 9000, 8888, 8000, 7000\n    var targetApplication = Processes.getCurrentProcessName() + ".exe"; \n    var localMachine = Registry.LocalMachine;\n    var parentKeyLocation = @"SOFTWARE\Microsoft\Internet Explorer\MAIN\FeatureControl";\n    var keyName = "FEATURE_BROWSER_EMULATION";\n    "opening up Key: {0} at {1}".info(keyName, parentKeyLocation);\n    var subKey = localMachine.getOrCreateSubKey(parentKeyLocation,keyName,true);\n    subKey.SetValue(targetApplication, IEVAlue,RegistryValueKind.DWord);\n    return "all done, now try it on a new process".info();\n}\ncatch(Exception ex)\n{\n    ex.log();\n    "NOTE: you need to run this under no UAC".info();\n}	0
24371095	24370959	How to continuously check for CPU usage in C#?	PerformanceCounter counter = new PerformanceCounter("Processor", "% Processor Time", "_Total");\n   while (true)\n   {\n       float cpuPercent = counter.nextValue();\n       if (cpuPercent >= 5)\n       {\n           totalhits += 1;\n           if (totalhits == 10)\n           {\n               Console.WriteLine("Alert Usage has exceeded");\n               Console.WriteLine("Press Enter to continue");\n               Console.ReadLine();\n               totalhits = 0;\n           }\n       }\n       else\n       {\n           totalhits = 0;\n       }\n   }	0
15471207	15471034	How to find forgot password from the database?	DataSet ds =DataAccessLayer.ExeSelectQuery(sQuery);\n            try\n            {\n\n  if(ds .Tables[0].Rows.Count>0)\n                {\n  string sUserName = "";\n                string sPassword = "";\n                 sUserName =   ds.Tables[0].Rows[0]["Username"].ToString();\n                 sPassword =   ds.Tables[0].Rows[0]["Password"].ToString();\nsendMail( sUserName, sPassword);\n                } \n            }	0
28550025	28549852	C# interface access implementers type for generic	public class A<T> where T : default(string) { ... }	0
19925151	19924790	how to set output parameter of mysqldataadapter	msdadapter.SelectCommand.Parameters.Add("p_maxsi", MySqlDbType.Decimal).Direction = ParameterDirection.Output;	0
2096844	2096489	C# removing items from listbox	sqldatapull = dr[0].ToString();\n                if (sqldatapull.StartsWith("OBJECT"))\n                {\n                    sqldatapull = "";\n                }\n                listBox1.Items.Add(sqldatapull);\n                for (int i = listBox1.Items.Count - 1; i >= 0; i--)\n                {\n                    if (String.IsNullOrEmpty(listBox1.Items[i] as String))\n                        listBox1.Items.RemoveAt(i);\n                }\n            }	0
11601370	11601198	Button in a DataGrid column, getting the cell values of row from which it came on the Click event handler	//youll need to google for GetVisualParent function.\nDataGridRow row = GetVisualParent<DataGridRow>(button);\nfor(int j = 0; j < dataGrid.Columns.Count; j++)\n   DataGridCell cell = GetCell(dataGrid, row, j);	0
14589690	14586521	Bind ViewModel to Item from LongListSelector in DataTemplate	public static DependencyProperty MyItemProperty = DependencyProperty.Register("MyItem", typeof(object), typeof(MyViewModel), new PropertyMetadata(string.Empty, ItemChanged));\n private static void ItemChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)\n{\n        var obj = d as MyViewModel;\n        obj.RaisePropChangeEvent("MyItem");\n}	0
33337634	33336935	How to Flip An Image in C#	int Height = TransformedPic.GetLength(0);\n        int Width = TransformedPic.GetLength(1);\n\n        for (int i = 0; i < Height / 2; i++)\n        {\n            for (int j = 0; j < Width; j++)\n            {\n                var tmp = TransformedPic[i, j];\n                TransformedPic[i, j] = TransformedPic[Height - 1 - i, j];\n                TransformedPic[Height - 1 - i, j] = tmp;\n            }\n        }	0
16057663	16057479	How to access a property of a custom class using Linq to Object?	var listLogFiles = new List<LogFiles>();\nvar orderedListLogFiles = (from a in listLogFiles \n                           order by a.LogStatus\n                           select a);	0
21954932	21954877	How to retrieve alphanumeric rows?	var res = dataSource\n    .MyTable\n    .AsEnumerable()\n    .Where(s => s.IdentityNumber.Any(Char.IsDigit) && s.IdentityNumber.Any(Char.IsLetter));	0
14048542	5738123	Using EPPlus with a MemoryStream	using (var package = new ExcelPackage())\n{\n    var worksheet = package.Workbook.Worksheets.Add("Worksheet Name");\n\n    worksheet.Cells["A1"].LoadFromCollection(data);\n\n    var stream = new MemoryStream(package.GetAsByteArray());\n}	0
31527831	31527455	How do I get a click event from a GridViewColumn header?	AddHandler(GridViewColumnHeader.ClickEvent, new RoutedEventHandler(ListView_OnColumnClick));	0
33110478	33108261	Best way to get selected item OR entered text from combobox	string Code1 = comboBox_Code1.Text;	0
620103	611092	How do you login to a webpage and retrieve its content in C#?	string postData = "userid=ducon";\n            postData += "&username=camarche" ;\n            byte[] data = Encoding.ASCII.GetBytes(postData);\n            WebRequest req = WebRequest.Create(\n                URL);\n            req.Method = "POST";\n            req.ContentType = "application/x-www-form-urlencoded";\n            req.ContentLength = data.Length;\n            Stream newStream = req.GetRequestStream();\n            newStream.Write(data, 0, data.Length);\n            newStream.Close();\n            StreamReader reader = new StreamReader(req.GetResponse().GetResponseStream(), System.Text.Encoding.GetEncoding("iso-8859-1"));\n            string coco = reader.ReadToEnd();	0
14670417	14670379	Foreach item in TableLayoutPanel row1	foreach ( Control c in this.TableLayoutPanel1.Controls )\n{\n    Console.WriteLine(this.TableLayoutPanel1.GetRow(c));\n}	0
15168004	15167875	How to disable menu items in the ContextMenuStrip?	void listView1_MouseDown(object sender, MouseEventArgs e) {\n  if (e.Button == MouseButtons.Right) {\n    updateToolStripMenuItem.Enabled = (listView1.Items.Count > 0);\n  }\n}	0
9989385	9988595	Windows Phone 7 read and parse XML data from web service	penalty = resultElements.Element("studentPunishmentsTable").Element("penalty").Value;\nsemester = resultElements.Element("studentPunishmentsTable").Element("semester").Value;	0
32138649	32133239	How To Hide Certain column if User Choose filter,Sorting or Grouping in xtraGridView Devexpress Windows Form	gridView1.ColumnFilterChanged += (s, e) => { gridView1.Columns[0].Visible = false; };	0
32681091	32680705	Posting JSON to web service (400) Bad Request	{"type":"smsmessage","to":"07984389886","from":"07984389886","body":"THIS IS A TEXT MESSAGE"}	0
7150565	7150228	LinqToSql: Select field from list used within a query	var products = (from product in context.Product                \n                where installs.Select(i => i.ProductId).Contains(p.ProductId)\n                select product).ToList()\n\nvar installedProducts = (from product in products\n                         join install in installs\n                         on install.ProductId equals product.ProductId\n                         select new \n                         {\n                             ProductNumber = product.ProductNumber,\n                             InstallationId = install.InstallationId\n                         }).ToList();	0
13809387	13808930	How can I include saving in a text file in executable file?	var filePath = Path.Combine(\n   Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + "\\",\n   ConnectFour.txt");\nusing(var  myFile = File.CreateText(filePAth))\n{\n  // save data here.\n}	0
3746597	3746594	Specific .NET XML enumeration procedure	XDocument doc = XDocument.Load("file.xml");\n\nforeach (XElement element in doc.Descendants("objectname"))\n{\n    string s = (string) element.Attribute("attribname");\n    // ...\n}	0
15051350	15051316	How to create a object reference in C#?	public string testCHECK(SqlCeConnection thisConnection)\n{\n    if (thisConnection.State == ConnectionState.Open)\n    {\n        return "Database connection: Open";\n    }\n    if (thisConnection.State == ConnectionState.Closed)\n    {\n        return "Database connection: Closed";\n    }\n    else\n    {\n        return "";\n    }\n}	0
4435828	4429103	How can I set up two navigation properties of the same type in Entity Framework	protected override void OnModelCreating(ModelBuilder modelBuilder)\n{\n    modelBuilder.Entity<AdapterFrameCapability>()\n                .HasRequired(afc => afc.FromPressType)\n                .WithMany()\n                .HasForeignKey(afc => afc.FromPressTypeID)\n                .WillCascadeOnDelete(true);\n\n    modelBuilder.Entity<AdapterFrameCapability>()\n                .HasRequired(afc => afc.ToPressType)\n                .WithMany()\n                .HasForeignKey(afc => afc.ToPressTypeID)\n                .WillCascadeOnDelete(false);\n}	0
525169	525158	Can a generic class be forced to have a type inherit from one of two interfaces?	public interface BaseInterface\n{\n}\n\npublic interface Interface1 : BaseInterface\n{\n    void SomeMethod();\n}\n\npublic interface Interface2 : BaseInterface\n{\n    void SomeOtherMethod();\n}\n\npublic class MyGenericClass<T> where T : BaseInterface\n{\n    ...\n}\n\nvar myClass1 = new MyGenericClass<Interface1>();\n\nvar myClass2 = new MyGenericClass<Interface2>();	0
6920764	6920730	How to read all pages from PDF?	PDFDoc doc = new PDFDoc(input_path);\n    doc.InitSecurityHandler();\n     PageIterator itr = doc.GetPageIterator();\n     for (; itr.HasNext(); itr.Next()) //  Read every page\n    {\n    for (line = txt.GetFirstLine(); line.IsValid(); line = line.GetNextLine())\n    {\n    for (word = line.GetFirstWord(); word.IsValid(); word = word.GetNextWord())\n    {\n    Console.WriteLine(word.GetString());\n    }\n    }\n    }	0
13652527	13652526	Converting Asp.Net GridView with controls to DataTable	protected DataTable ConvertToDataTable()\n{\n    DataTable TempTable = new DataTable();\n    TempTable = dtCompanies.Clone();\n\n    foreach (GridViewRow row in gvCompanies.Rows)\n    {\n         DataRow TempRow = TempTable.NewRow();\n\n         for (int i = 0; i < row.Cells.Count; i++)\n         {\n             if (row.Cells[i].Controls[0].GetType().Equals(typeof(DataBoundLiteralControl)))\n             {\n                 TempRow[i] = ((DataBoundLiteralControl)row.Cells[i].Controls[0] as DataBoundLiteralControl).Text;\n             }\n             else if (row.Cells[i].Controls[0].GetType().Equals(typeof(TextBox)))\n             {\n                 TempRow[i] = ((TextBox)row.Cells[i].Controls[0]).Text;\n             }\n         }\n         TempTable.Rows.Add(TempRow);\n    }\n    return TempTable;\n}	0
24557782	24557437	How can I use several Application Configuration Files in one project?	ExeConfigurationFileMap configFileMap = \n        new ExeConfigurationFileMap();\n    configFileMap.ExeConfigFilename = "App4.config"; // full path to the config file\n\n    // Get the mapped configuration file\n   Config config = \n      ConfigurationManager.OpenMappedExeConfiguration( \n        configFileMap, ConfigurationUserLevel.None);\n\n   //now on use config object\n\nAppSettingsSection section = (AppSettingsSection)config.GetSection("appSettings");	0
9733444	9733414	usage of global variable on C#	static double moneyamount = 0;\nstatic void SelectProduct() {\n    moneyamount = 0;\n\n    int selection = int.Parse(Console.ReadLine());\n    if (selection == 1) {\n        moneyamount = 1.50;       \n    }\n\n    else {\n        Console.WriteLine("Wrong Selection");\n    }\n\n    Console.WriteLine("Your drink costs $" + moneyamount);\n    InsertCoin();\n}\nstatic void InsertCoin() {\n\n    Console.WriteLine("Balance of cost $" + moneyamount);\n}	0
27029690	27026829	How to create a ContactsService using Google Contact API v3 with OAuth v2 UserCredentials	var token = new FileDataStore("Google.Apis.Auth")\n    .GetAsync<TokenResponse>("user");\nvar accessToken = token.AccessToken; // valid for 60 minutes ONLY.\nvar refreshToken = token.RefreshToken;	0
17297904	17297828	How to convert number to string in Linq to Entities without pulling into local object	SqlFunctions.StringConvert(double)	0
5374318	5374130	Float array to Image	Bitmap newBitmap = new Bitmap(original.Width, original.Height);\n\n        for (int j = 0; j < original.Height; j++)\n        {\n            for (int i = 0; i < original.Width; i++)\n            {\n                Color newColor = Color.FromArgb((int)grayScale[i + j * original.Width], (int)grayScale[i + j * original.Width], (int)grayScale[i + j * original.Width]);\n\n                newBitmap.SetPixel(i, j, newColor);\n            }\n        }\n\n        Image img = (Image)newBitmap;	0
14783371	14725328	Draw border for NumericUpDown	public class NumericUpDownEx : NumericUpDown\n{\n    bool isValid = true;\n    int[] validValues = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9 };\n\n    protected override void OnPaint(PaintEventArgs e)\n    {\n        base.OnPaint(e);\n\n        if (!isValid)\n        {\n            ControlPaint.DrawBorder(e.Graphics, this.ClientRectangle, Color.Red, ButtonBorderStyle.Solid);\n        }\n    }\n\n    protected override void OnValueChanged(System.EventArgs e)\n    {\n        base.OnValueChanged(e);\n\n        isValid = validValues.Contains((int)this.Value);\n        this.Invalidate();\n    }\n}	0
15089429	15089362	C# call method (params object[][]) with object[] and object[][] as parameters	object[][] args = new[] { var1 }.Concat(var2).ToArray();\nmethod(args);	0
22093961	22093731	Trying to create a grid of pictureboxes in an array for a board in c#	PictureBox[,] pb = new PictureBox[3, 3];\n            for (int i = 0; i < 3; i++)\n            {\n                for (int j = 0; j < 3; j++)\n                {\n                    pb[i,j] = new PictureBox();\n                    pb[i, j].Location = new Point(i * 150 + 100, j * 150 + 100);\n                    pb[i, j].Width = 150;\n                    pb[i, j].Height = 150;\n                    pb[i, j].Visible = true;\n                    pb[i, j].BorderStyle = BorderStyle.FixedSingle;\n                    pb[i, j].BringToFront();\n                    this.Controls.Add(pb[i, j]);\n                }\n            }	0
12560654	12560574	To insert a new item into a ListBox and placed it as the first entry and get it selected	ListBoxVenue.Items.Insert(0, new ListItem("","{BLANK}"));\nListBoxVenue.SelectedIndex = 0;	0
19132088	19121636	Adding links to pdf by using MigraDoc	var h = paragraph.AddHyperlink("http://stackoverflow.com/",HyperlinkType.Web);\n    h.AddFormattedText("http://www.stackoverflow.com/");	0
8656036	8656015	Removing one items from an array and moving the others backwards	string[] fruits = { "Banana", "Apple", "Watermelon", "Pear", "Mango" };\n\n  fruits = fruits.Where(f => f != "Apple").ToArray();	0
18329054	18314929	when we serialize serializable object using JSON.Net, JSON string is different from DatacontractJSON serializer	#if !(SILVERLIGHT || NETFX_CORE || PORTABLE || PORTABLE40)\n    IgnoreSerializableAttribute = true;\n#endif	0
4465530	4465504	Loading of Master pages dynamically?	protected override void OnPreInit(EventArgs e)\n{\n    base.OnPreInit(e);\n    this.Page.MasterPageFile = "~/AlternateMasterPage.master";\n}	0
3634286	3634214	Implement VB With statement in C#	new FooBar().With( fb=> {\n    fb.Foo = 10;\n    fb.Bar = fb.Foo.ToString();\n} );\n\n// ... somewhere else ...\npublic static void With<T>( this T target, Action<T> action ) {\n    action( target );\n}	0
25890766	25890272	WPF Converter Enum to Array	public enum myEnum\n{\n    One,\n    Two,\n    Four,\n    Eight\n}\n\npublic partial class MainWindow : Window\n{\n    private IEnumerable<string> _enumValues;\n    public MainWindow()\n    {\n        InitializeComponent();\n\n        _enumValues = ConvertEnumToStrings<myEnum>();\n\n        enumCombo.ItemsSource = _enumValues;\n    }\n\n    private static IEnumerable<string> ConvertEnumToStrings<T>()\n    {\n        var enumValues = Enum.GetValues(typeof(T))\n            .Cast<T>()\n            .Select(x => x.ToString())\n            .OrderBy(x => x)\n            .ToArray();\n\n        return enumValues;\n    }\n}	0
15744189	15743798	Using a C# DataGridView to update SQL tables?	int id; \nstring name;\nstring address;  \n\nfor (int i = 0; i <= adminDataGrid.Rows.Count-1; i++)\n{\n    id = int.Parse(adminDataGrid.Rows[i].Cells["ID"].Value);\n    name = adminDataGrid.Rows[i].Cells["NAME"].Value.ToString();\n    address = adminDataGrid.Rows[i].Cells["Address"].Value.ToString();\n// now write the C# code to update your table using id, name and address. in first cycle of the for loop the table will update with first row data of your adminDataGrid. \n}	0
32679237	32678478	Copy a 3-dim array into an 11x3-dim array C#	Buffer.BlockCopy(temprate, 0, RATES, i * 3 * sizeof(double), 3 * sizeof(double));	0
24302382	24302076	Unable to find table after successfully connecting to database file	connectionString = "DataSource=C:\\some\\where\\myDataBase.db";	0
3543046	3542705	Adding a line to a textblock programatically	var t = new TextBlock();\n        t.Inlines.Add(new Line { X1 = 0, Y1 = 0, X2 = 100, Y2 = 0, Stroke = new SolidColorBrush(Colors.Black), StrokeThickness = 4.0 });\n        t.Inlines.Add("Hello there!");\n        t.Inlines.Add(new Line { X1 = 0, Y1 = 0, X2 = 100, Y2 = 0, Stroke =  new SolidColorBrush(Colors.Black),StrokeThickness = 4.0});\n        LayoutRoot.Children.Add(t);	0
6628866	6628599	Using <ItemTemplate> with Checkbox and Label	var values = myDbConnection.GetValues();\nvar listOfValues = values.Select(x => new ListItem(x.Name, x.Value)).ToList(); // something like that\nlistOfValues.Add(new ListItem("All Profiles"));\n\nmyCombo.DataSource = listOfValues;\nmyCombo.DataBind();	0
3690425	3684498	How do I force a relative URI to use https?	// Get the executing XAP Uri\n    var appUri = App.Current.Host.Source;\n\n    // Remove the XAP filename\n    var appPath = appUri.AbsolutePath.Substring(0, appUri.AbsolutePath.LastIndexOf('/'));\n\n    // Construct the required absolute path\n    var rootPath = string.Format("https://{0}{1}", appUri.DnsSafeHost, appUri.AbsolutePath);\n\n    // Make the relative target Uri absolute (relative to the target Uri)\n    var uri = new Uri(new Uri(rootPath), "../Services/Authenticated/VariationsService.svc");	0
10226723	10223608	How to post HTML form from server side?	NameValueCollection data = new NameValueCollection();\ndata["input-data1"] = "value1";\ndata["input-data2"] = "value2";\ndata["input-data3"] = "value3";\n\nWebClient webClient = new WebClient();\nwebClient.Credentials = new NetworkCredential(mylogin, mypassword);\nbyte[] responseBytes = webClient.UploadValues("http://www.site.com/posttome.aspx", "POST", formData);\nstring response = Encoding.UTF8.GetString(responseBytes);	0
12390076	12389725	Table not update with new data	I have refatored your code, now it should work\n\nprotected void Button3_Click(object sender, EventArgs e){\nSqlConnection conn = new   SqlConnection(ConfigurationManager.ConnectionStrings["Connection"].ConnectionString);\nSqlCommand cmd = new SqlCommand("UPDATE aspnet_membership SET Email = @email WHERE UserName = @id1", conn);\n\ncmd.Connection = conn;\ncmd.CommandType = CommandType.Text;\ncmd.Parameters.AddWithValue("@email", TextBox2.Text);\ncmd.Parameters.AddWithValue("@id1", TextBox3.Text);   \n try { \nconn.Open();\ncmd.ExecuteNonQuery();\n\n   }\n  catch(Exception ex){ \n  throw ex;    \n  }\nfinally{    \nconn.Close();\n   }\n }	0
26483400	26480288	DataGridView Multiple Selected Columns get both row data	foreach (DataGridViewRow row in RGV.Rows)\n    {\n        foreach (DataGridViewCell cell in row.Cells)\n        {\n            row.Cells["Status"].Value = "Check";\n            if (RGV.SelectedColumns.Contains(cell.OwningColumn))\n            { \n                row.Cells["Status"].Value = "OK";\n                break; \n            }\n        }\n    }	0
2397674	2397659	create a dictionary or list from string(HTML tag included) in C#	var doc = new HtmlDocument();\ndoc.LoadHtml(s);\nvar dict = doc.DocumentNode.Descendants("tr")\n              .ToDictionary(\n                  tr => int.Parse(tr.Descendants("td").First().InnerText),\n                  tr => int.Parse(tr.Descendants("td").Last().InnerText)\n              );	0
2624668	2624630	Referencing an ASP control within a LoginView	HyperLink hypLink1 = (HyperLink)LoginView1.FindControls("hypLink1");	0
7213004	7212969	Work with xml in c#	StringWriter sw = new StringWriter();\nXmlSerializer ser = new XmlSerializer(typeof(Nothing));\nser.Serialize(sw, new Nothing(){AStringInNothing = "asd"});\nsw.ToString();\nvar whatYouWant = XElement.Parse(sw.ToString());	0
8185457	8168975	Unobvious array indexing	int sectionSize = 16;\n\nString usedAlphabet = "x3w4tnu34urgbgierg";\nbyte sectionIndex = // (something initialized earlier)\n\nint alphabetIndex = sectionIndex / sectionSize;\nreturn usedAlphabet[alphabetIndex]; // not so puzzling anymore	0
791739	791734	Fill combobox with english months	var americanCulture = new CultureInfo("en-US");\ncomboMonth.Items.AddRange(americanCulture.DateTimeFormat.MonthNames.Take(12)); //to remove last empty element	0
12245452	12245377	C# Elegant method to derive DataRow subset using key column array	PKeys.Select(key => Row[key].ToString()).ToList()	0
14515665	14515353	How to use function D3DXSaveSurfaceToFile() in C#	try\n{\n\n// initialize D3D device \nPresentParameters presentParams = new PresentParameters();\npresentParams.Windowed = true;\npresentParams.SwapEffect = SwapEffect.Discard;\nDevice myDevice = new\nDevice(0,DeviceType.Hardware,this,CreateFlags.SoftwareVertexProcessing,presentParams);\n\n// create a surface the size of screen, \n// format had to be A8R8G8B8, as the GetFrontBufferData returns\n// only memory pool types allowed are Pool.Scratch or Pool.System memory\nSurface mySurface =\nmyDevice.CreateOffscreenPlainSurface(SystemInformation.PrimaryMonitorSize.Width,SystemInformation.PrimaryMonitorSize.Height,Format.A8R8G8B8,Pool.SystemMemory);\n\n//Get the front buffer.\nmyDevice.GetFrontBufferData(0,mySurface);\n\n//saves surface to file\nSurfaceLoader.Save("surface.bmp",ImageFileFormat.Bmp,mySurface);\n\n}\ncatch\n{\n   //whatever\n}	0
23562109	23561962	Can I combine a foreach and a LINQ query into one?	var auditableTables = this.ChangeTracker.Entries()\n                                        .Where(e => e.State == EntityState.Added)\n                                        .Select(e => e.Entity)\n                                        .OfType<IAuditableTable>();\n\nforeach (var table in auditableTables)\n{\n    table.ModifiedDate = DateTime.Now;\n}	0
1877814	1877788	Javascript date to C# via Ajax	DateTime dt = DateTime.ParseExact("Wed Dec 16 00:00:00 UTC-0400 2009",\n                                  "ddd MMM d HH:mm:ss UTCzzzzz yyyy",\n                                  CultureInfo.InvariantCulture);	0
4088671	4088619	C# regex help - validating input	private static readonly Regex _validator = \n    new Regex(@"^\d{4}-\d{5}-\d{4}-\d{3}$", RegexOptions.Compiled);\nprivate static bool ValidateInput(string input)\n{\n    input = (input ?? string.Empty);\n    if (input.Length != 19)\n    {\n        return false;\n    }\n    return _validator.IsMatch(input);\n}	0
13342113	13341630	Install Profile Service - Profile Installation Failed (Get UDID from iOS)	context.Response.Status = "301 Moved Permanently";\n        context.Response.AddHeader("Location", "/device/enroll.aspx");\n        context.Response.End();	0
24976295	18599002	How to properly set the path for executing a child powershell script?	[System.Reflection.Assembly]::LoadFrom((Join-Path (pwd) "MyAssembly.dll")) | out-null	0
984890	984882	Changing Button Attributes in C#	if ( textBox1.Text == "password") {\n  button1.Visible = true;\n  button2.Visible = true;\n}	0
28446485	28446374	Open .sql file SQL Server Management Studio from a folder throught C# with a specfic server name	Process.Start("ssms.exe", "-S (local)\\sqlexpress -E C:\\SQLQuery1.sql");	0
16661563	16654156	Get a specific sized rectangle from a form	int posX = 0; // area position\nint posY = 0;\nint w = 200;  // area size\nint h = 100;\n\n//pull the picture from the buffer \nint[] backBuffer = new int[w * h];\nGraphicsDevice.GetBackBufferData(new Rectangle(posX, posY, w, h), backBuffer, 0, w*h );\n\n//copy into a texture \nTexture2D texture = new Texture2D(GraphicsDevice, w, h, true, GraphicsDevice.PresentationParameters.BackBufferFormat);\ntexture.SetData(backBuffer);	0
1801923	1801905	how to fetch data from nested Dictionary in c#	foreach(var key1 in dc.Keys)\n{\n    Console.WriteLine(key1);\n    var value1 = dc[key1];\n    foreach(var key2 in value1.Keys)\n    {\n        Console.WriteLine("    {0}, {1}", key2, value1[key2]);\n    }\n}	0
6995746	6995549	Keeping a C# Mutex Alive in a Windows Service	Mutex sessMutex = new Mutex(false, "sessMutex");\nsessMutex.WaitOne();\n// Write to the file ...... \nsessMutex.ReleaseMutex();	0
372822	372812	How do get some of the object from a list without Linq?	static void Main()\n    {\n        List<SimpleObject> list = new List<SimpleObject>();\n        list.Add(new SimpleObject(1,"Jon"));\n        list.Add(new SimpleObject( 2,  "Mr Skeet" ));\n        list.Add(new SimpleObject( 3,"Miss Skeet" ));\n        Predicate<SimpleObject> yourFilterCriteria = delegate(SimpleObject simpleObject)\n        {\n            return simpleObject.Name.Contains("Skeet");\n        };\n        list = list.FindAll(yourFilterCriteria);//Get only name that has Skeet : Here is the magic\n        foreach (SimpleObject o in list)\n        {\n            Console.WriteLine(o);\n        }\n        Console.Read();\n    }\n    public class SimpleObject\n    {\n        public int Id;\n        public string Name;\n\n        public SimpleObject(int id, string name)\n        {\n            this.Id=id;\n            this.Name=name;\n        }\n\n        public override string ToString()\n        {\n            return string.Format("{0} : {1}",Id, Name);\n        }\n    }	0
7585489	7557565	Project asking for a config setting that's there already	using (var client = new WCFServiceChannelFactory<IFxCurveService>(new Uri("http://ksqcoreapp64int:5025/")))	0
12475857	12475683	Unable to add user controls to a panel dynamically	mr[i].Dock = DockStyle.Top;	0
27926200	27925723	C# format float to string with separators and padding 0	NumberFormatInfo numberFormat = new NumberFormatInfo\n{\n    NumberDecimalSeparator=",",\n    NumberGroupSeparator="."\n};\n\nstring formatFloat(float f)\n{\n    return f.ToString("0####,0.00",numberFormat);\n}\n\nstring formatInt(int i)\n{\n    return i.ToString("0####,0",numberFormat);\n}	0
17796999	17796526	Thruster effect using particle engine	public void Update()\n    {\n        TTL--;\n        Position += Velocity + 1;//or other value...test it!\n        Angle += AngularVelocity;\n    }	0
12822026	12821998	How to generate a UTC Unix Timestamp in C#	private double ConvertToTimestamp(DateTime value)\n{\n    //create Timespan by subtracting the value provided from\n    //the Unix Epoch\n    TimeSpan span = (value - new DateTime(1970, 1, 1, 0, 0, 0, 0).ToLocalTime());\n\n    //return the total seconds (which is a UNIX timestamp)\n    return (double)span.TotalSeconds;\n}	0
370395	370291	Serializing without XmlInclude	public XmlSerializer(\n   Type type,\n   Type[] extraTypes\n);	0
33424997	33285866	Unity webGL for Facebook - Failed to find parameter 'grantedScopes' in login result	void Start(){\n    if(!FB.IsInitialized){\n        FB.Init(OnInit)\n    } else {\n        OnInit()\n    }\n}\n\nvoid OnInit(){\n    if(!FB.IsInitialized) Debug.LogError("Failed to Initialize");\n\n    if(!FB.IsLoggedIn){\n        FB.LogInWithReadPermissions(mPermissions, AuthCallback);\n    } else {\n        OnFBConnected();\n    }\n}\n\nvoid AuthCallback(ILoginResult r)\n{\n    if (!string.IsNullOrEmpty(r.Error))\n    {\n        Debug.LogError("OnFBConnected: failed");\n        return;\n    }\n\n    if (FB.IsLoggedIn)\n    {\n        OnFBConnected();\n    }\n    else\n    {\n        Debug.LogWarning("User cancelled facebook login.");\n    }\n}\n\nvoid OnFBConnected(){\n    //Do whatever you need with the AccessToken you have\n}	0
26239309	26222443	How to initialize a large Seed efficiently with EF Code First?	foreach (string file in files)\n            {\n                var fileInfo = new FileInfo(file);\n\n                Console.WriteLine("Running script {0}", fileInfo.Name);\n\n                string text = fileInfo.OpenText().ReadToEnd();\n\n                using (var conn = new SqlConnection(connectionString))\n                {\n                    using (var cmd = new SqlCommand(text, conn))\n                    {\n                        conn.Open();\n\n                        await cmd.ExecuteNonQueryAsync();\n                    }\n                }\n            }	0
9382572	9367963	C# create a browse for file property for a custom control	private Icon IconLocation;\npublic Icon CustomIcon\n{\n    get\n    {\n        return IconLocation;\n    }\n    set\n    {\n        IconLocation = value;\n    }\n}	0
25631961	25631863	Unity 2D Raycasting from a Rotating Transform	Vector2 direction = transform.TransformDirection(angle);\nif (transform.localScale.x < 0f) {\n    direction.x = -direction.x;\n}\n\nRaycastHit2D tile_hit = Physics2D.Raycast(position, direction, 10);	0
8047271	8039411	Modify values before inserting through an EntityDataSource Object	protected void EntityDataSource_Inserting(object sender, EntityDataSourceChangingEventArgs e)\n{\nmyDatasetObject newElement = e.Entity as myDatasetObject;\nnewElement.id = NextPrimaryID();\n}	0
27048253	27047000	How can I perform additional object configuration via parameter?	private Locate Build(Func<IPostprocessComposer<Locate>, IPostprocessComposer<Locate>> action)\n    {\n        var customizationComposer = _fixture.Build<Locate>();\n        var postProcessComposer = customizationComposer\n            .With(x => x.TicketNo, DateTime.Now.ToFileTime())\n            .With(x => x.On1CallNotified, false)\n            .Without(x => x.Attachments)\n            .Without(x => x.Comments)\n            .Without(x => x.Reviews)\n            .Without(x => x.ScheduledCrew)\n            .Without(x => x.PendingDecision)\n            .Without(x => x.FinalDecision)\n            .Without(x => x.ConflictResolution);\n\n        postProcessComposer = action(postProcessComposer);\n\n        return postProcessComposer.Create();\n    }	0
34130581	34130386	Read file with partially unknown filename	var pathToSearch = @"\\myServer1\files\";\n  var knownPart = string.Format("FOO_{0:yyyymmdd}_", DateTime.Now);\n\n  var files = Directory\n    .EnumerateFiles(pathToSearch, knownPart + "??????.txt")\n    .Where(file => Regex.IsMatch(\n      Path.GetFileNameWithoutExtension(file).Substring(knownPart.Length),\n      "^(([0-1][0-9])|(2[0-3]))([0-5][0-9]){2}$"))\n    .ToArray();\n\n  if (files.Length <= 0) {\n    // No such files are found\n    // Probably, you want to throw an exception here\n  }\n  else if (files.Length > 1) {\n    // Too many such files are found\n    // Throw an exception or select the right file from "files"\n  }\n  else {\n    // There's one file only\n    var fileName = files[0];\n    ...\n  }	0
19722529	19722478	Replace row values in a Dataset using LINQ	var rowsToUpdate = from r in oT2.AsEnumerable()\n                   let data = r.Field<string>("Data")\n                   where data != null && \n                         (data.Contains("<<") || data.Contains(">>"))\n                   select r;\n\nforeach (var row in rowsToUpdate)\n    row.SetField("Data", row.Field<string>("Data")\n                            .Replace("<<", "&#60").Replace(">>", "&#62"));	0
3055772	3055742	Regex to remove all (non numeric OR period)	string s = "joe ($3,004.50)";\ns = Regex.Replace(s, "[^0-9.]", "");	0
12972852	12972815	c# splitting an array and displaying it in descending order in a textbox	int[] newOne = arrText.Select(x => int.Parse(x)).OrderByDescending(x => x).ToArray();	0
15920809	15920741	Convert from string ascii to string Hex	string str = "1234";\nchar[] charValues = str.ToCharArray();\nstring hexOutput="";\nforeach (char _eachChar in charValues )\n{\n    // Get the integral value of the character.\n    int value = Convert.ToInt32(_eachChar);\n    // Convert the decimal value to a hexadecimal value in string form.\n    hexOutput += String.Format("{0:X}", value);\n    // to make output as your eg \n    //  hexOutput +=" "+ String.Format("{0:X}", value);\n\n}\n\n    //here is the HEX hexOutput \n    //use hexOutput	0
24131656	18746064	Using Reflection to create a DataTable from a Class?	public static DataTable CreateDataTable<T>(IEnumerable<T> list)\n{\n    Type type = typeof(T);\n    var properties = type.GetProperties();      \n\n    DataTable dataTable = new DataTable();\n    foreach (PropertyInfo info in properties)\n    {\n        dataTable.Columns.Add(new DataColumn(info.Name, Nullable.GetUnderlyingType(info.PropertyType) ?? info.PropertyType));\n    }\n\n    foreach (T entity in list)\n    {\n        object[] values = new object[properties.Length];\n        for (int i = 0; i < properties.Length; i++)\n        {\n            values[i] = properties[i].GetValue(entity);\n        }\n\n        dataTable.Rows.Add(values);\n    }\n\n    return dataTable;\n}	0
25807663	25807138	Can I add a hyperlink to my shape to close the current powerpoint presentation in C#	shape.ActionSettings[PowerPoint.PpMouseActivation.ppMouseClick].Action = PowerPoint.PpActionType.ppActionEndShow;	0
9774414	9761499	C# with MySQL through Connector/NET	public static string ConnectionString {get;set;}\n\npublic static bool InsertRecord(sql)\n{\n    bool success = false;\n    using (var con = new Connection(ConnectionString)){\n        var command = new SqlCommand(sql,con);\n        success = (command.ExecuteNonQuery() > 0);\n    }\n    return success;\n}	0
24363521	24363169	Trying to return the names of people within a winForm listbox	Person_List people = new Person_List();\n\nprivate void addPerson_Click(object sender, EventArgs e)\n{\n    string name = addName.Text;\n\n    int age = Convert.ToInt32(addAge.Text);\n\n    people.addPersonToList(name, age);\n}	0
2000190	2000125	How do I make a webpart's settings configurable in Sharepoint?	[WebBrowsable(true),Category("Calendar Setup"),\n WebDisplayName("Starting Date Column"),\n WebDescription("column that contains item starting date"),\n Personalizable(PersonalizationScope.Shared)]\npublic DateTime StartDate { get; set; }	0
8992010	8991638	How to load a root object and it's child entities based on IsDeleted = true using EntityFramework	EntityHavingClause.IsDeleted	0
13547329	13547025	Combinations of 4 points from 2 arrays of points	function combinations(array1, count1, array2, count2)\n{\n    var result = [];\n    combine(array1, 0, count1, array2, 0, count2, [], result);\n    return result;\n}\n\nfunction combine(array1, offset1, count1, array2, offset2, count2, chosen, result)\n{\n    var i;\n    var temp;\n    if (count1) {\n        count1--;\n        for (i = offset1; i < array1.length - count1; i++) {\n            temp = chosen.concat([array1[i]]); // this copies the array and appends the item\n            combine(array1, i + 1, count1, array2, offset2, count2, temp, result);\n        }\n    } else if (count2) {\n        count2--;\n        for (i = offset2; i < array2.length - count2; i++) {\n            temp = chosen.concat([array2[i]]);\n            combine(null, 0, 0, array2, i, count2, temp, result);\n        }\n    } else {\n        result.push(chosen); // don't need to copy here, just accumulate results\n    }\n}	0
16097940	16097140	zip files with same names but different exensions using Ioniz.Zip DLL	string path = @"d:\test";\n\n //First find all the unique file name i.e. ABC123 & XYZ456 as per your example                \n List<string> uniqueFiles=new List<string>();\n foreach (string file in Directory.GetFiles(path))\n {\n     if (!uniqueFiles.Contains(Path.GetFileNameWithoutExtension(file)))\n         uniqueFiles.Add(Path.GetFileNameWithoutExtension(file));\n }\n\n foreach (string file in uniqueFiles)\n {\n      string[] filesToBeZipped = Directory.GetFiles(@"d:\test",string.Format("{0}.*",file));\n\n      //Zip all the files in filesToBeZipped \n }	0
4189750	4189739	DateTime TryParse problem	string date = txtWorkingDate.Text;\nDateTime dateTime;\nstring[] formats = new[] { "dd.MM.yyyy", "MM/dd/yyyy" };\nif (DateTime.TryParseExact(date, formats, CultureInfo.InvariantCulture, DateTimeStyles.None, out dateTime))\n{\n    args.IsValid = true;\n}\nelse\n{\n    args.IsValid = false;\n}	0
34139179	34139044	Adding values to a dictionary that its values are	var outerKey = "Some Outer Key";\nvar innerKey = "Some Inner Key";\nvar myValue = "Some Value";\n\nif (!myDictionary.ContainsKey(outerKey))\n{\n    myDictionary.Add(outerKey, new Dictionary<string, List<string>>());\n}\n\nif (!myDictionary[outerKey].ContainsKey(innerKey))\n{\n    myDictionary[outerKey].Add(innerKey, new List<string>());\n}\n\nmyDictionary[outerKey][innerKey].Add(myValue);	0
4582786	4582380	C# DataSet, DataAdapter -- How to change row state to invoke an INSERT?	row.AcceptChanges(); // sets DataRowState.Unchanged\nrow.SetAdded();	0
22281002	22280633	Bitmap constructor with scan0 and unmanaged resources	unsafe\n{\n    byte stlThres = 115;\n    Bitmap myBmp = ...; // init the bitmap \n    var data = myBmp.LockBits(new Rectangle(0, 0, myBmp.Width, myBmp.Height), ImageLockMode.WriteOnly, myBmp.PixelFormat);\n    for (int y = 0; y < data.Height; y++)\n    {\n        byte* row = (byte*)data.Scan0 + (y * data.Stride);\n        //...\n}	0
16530536	16530472	How can i resize an image?	ResizeImage(bmp, new Size(150, 150));	0
26889699	25282440	Combine two condition from two table with OR clause in orchard HQL query	Action<IAliasFactory> productPartRecordAlias = x => x.ContentPartRecord<ProductPartRecord>().Named("productPartRecord");\nAction<IAliasFactory> titlePartRecordAlias = x => x.ContentPartRecord<TitlePartRecord>().Named("titlePartRecord");\n\nvar query = _contentManager.HqlQuery()\n    .Join(productPartRecordAlias)\n    .Join(titlePartRecordAlias)\n    .Where(a => a.ContentItem(), p => p.Gt("Id", "0 AND (productPartRecord.Price = 1000 OR titlePartRecord.Title = 'myTitle')"));	0
3538909	3538842	C# - Pushing Enter in MessageBox triggers control KeyUp Event	private void textBox1_KeyDown(object sender, KeyEventArgs e) {\n        if (e.KeyData == Keys.Enter) {\n            button1.PerformClick();\n            e.SuppressKeyPress = true;\n        }\n    }	0
15894107	15893964	Fill ComboBox inside a DataGridView with two Different Tables in C#?	dtOne.Merge(dtSecond);\ncnsmNm.DataSource = dtOne;	0
16222765	16222601	How to define a "List" of derived classes?	List<Type> types = new List<Type> { typeof(A), typeof(B), typeof(C) };\n\nA instance = (A)Activator.CreateInstance(types[r.Next(0, types.Count)]);	0
7446980	7446779	Can I pass a C# array to a C pointer via a C++/CLI wrapper?	int Class1::FXForwardRateW(array<int>^ premium, double %fwdRate)\n{\n     double tempFwdRate = fwdRate;\n     pin_ptr<int> premiumPtr = &premium[0];\n     int status = FXForwardRate(premiumPtr, &tempFwdRate);\n     fwdRate = tempFwdRate;\n     return status;\n}	0
3369744	3369715	Programmatically generated image doesnt have a CanvasLeft	Canvas.SetLeft(newItem, 10d);	0
27754873	27754744	Building a linq expression with only field names	if (tableName == "Jobs") query = query.Where(...)	0
10695164	10694223	Setting multiple DataContexts in WPF C#	class VM \n{\n  private IVMImplementation manager = null;\n\n  public VM(IVMImplementation manager) { this.manager = manager; }\n\n  public SetManager(IVMImplementation manager) { this.manager = manager; }\n}\nclass TwitterVMManager : IVMImplementation  {}\nclass FacebookVMManager : IVMImplementation  {}	0
10630281	10630223	Try/Catch/Finally, use exception from Catch in Finally?	try {\n  try { //something }\n  finally {\n      DoSomething();        \n  }\n   ... //more code\n}\nfinally {\n  // cleanup code\n}	0
3571548	3571513	How do get a strongly typed single value using LINQ	var OneRunner = (\n  from f in RunnerDataTable.AsEnumerable()\n  where f.Field<string>("FirstName") == "Jordan"\n  select new\n    {\n       FirstName = f.Field<string>("FirstName"),\n       LastName = f.Field<string>("LastName")\n    }\n ).Single();	0
29157637	29157357	Not searching for view in Areas folder	public class EventAreaRegistration : AreaRegistration \n{\n    public override string AreaName\n    {\n        get\n        {\n            return "Event";\n        }\n    }\n\n    public override void RegisterArea(AreaRegistrationContext context)\n    {\n        context.MapRoute(\n            "Event_default",\n            "{locale}/Event/{action}/{id}",\n            new { controller = "Event", action = "Index", id = UrlParameter.Optional },\n            namespaces: new[] { "ProjectName.Areas.Event.Controllers" }\n        );\n    }\n}	0
30091400	30075163	Mapping a string Array to an Object using ValueInjecter	KnownSourceValueInjection<string[]>	0
5546737	5546704	removing readonly from folder, its sub folders and all the files in it	var di = new DirectoryInfo("C:\\Work");\n\nforeach (var file in di.GetFiles("*", SearchOption.AllDirectories)) \n    file.Attributes &= ~FileAttributes.ReadOnly;	0
31813589	31813475	how to convert escaped c# string with double quotes to escaped javascript string with double quotes	test(@Html.Raw(JsonConvert.Serialize(lol)));	0
21644814	21643805	Unity3d - Coroutine in For Loop	public IEnumerator DelayInstantiate()\n{\n  for (int i = 0; i <= 3; i++)\n  {\n     Instantiate(gameObject, objectSpawn[i].transform.position, Quaternion.identity);\n     StartCoroutine(WeaponsCooldown(6)); //or do what you want\n\n     yield return new WaitForSeconds(0.5f);\n  }\n}	0
27779242	27779196	Add new line when printing C# string array	myString += Environment.NewLine;	0
23732742	23732587	Cannot access a closed stream while sending attachment	using(var ms = new System.IO.MemoryStream())\n    {\n      using(var writer = new System.IO.StreamWriter(ms))\n      {\n         writer.Write("Hello its my sample file");\n         writer.Flush();\n\n         System.Net.Mime.ContentType ct = new System.Net.Mime.ContentType(System.Net.Mime.MediaTypeNames.Text.Plain);\n         System.Net.Mail.Attachment attach = new System.Net.Mail.Attachment(ms, ct);\n         attach.ContentDisposition.FileName = "myFile.txt";\n\n         mm.Attachments.Add(attach);\n         try\n         {\n             client.Send(mm);\n         }\n         catch(SmtpException e)\n         {\n            Console.WriteLine(e.ToString());\n         }\n       }\n    }	0
13571469	13571400	1E-08 to decimal	decimal x = decimal.Parse("1E-08", NumberStyles.Float);	0
10229280	10229081	Dynamic / run-time loading of Assembly C from A where both C and A reference B	//Since we'll be dynamically loading assemblies at runtime, we need to add an appropriate resolution path\n    //Otherwise weird things like failing to instantiate TypeConverters will happen\n    AppDomain.CurrentDomain.AssemblyResolve += CurrentDomain_AssemblyResolve;\n\nprivate Assembly CurrentDomain_AssemblyResolve(object sender, ResolveEventArgs args)\n{\n    var domain = (AppDomain)sender;\n\n    foreach (var assembly in domain.GetAssemblies())\n    {\n        if (assembly.FullName == args.Name)\n            return assembly;\n    }\n\n    return null;\n}	0
5858249	5857708	C# Loop round a Range.Value which has 2 objects [0,0] to find if string = variable	object[,] rng = (object[,])range.Value;\n\n    for (int row = rng.GetLowerBound(0); row <= rng.GetUpperBound(0); row++)\n    {\n        for (int day = rng.GetLowerBound(1); day <= rng.GetUpperBound(1); day++)\n        {\n            string dayName = rng[row,day] as string;\n        }\n    }	0
253098	252897	Using regini from a c# app without bothering the user?	pi.CreateNoWindow = true;	0
10637456	10619783	Using a JsonRequest to grab TeamCity User names: Internal	var change = Client.LastChangeDetailByBuildConfigId(buildConfig.Id); // Provides the changeID\n                    var changeDetail = Client.ChangeDetailsByChangeId(change.Id); // Provides the username, this one populates the usernames	0
26731948	26729408	Access a Shared Screen through BEQSRequest	Request request = service.CreateRequest("BeqsRequest");\n            request.Set("screenName", "My Screen Name");\n            request.Set("screenType", "PRIVATE");	0
7838267	7837230	Silent save without prompting in Revit API	Document.Save	0
2329344	2329265	how to write this into linq to object query?	var groups = list.GroupBy(s => s.Attribute1);\nvar recur_1 = groups.Where(g => g.Count() == 1).SelectMany(s => s);\nvar recur_2 = groups.Where(g => g.Count() == 2).SelectMany(s => s);\nvar recur_3 = groups.Where(g => g.Count() == 3).SelectMany(s => s);	0
26804736	26804607	C# regex Split capture preceding characters	(?=..;(?:CR  |PERS|EFFE);)	0
16030587	16030476	read xml attributes	XDocument doc = XDocument.Load(@"e:\input\partylist.xml");\nforeach (var partyList in doc.Descendants("party"))\n{\n   string currency= partyList .Attribute("currency").Value;\n   string id= partyList .Attribute("id").Value;\n}	0
27221652	27214958	How to set column length and type	DataSet dataSet = new DataSet();\n\nDataTable customTable = new DataTable();\nDataColumn dcName = new DataColumn("Name", typeof(string));\ndcName.MaxLength= 500;\ncustomTable.Columns.Add(dcName);\n\ndataSet.Tables.Add(customTable);	0
5270954	5270104	Saving SPFile to local hard disk	int size = 10 * 1024;\nusing (Stream stream = file.OpenBinaryStream())\n{\n  using (FileStream fs = new FileStream(@"C:\Users\krg\Desktop\xyz.pptx", FileMode.Create, FileAccess.Write))\n  {\n    byte[] buffer = new byte[size];\n    int bytesRead;\n    while((bytesRead = stream.Read(buffer, 0, buffer.Length)) > 0)\n    {\n      fs.Write(buffer, 0, bytesRead);\n    }\n  }\n}	0
25076723	25076702	Cast object type in a LINQ statement	var item = Layers.FirstOfDefault(x => ((PushPin)x.Content).Description == "xyz");	0
14072461	14071718	Most efficient way to query a database and then remove entries from returned items	var followedIDs = user.followBloggers.Select(follow => follow.PersonID);\nreturn Uow.People.GetPeople().Where(p => !followedIDs.Contains(p.PersonID));	0
28630320	28629220	Importing files to database with folders as categories ASP.NET C#	var ff = Directory.GetFiles(fileImportFolder, "*", SearchOption.AllDirectories);\nforeach (var f in ff)\n{\n    // f is a full path of the file\n    Response.Write(f.ToString());\n\n    // use FileInfo to get specific attributes   \n    var i = new FileInfo(f);\n    Response.Write("SubCategoryId=" + i.Directory.Name);\n    Response.Write("CategoryId=" + i.Directory.Parent.Name);\n    Response.Write("UpdateDate=" + i.LastWriteTime.ToString());\n    ...\n}	0
12668501	12668391	Getting last element of an xml file	var xDoc = XDocument.Load("logins.xml");\n\nvar userElements = xDoc.Descendants("User")\n    .Where(x => x.Element("Name").Value == "David")\n    .ToList();\n\nif (userElements.Any())\n{\n    string lastDate = userElements.Select(x => \n                                       DateTime.Parse(x.Element("Date").Value))\n        .OrderByDescending(x => x)\n        .First()\n        .ToString();\n}	0
4836846	4833023	calling modal window from asp.net secure site links	public void LinkButton_Click(object sender, EventArgs e) {\n    if (!Request.IsAuthenticated) {\n        Page.RegisterClientScriptBlock("myScript", "<script language='javascript'>alert('');</script>");\n    }\n    else {\n        myalert.Text = "no dice";\n    }\n}	0
7194971	7194952	Inherit from an abstract class and realize an interface at the same time	MyViewModelClass: MyAbstractBaseForVMClass, INotifyPropertyChanged	0
17756217	17690308	Extracting action from recognized string	GoogleSearch.Text += (" " + e.Result.Text.ToString().substring(OFFSET));	0
5386305	5375596	Unable to get htmlelement in winforms webbrowser control	HtmlWindow docWindow = extendedWebBrowser2.Document.Window;\n\nforeach (HtmlWindow frameWindow in docWindow.Frames)\n{\n  implementation code...\n}	0
7874143	7874111	Convert DateTime.Now to a valid Windows filename	DateTime.Now.ToString("dd_MM_yyyy")	0
20288092	20287406	Unable to Use an HtmlHelper in Razor syntax in MVC4 Intranet App using Entity Framework	public partial class PrinterMapping\n{\n    [Bind(Exclude="ExceptionMessage")]\n    public string ExceptionMessage { get; set; }\n}	0
32455917	32455749	Generating XML document with C#	[XmlText]\npublic string Value { get; set; }	0
18442826	18436917	How can I get the partition UUID of a disk in .NET	Environment.OSVersion.Platform	0
22598555	22598539	C# use SHA1 to hash string into byte array	String passwd = Membership.GeneratePassword(10, 2);\nbyte[] bytes = System.Text.Encoding.UTF8.GetBytes(passwd);\nSHA1 sha = new SHA1CryptoServiceProvider();\nbyte [] password = sha.ComputeHash(bytes);	0
18741292	18741096	Find IP address of remote server	netstat -an -p tcp	0
10657468	10657438	C# address Button using a string	Button btn = (Button)sender;\nbtn.Text = "Whatever";	0
29571538	29571129	Delete specific document from DocumentDb	class CrawlResult\n{\n    [JsonProperty("jobId")]\n    public string JobId;\n}\n\nprivate async Task QueryAndDelete(DocumentClient client, string collectionLink)\n{\n    await client.CreateDocumentAsync(collectionLink, new CrawlResult { JobId = "J123" });\n    await client.CreateDocumentAsync(collectionLink, new CrawlResult { JobId = "J456" });\n\n    foreach (Document document in client.CreateDocumentQuery(\n        collectionLink,\n        new SqlQuerySpec(\n            "SELECT * FROM crawlResults r WHERE r.jobId = @jobId",\n            new SqlParameterCollection(new[] { new SqlParameter { Name = "@jobId", Value = "J123" } })\n            )))\n    {\n        // Optionally, cast to CrawlResult using a dynamic cast\n        CrawlResult result = (CrawlResult)(dynamic)document;\n\n        await client.DeleteDocumentAsync(document.SelfLink);\n    }\n}	0
15463038	15462960	Can we send mails from localhost using asp.net and c#?	using (var client = new SmtpClient("smtp.gmail.com", 587)\n{\n  Credentials = new NetworkCredential("yourmail@gmail.com", "yourpassword"),\n  EnableSsl = true\n})\n{\n  client.Send("frommail@gmail.com", "tomail@gmail.com", "subject", message);\n}	0
2867037	2867009	DateTime Compare in c#	TimeSpan diff = date2.Subtract(date1);	0
30641335	30641212	Don't split the string if contains in double marks	Microsoft.VisualBasic.FileIO.TextFieldParser	0
12110213	12110131	Waiting for WebBrowser to load in a timer	webBrowser1.Navigated += WebBrowser_DocumentCompleted;\ntimesToRun = 22;\n\nprivate void Time_Tick(object sender, EventArgs e)\n{\n    timer.stop();\n    webBrowser1.Document.Window.Navigate(url);\n}\n\nvoid WebBrowser_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)\n{\n    timesToRun--;\n    if(timesToRun > 0)\n    {\n        timer.Start();\n    }\n}	0
29651478	29649070	Filter records by string using wildcard in any position	public IEnumerable<string> MyFunc(string searchString)\n{\n    return myThingToSearch.Where(x => LevenshteinDistance(x, searchString) <= 1);\n}\n\npublic static int LevenshteinDistance(string s1, string s2)\n{\n    if (s1 == s2)\n    {\n        return 0;\n    }\n\n    if (s1.Length == 0)\n    {\n        return s2.Length;\n    }\n\n    if (s2.Length == 0)\n    {\n        return s1.Length;\n    }\n\n    int[] v0 = new int[s2.Length + 1];\n    int[] v1 = new int[s2.Length + 1];\n    for (int i = 0; i < v0.Length; i++)\n    {\n        v0[i] = i;\n    }\n\n    for (int i = 0; i < s1.Length; i++)\n    {\n        v1[0] = i + 1;\n\n        for (int j = 0; j < s2.Length; j++)\n        {\n            var cost = (s1[i] == s2[j]) ? 0 : 1;\n            v1[j + 1] = Math.Min(v1[j] + 1, Math.Min(v0[j + 1] + 1, v0[j] + cost));\n        }\n\n        for (int j = 0; j < v0.Length; j++)\n        {\n            v0[j] = v1[j];\n        }\n    }\n    return v1[s2.Length];\n}	0
14562694	14562365	Input string that takes in only letters, alphabets, # and spaces	if (Regex.IsMatch(textBox_address.Text, @"^[a-zA-Z0-9# ]+$"))	0
673246	673205	How to check if two Expression<Func<T, bool>> are the same	using System;\nusing System.Linq.Expressions;\n\nusing Db4objects.Db4o.Linq.Expressions;\n\nclass Test {\n\n    static void Main ()\n    {\n    Expression<Func<int, bool>> a = x => false;\n    Expression<Func<int, bool>> b = x => false;\n    Expression<Func<int, bool>> c = x => true;\n    Expression<Func<int, bool>> d = x => x == 5;\n\n    Func<Expression, Expression, bool> eq =\n    ExpressionEqualityComparer.Instance.Equals;\n\n    Console.WriteLine (eq (a, b));\n    Console.WriteLine (eq (a, c));\n    Console.WriteLine (eq (a, d));\n    }\n}	0
2823219	2823073	Finding spelling of an element in an ignore case dictionary	string value = myDictionary.First(v => StringComparer.Create(CultureInfo.CurrentCulture,true)\n                  .Compare(v.Key,"AAA") == 0)\n                  .Key	0
17078190	17005911	How to create an expression call with function createdatetime?	Expression.Call(typeof(EntityFunctions), "CreateDateTime",\n  new Type[]\n      {\n        typeof(int?), typeof(int?), typeof(int?), \n        typeof(int?), typeof(int?), typeof(double?)\n      }, \n  new Expression[]\n      {\n        Expression.Convert(Expression.Constant(2012),typeof(int?)),\n        Expression.Convert(Expression.Constant(12),typeof(int?)),\n        Expression.Convert(Expression.Constant(22),typeof(int?)),\n        Expression.Convert(Expression.Constant(0),typeof(int?)),\n        Expression.Convert(Expression.Constant(0),typeof(int?)),\n        Expression.Convert(Expression.Constant(0.0),typeof(double?)),\n      }\n );	0
15133673	15133379	How to test custom configuration section in web.config?	Configuration OpenWebConfiguration(string configurationFilePath)\n{\n    var configurationFileInfo = new FileInfo(configurationFilePath);\n    var vdm = new VirtualDirectoryMapping(configurationFileInfo.DirectoryName, true, configurationFileInfo.Name);\n    var wcfm = new WebConfigurationFileMap();\n    wcfm.VirtualDirectories.Add("/", vdm);\n    return WebConfigurationManager.OpenMappedWebConfiguration(wcfm, "/");\n}\n\n...\nvar c = OpenWebConfiguration(pathToWebConfigFile);\nvar section = c.GetSection(sectionName);\n... etc ...	0
11903448	11903270	Reading a Single Item from a custom web config section	ConfigurationManager.RefreshSection("Items")	0
6169056	6168954	Playing sound byte[] in C#	byte[] bytes = ...\nstring name = Path.ChangeExtension(Path.GetRandomFileName(), ".wav");\nstring path = Path.Combine(Path.GetTempPath(), name);\nFile.WriteAllBytes(path, bytes);\nProcess.Start(path);	0
18821071	18820845	List operations getting a list's index	var pets = new Dictionary<string, int>();\npets.Add("Dogs", 2);\npets.Add("Fish", 8);\nint amount = pets["Fish"];	0
22810682	22810493	How to delete all match and delete text	richTextBox1.Lines = richTextBox1.Lines\n    .Where((line, b) => !line.Contains("Banned"))\n    .Select((line, b) => line).ToArray();	0
28749867	28748865	"InvalidDataContractException: Type contains two members with same data member name" for no apparent reason	var protectedFile=\nnew ProtectedFile("C",new FileIdInfo(new FileSystemFileIdInformation(\n                        1, new FileId128(2,3)),\n                4));\n            DataContractSerializer d = new DataContractSerializer(protectedFile.GetType());\n            var stream = new MemoryStream();\n            d.WriteObject(stream, protectedFile);\n            stream.Seek(0, SeekOrigin.Begin);\n            var fileAfterSerialization = d.ReadObject(stream);	0
29549289	29549229	Reading a delimited text file by line and by delimiter in C#	string[] lines = File.ReadAllLines( filename );\nforeach ( string line in lines )\n{\n  string[] col = line.Split( new char[] {','} );\n  // process col[0], col[1], col[2]\n}	0
6776084	6775919	PHP Equivalent of C# ticks	microtime(true)	0
10372139	10372028	WCF Data Services - How to write this Select LINQ Query	se.Streets.Where(s => s.CityId == (int)cb_City.EditValue)\n              .Select(s => new { \n                    HebName = s.HebName,\n                    EngName = s.EngName,\n                    ID = s.StreetID\n              }).ToList();	0
5982788	5982417	C# - Cookie Management	(request as HttpWebRequest).CookieContainer = new CookieContainer();\nHttpWebResponse response = (HttpWebResponse)request.GetResponse();\nCookieCollection cookies = (request as HttpWebRequest).CookieContainer.GetCookies("www.binarywatch.biz");\nstring myValue cookies["myCookie"].Value	0
10434185	10433780	Castle Windsor - set up of AOP outside application	container.Install(FromAssembly.InThisApplication());	0
22662154	22661892	How can i check of a string contains a letter space letter space and anotherl letter C#	void Main()\n{\n    string test = "P I E T S N O T . C O M";\n    Console.WriteLine(CheckSpaceLetterSequence(test));\n    test = "Hi my name is";\n    Console.WriteLine(CheckSpaceLetterSequence(test));\n}\n\n\nbool CheckSpaceLetterSequence(string test)\n{\n    int count = 0;\n    bool isSpace = (test[0] == ' ');\n    for(int x = 1; x < test.ToCharArray().Length; x++)\n    {\n        bool curSpace = (test[x] == ' ');\n        if(curSpace == isSpace)\n            return false;\n\n        isSpace = !isSpace;\n        count++;\n        if(count == 3)\n           break;\n    }\n    return true;\n}	0
6491073	6490995	How to use unichar array in C# struct with DLLImport of unmanaged C	[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]\npublic struct foo\n{\n   public IntPtr fileId;\n   [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 15)]\n   public string fileName;\n}	0
18455224	18454856	Edit property in entity framework in contructor	public String DecryptPassword\n{\n    get\n    {\n        return Decrypt(this.Pin);\n    }\n}	0
11588954	11588930	Set selected values in asp ListBox with one line	string[] pageRoles = new string[] {"Admin", "Users", "Publisher"};\npageRoles.ToList().ForEach(r => rolesListBox.Items.FindByValue(r).Selected = true);	0
20322026	20066651	How to call methods of .Net nested class from COM callers	[ProgId("Application.TestA.TestB")	0
8163545	8140385	Moving From LINQpad to a Proper Visual Studio Project?	File.Copy (GetType().BaseType.Assembly.Location, ...	0
10274534	10169137	SQL Server 2005 Accessing a FileUpload control in code-behind	if(FormView1.CurrentMode == FormViewMode.Edit){\n  FileUpload f = (FileUpload) FormView1.FindControl("FleUpload");\n  .... then rest of code\n}	0
3207586	3207492	Visual C# - Write contents of a textbox to a .txt file	File.WriteAllText(filename, logfiletextbox.Text)	0
11763883	11763821	reading string each number c#	string line;\nList<string> stdList = new List<string>();\n\nStreamReader file = new StreamReader(myfile);\nwhile ((line = file.ReadLine()) != null)\n{\n    stdList.Add(line);\n    var trash = file.ReadLine();  //this advances to the next line, and doesn't do anything with the result\n}\nfinally\n{\n}	0
15923136	15474669	get content files according to the number of revision	GetFileAnnotationsCmdOptions gfacmo = new GetFileAnnotationsCmdOptions(GetFileAnnotationsCmdFlags.AllResults, k);	0
28279638	28278446	Best way to checksum a collection of variables?	public class _Object\n    {\n        public Int32 IntField;\n        public String StringField;\n        public Decimal DecimalField;\n        public Guid GuidField;\n\n        private string m_UniqueKey;\n        [DebuggerBrowsable(DebuggerBrowsableState.Never)]\n        public string UniqueKey\n        {\n            get\n            {\n                if (m_UniqueKey == null)\n                {\n                    m_UniqueKey = IntField.ToString()\n                                + "|" + (StringField ?? string.Empty)\n                                + "|" + DecimalField.ToString("F6", CultureInfo.InvariantCulture)\n                                + "|" + GuidField.ToString("X");\n                }\n                return m_UniqueKey;\n            }\n        }\n    }	0
17808672	17797778	WCF Soap Service with Meta Data Export	var meta = new ServiceMetadataBehavior()\n{\n    //ExternalMetadataLocation = new Uri(soapServerUrl + "/CritiMon?wsdl"),\n    HttpGetEnabled = true,\n    HttpGetUrl = new Uri("", UriKind.Relative),\n    HttpGetBinding = basicHttpBinding,\n};\n\n host.AddServiceEndpoint(typeof(IMetadataExchange), MetadataExchangeBindings.CreateMexHttpBinding(), "mex");	0
299406	296842	Converting Days into Human Readable Duration Text	let divmod n m = n / m, n % m    \n\nlet units = [\n    ("Centuries", TimeSpan.TicksPerDay * 365L * 100L );\n    ("Years", TimeSpan.TicksPerDay * 365L);\n    ("Weeks", TimeSpan.TicksPerDay * 7L);\n    ("Days", TimeSpan.TicksPerDay)\n]\n\nlet duration days =\n    let rec duration' ticks units acc =\n        match units with\n        | [] -> acc\n        | (u::us) ->\n            let (wholeUnits, ticksRemaining) = divmod ticks (snd u)\n            duration' ticksRemaining us (((fst u), wholeUnits) :: acc)\n    duration' (TimeSpan.FromDays(float days).Ticks) units []	0
9254701	9254680	String manipulation to URI in C#	var s = @"\\localhost\C:\MP3 Collection\?lbuns\# - E\A\a-ha\[1985] Hunting High And Low\01. Take On Me.mp3";\n\nvar result = Path.Combine(Path.GetDirectoryName(s), "folder.jpg");\n// result == @"\\localhost\C:\MP3 Collection\?lbuns\# - E\A\a-ha\[1985] Hunting High And Low\folder.jpg"	0
11719800	11719684	Alter lines in a multiline TextBox programatically - Silverlight	var text = textBox.GetLineText(1);	0
18570903	18570657	C# - XML serialization of derived classes	public class XMLFile\n{\n    [XmlArray("MasterFiles")]\n    [XmlArrayItem("Supplier", typeof(Supplier))]\n    [XmlArrayItem("Customer", typeof(Customer))]\n    public List<MasterElement> MasterFiles;\n}	0
21356552	21356518	How to print contents of the array with spaces using the c# ForEach method and store it in a string variable?	var joinedWords = string.Join(" ", words);	0
5645050	5644994	Want to display a Visual notification in my C# Application	if (WindowState==FormWindowState.Minimized)\n{\n   BackupMinimizeNotification.Visible = true;\n   Hide();\n   BackupMinimizeNotification.BalloonTipTitle = "APP Hidden";\n   BackupMinimizeNotification.BalloonTipText = "Your application has been minimized to the taskbar.";\n   BackupMinimizeNotification.ShowBalloonTip(2000);\n}	0
3552918	3552687	Setting property values dynamically	foreach (DataRow dr in appearances) {\n   string type = dr["Type"].ToString();\n\n   PropertyInfo propertyForType = grid.AppearancePrint.GetType().GetProperty(type);\n   object objectForProperty = propertyForType.GetValue(grid.AppearancePrint, null);\n\n   PropertyInfo propertyForBackColor = objectForProperty.GetType().GetProperty("BackColor");\n   PropertyInfo propertyForBackColor2 = objectForProperty.GetType().GetProperty("BackColor2");\n\n   propertyForBackColor.SetValue(objectForProperty, Color.FromName(dr["BackColor"].ToString()), null);\n   propertyForBackColor2.SetValue(objectForProperty, Color.FromName(dr["BackColor2"].ToString()), null);\n}	0
641337	641240	Changing the Log4Net Root Level When App is built as Release	public static void Initialize()\n{\n\n#if DEBUG\n    ConfigureAndWatch();\n#else\n    ConfigureAndLockChanges();\n#endif\n\n}\n\n#if DEBUG\n\nprivate static void ConfigureAndWatch()\n{\n    XmlConfigurator.ConfigureAndWatch(new FileInfo("log4net.config"));\n}\n\n#else\n\nprivate static void ConfigureAndLockChanges()\n{\n    // Disable using DEBUG mode in Release mode (to make harder to hack)\n    XmlConfigurator.Configure(new FileInfo("log4net.config"));\n    foreach (ILoggerRepository repository in LogManager.GetAllRepositories())\n    {\n        repository.Threshold = Level.Warn;\n    }\n}\n\n#endif	0
8739916	8739859	Need a RegEx to eliminate < and >	here is a working example : \n\nstring plainText = Regex.Replace(htmlText, "<[^>]+?>", "");	0
7865052	7864968	set gridview column width in c#	GridView1.RowCreated += new GridViewRowEventHandler(GridView1_RowCreated);\n\n      void GridView1_RowCreated(object sender, GridViewRowEventArgs e)\n        {\n            e.Row.Cells[0].Width = 200;\n           // GridView1.Columns[0].HeaderStyle.Width = 100;\n        }	0
1603829	1603585	C# - Transform text in ListView column into password characters	String password = "MyPassword";\nListViewItem lvi = new ListViewItem("********");\nlvi.Tag = password;\n\nlistView.Items.Add(lvi);	0
2259197	2259171	How to get a static reference to a WPF Window?	public class Core\n{\n     internal static MyWindowClass m_Wnd = null;\n\n     // call this when your non-static form is created\n     //\n     public static void SetWnd(MyWindowClass wnd)\n     {\n         m_Wnd = wnd;\n     }\n\n     public static MyWindow { get { return m_Wnd; } }\n}	0
11828922	11828843	WebException how to get whole response with a body?	var resp = new StreamReader(ex.Response.GetResponseStream()).ReadToEnd();\n\ndynamic obj = JsonConvert.DeserializeObject(resp);\nvar messageFromServer = obj.error.message;	0
28459553	4360009	Any Good Open Source Web Crawling Framework in C#	void Test()\n{\n    var linkText = @"Help Spread DuckDuckGo!";\n    Console.WriteLine(GetHyperlinkUrl("duckduckgo.com", linkText));\n    // as of right now, this would print ?https://duckduckgo.com/spread?\n}\n\n/// <summary>\n/// Loads pageUrl, finds a hyperlink containing searchLinkText, returns\n/// its URL if found, otherwise an empty string.\n/// </summary>\npublic string GetHyperlinkUrl(string pageUrl, string searchLinkText)\n{\n    using (IWebDriver phantom = new PhantomJSDriver())\n    {\n        phantom.Navigate.GoToUrl(pageUrl);\n        var link = phantom.FindElement(By.PartialLinkText(searchLinkText));\n        if(link != null)\n            return link.GetAttribute("href");\n    }\n    return string.Empty;\n}	0
19545832	19545716	Simplifying a LINQ expression	A a = collection.FirstOrDefault(x => x.Field == null);\n\nif(a != null)    \n   throw new ScriptException("{0}", a.y);	0
21137864	21137644	Datagrid add data dynamically	var datagridTopic = new DataGrid {Width = 400, IsReadOnly = true};\n//I only need one column\nvar column1 = new DataGridTextColumn()\n{\n    Header = "ID",\n    Width = datagridTopic.Width - 8 //after adding rows the grid gets scroll, so made column width lower\n};\ncolumn1.Binding = new Binding("ID")\ndatagridTopic.Columns.Add(column1);\n\nvar column2 = new DataGridTextColumn()\n{\n    Header = "Title",\n    Width = datagridTopic.Width - 8 //after adding rows the grid gets scroll, so made column width lower\n};\ncolumn2.Binding = new Binding("Title")\ndatagridTopic.Columns.Add(column2);\n\nvar items = xElementArray.Select(x => new { ID= x.Attribute("id").Value, Title = x.Attribute("title").Value});\n\n\ndatagridTopic.ItemsSource = items; //set the data source for the grid to custom created items.\n\nStackPanelContent.Children.Add(datagridTopic);	0
1861968	1425732	How to read each revision of file using sharpsvn client using c#?	public void WriteRevisions(SvnTarget target, SvnRevision from, SvnRevision to)\n{\n    using(SvnClient client = new SvnClient())\n    {\n        SvnFileVersionsArgs ea = new SvnFileVersionsArgs \n            {\n                Start = from,\n                End = to\n            };\n\n        client.FileVersions(target, ea,\n            delegate(object sender2, SvnFileVersionEventArgs e)\n                {\n                    Debug.WriteLine(e.Revision);\n                    e2.WriteTo(...);\n                 });\n    }\n}	0
7159031	7158967	Parse value from string with structure "key=value"	var regex=new Regex(@"RCV_VALUE=(?<value>\d+)");\nvar match=regex.Match(inputString);\nvar rcv_value=int.Parse(match.Groups["value"].Value);	0
6167494	6167311	ListBox scrolling	int tempTopIndex = listBox1.TopIndex;\nlistBox1.Items.Remove(yourItem);\nlistBox1.TopIndex = tempTopIndex;	0
6008674	6003942	Check if word in english dictionary programmatically in c#	NetSpell.SpellChecker.Dictionary.WordDictionary oDict = new NetSpell.SpellChecker.Dictionary.WordDictionary(); \n\noDict.DictionaryFile = "en-US.dic"; \n//load and initialize the dictionary \noDict.Initialize();\nstring txtWords = Company;\nNetSpell.SpellChecker.Spelling oSpell = new NetSpell.SpellChecker.Spelling(); \n\noSpell.Dictionary = oDict; \nchar []chDelims = {' ','\n', '\t', '\r'};\nforeach (string s in txtWords.Split(chDelims)) \n{ \n    if (s.Length > 0 && oSpell.TestWord(s)) \n    { \n        //Do something here...\n    } \n}	0
18886192	18885901	Adding element to xml	xdocument\n    .Descendants("SettingsGroup")\n    .Where(x => x.Attribute("name").Value == "item2")\n    .First()\n    .Add(new XElement("Setting", new XAttribute("name", "value3"), 5));	0
33395034	33394019	Get UserName in a Windows 10 C# UWP Universal Windows app	private async void Page_Loaded(object sender, RoutedEventArgs e)\n{\n    IReadOnlyList<User> users = await User.FindAllAsync();\n\n    var current = users.Where(p => p.AuthenticationStatus == UserAuthenticationStatus.LocallyAuthenticated && \n                                p.Type == UserType.LocalUser).FirstOrDefault();\n\n    // user may have username\n    var data = await current.GetPropertyAsync(KnownUserProperties.AccountName);\n    string displayName = (string)data;\n\n    //or may be authinticated using hotmail \n    if(String.IsNullOrEmpty(displayName))\n    {\n\n        string a = (string)await current.GetPropertyAsync(KnownUserProperties.FirstName);\n        string b = (string)await current.GetPropertyAsync(KnownUserProperties.LastName);\n        displayName = string.Format("{0} {1}", a, b);\n    }\n\n    text1.Text = displayName;\n}	0
25710594	25710377	How can I use a parameter in an interface that is defined by the interface	class SomethingElse_class : SomethingElse\n        {\n            public void g(Something_class s)\n            {\n                Console.WriteLine("SomethingElse.g");\n            }\n            public void g(Something s) //overload g with the (Something s)\n            {\n                Console.WriteLine("Something.g");\n            }\n        }	0
4744798	4744084	Need some Design suggestion in C#	public static LogHandler GetLogger()	0
33655318	33654580	Ninject binding with two generic parameters in types	typeof(IRepository<,>)	0
16895669	16895620	Can I pass a MouseDown event for a form to a custom class?	SendMessage(f.Handle, WM_NCLBUTTONDOWN, HT_CAPTION, 0);	0
12483766	12483419	How to have radio button selected after page refresh	switch ((Request["category_id"]))\n    {\n        case "0": viewAll.Checked = true; break;\n        case "1": journey.Checked = true; break;\n        case "2": challenges.Checked = true; break;\n        case "3": advice.Checked = true; break;\n        case "4": thanks.Checked = true; break;\n        case "5": perspective.Checked = true; break;\n    }	0
7583065	7577535	Iphone, Obtaining a List of countries from MonoTouch	public void DisplayCountryCodeNames ()\n    {\n        NSLocale current = NSLocale.CurrentLocale;\n        IntPtr handle = current.Handle;\n        IntPtr selDisplayNameForKeyValue = new Selector ("displayNameForKey:value:").Handle;\n        foreach (var countryCode in NSLocale.ISOCountryCodes) {\n            using (var key = new NSString ("kCFLocaleCountryCodeKey")) {\n                using (var nsvalue = new NSString (countryCode)) {\n                    string ret = NSString.FromHandle (MonoTouch.ObjCRuntime.Messaging.IntPtr_objc_msgSend_IntPtr_IntPtr (handle, selDisplayNameForKeyValue, key.Handle, nsvalue.Handle));\n                    Console.WriteLine ("{0} -> {1}", countryCode, ret);\n                }\n            }\n        }\n    }	0
7895778	7882634	Search lists for keyword matches with an arbitrary string list	var results =  from r in datacontext.List \n    where r.title.Contains(Value1) OR r.title.Contains(Value2)	0
10581457	10580846	RegEx pattern needed to return the same found pattern under two different group names	string input = "Some identifier=Just a value like 123";\nstring pattern = @"^(?'key'.*?)(?'anotherName'\k<key>)=(?'value'.*)$";\nRegex regex = new Regex(pattern);\nMatch match = regex.Match(input);\n\nvar key = match.Groups["key"];\nvar value = match.Groups["value"];\nvar sameAsKeyButWithOtherGroupName = match.Groups["anotherName"];\n\nAssert.That(key, Is.EqualTo(sameAsKeyButWithOtherGroupName));	0
3180870	3180825	How do I convert these generic method calls from C# to Java	T <T> getValue(String methodName, Object param, Class<T> type)	0
3916601	3916578	Given a List of objects, how can I find the index of any particular object?	var users = new List<User> { ... };\n\nvar userRanks = users\n    .OrderBy(user => user.Prop1)\n    .ThenBy(user => user.Prop2)\n    .Select((user, index) => new { User = user, Rank = index + 1 });	0
32246661	32246237	Search a list of objects using object attributes	public List<Member> Search(string name, string email, string telephone, string username, List<Member> source)\n    {\n        var query = from s in source\n                    where (((s.name == name) || string.IsNullOrEmpty(name))\n                        && ((s.email == email) || string.IsNullOrEmpty(email))\n                        && ((s.telephone == telephone) || string.IsNullOrEmpty(telephone))\n                        && ((s.username == username) || string.IsNullOrEmpty(username)))\n                    select s;\n\n        return query.ToList();\n    }\n\n    public class Member\n    {\n        public String username;\n        public String name;\n        public String email;\n        public String telephone;\n    }	0
13940926	13940875	How can I check keyboard key state within a mousemove event	bool buttonpressed = false;\nprivate void KeyDown_Event(object s, System.Windows.Forms.KeyEventArgs e)\n{\n   if(e.KeyCode == KeyCode.Space)\n      buttonpressed = true;\n   else\n      buttonpressed = false;\n}\n\nprivate void pictureBox1_MouseMove(object sender, MouseEventArgs e)\n        {\n            if (e.Button == MouseButtons.Left)\n            {\n                if (buttonPressed)\n                {\n                    /* Do modified behavour for left mouse being held down while \n                    space is also held down */\n                }\n                else\n                {\n                    // Do normal behavour for left mouse being held down\n                }\n\n            }\n        }	0
16323203	16322691	Change the value of a textbox in a template field from event outside of GridView.	private void template textBox1_TextChanged(object sender, TextChangedEventArgs e)\n {\n if textBox1.Text (Double.TryParse(textBox1.Text, out value1))\n  {\n  textBox15 = value1.ToString();\n       }\n   }	0
9301251	9301225	Array of dictionaries in C#	Dictionary<int, string>[] matrix = new Dictionary<int, string>[] \n{\n    new Dictionary<int, string>(),\n    new Dictionary<int, string>()\n};	0
9897624	9875485	Find button in bindingNavigator c#	int pos = this.clientBindingSource.Find("id", toolStripTextBox1.Text); \nthis.clientBindingSource.Position = pos;	0
3397441	3397287	c# backgroundworker for socket application	private object _lock = new object(); //should have class scope\n\nprivate void DispalyMessage(byte[] bytes)\n{\n  if (this.InvokeRequired)\n  {\n    lock (_lock)\n    {\n      EventHandler d = new EventHandler(DispalyMessage);\n      this.Invoke(d, new object[] { bytes });\n      return;\n    }\n  }\n  else\n  {\n    //the bytes data has been marshaled from the controller class thread to the ui thread and can be used at will to populate a memeber of the ui.\n  }\n}	0
7675778	7675743	Convert string to datetime in asp.net	string[] dateStrings = {"2008-05-01T07:34:42-5:00", \n                        "2008-05-01 7:34:42Z", \n                        "Thu, 01 May 2008 07:34:42 GMT"};\nforeach (string dateString in dateStrings)\n{\n   DateTime convertedDate = DateTime.Parse(dateString);\n   Console.WriteLine("Converted {0} to {1} time {2}.", \n                     dateString, \n                     convertedDate.Kind.ToString(), \n                     convertedDate);\n}	0
30747715	30747257	disable and enable textbox on checkbox click in table	cbox.Attributes.Add("onclick", "document.getElementById('textbox_" + count1 + "').disabled = !this.checked;");	0
8793662	8793501	String function (regex?) to remove query string pair from url string	(&token=[^&]*|token=[^&]*&)	0
717077	717074	How to access form objects from another cs file in C#	public static class Test\n{\n    public static void DisalbeMyButton()\n    {\n        var form = Form.ActiveForm as Form1;\n\n        if (form != null)\n        {\n            form.MyButton.Enabled = false;\n        }\n    }\n}	0
5141900	5141863	How to get distinct characters in c#	string code = "AABBDDCCRRFF";\n        string answer = new String(code.Distinct().ToArray());	0
2643855	2637083	Testing a method used from an abstract class	namespace AbstractTestExample\n{\n    public abstract class AbstractExample\n    {\n        protected XmlNode propertyValuesXML;\n\n        protected string getProperty(string propertyName)\n        {\n            XmlNode node = propertyValuesXML.FirstChild.SelectSingleNode(String.Format("property[name='{0}']/value", propertyName));\n            return node.InnerText;\n        }\n    }\n\n    public class AbstractInheret : AbstractExample\n    {\n        public AbstractInheret(string propertyValues){\n\n            propertyValuesXML = new XmlDocument();\n            propertyValuesXML.Load(new System.IO.StringReader(propertyValues));\n        }\n\n        public void runMethod()\n        {\n            bool addIfContains = (getProperty("AddIfContains") == null || getProperty("AddIfContains") == "True");\n            //Do something with boolean\n        }\n    }\n}	0
5252370	5252276	c# - Pass a class to a method	class DTO\n{\n//All you properties go here\n}\n\nclass databaseConnector\n{\n     public void saveToDB (DTO dto){\n      //whatever you want to do here...\n     }\n}	0
25864068	25863744	Connect to database using sql server authentication programatically	SqlConnectionStringBuilder connectionString = new SqlConnectionStringBuilder();\nconnectionString.ConnectionString = @"data source=.;initial catalog=master;";\nconnectionString.UserID = "username";\nconnectionString.Password = "password";\n\nusing (var sqlConnection = new SqlConnection(connectionString.ConnectionString))\n{\n\n}	0
1627349	1606530	PInvoke - how to represent a field from a COM interface	[Guid("ae9e84b5-3e2d-457e-8fcd-5bbd2a8b832e"), ComImport, \n    InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]\ninterface nsICacheSession\n{\n\n    bool doomEntriesIfExpired \n    { \n        [param:MarshalAs(UnmanagedType.Bool)]set; \n        [return:MarshalAs(UnmanagedType.Bool)]get; \n    }	0
6648944	6647730	change wav file ( to 16KHz and 8bit ) with using NAudio	using (var reader = new WaveFileReader("input.wav"))\n{\n    var newFormat = new WaveFormat(8000, 16, 1); \n    using (var conversionStream = new WaveFormatConversionStream(newFormat, reader))\n    {\n        WaveFileWriter.CreateWaveFile("output.wav", conversionStream);\n    } \n}	0
16059102	16059056	How to stop leading 0's from being stripped from my integers in C#	Console.WriteLine(i.ToString("D4"));	0
8347354	8347173	How can I use Eval in asp.net to read fields from a database?	public int MyFieldID = 0;\npublic string MyStringFromDB = string.empty;\n\n// PAGE LOAD GET DB VALUES\n{\n    MyFieldID = Convert.ToInt32(db["ID"]);\n    MyStringFromDB = Convert.ToString(db["FIELD"]);\n}	0
31534797	31416934	Iterating backwards through an char array after finding a known word	string wordString = "(Four)";\n        string sentenceString = "Maybe the fowl of Uruguay repeaters (Four) will be found";\n        //Additionally you can add splitoption to remove the empty word on split function bellow\n        //Just in case there are more space in sentence.\n        string[] splitedword = sentenceString.Split(' ');\n        int tempBackposition = 0;\n        int finalposition = 0;\n        for (int i = 0; i < splitedword.Length; i++)\n        {\n            if (splitedword[i].Contains(wordString))\n            {\n                finalposition = i;\n                break;\n            }\n        }\n        tempBackposition = finalposition - wordString.Replace("(","").Replace(")","").Length;\n        string output = "";\n        tempBackposition= tempBackposition<0?0:tempBackposition;\n        for (int i = tempBackposition; i < finalposition; i++)\n        {\n            output += splitedword[i] + " ";\n        }\n        Console.WriteLine(output);\n        Console.ReadLine();	0
5142953	5142687	Fluent NHibernate mapping properties coming from an interface in one place	public class BasePageMapping : SubclassMap<IPage> //IPage could inherit: IMultiTaggedPage, ISearchablePage\n{\n    public BasePageMapping()\n    {\n        Map(x => x.Text, "Text");\n        // coming from IMultiTaggedPage\n        HasManyToMany(x => x.Tags).Table("PageTags").ParentKeyColumn("PageId").ChildKeyColumn("TagId").Cascade.SaveUpdate();\n        // coming from ISearchablePage\n        Map(x => ((ISearchablePage)x).SearchIndex, "SearchIndex").LazyLoad();\n    }\n}\n\npublic class PostMapping : BasePageMapping\n{\n    public PostMapping()  // don't need to specify : base() because it happens automatically\n    {\n        Table("the specific table");\n\n        HasManyToMany(x => x.Categories).Table("PageCategories").ParentKeyColumn("PageId").ChildKeyColumn("CategoryId").Cascade.SaveUpdate();\n\n        //Other table specific mappings:\n    }\n}	0
21429356	21428963	Add a different 'reply to' Email address in MailDefinition C#	System.Net.Mail.MailMessage m = new System.Net.Mail.MailMessage();\nm.Body = "HTML Content";\nm.IsBodyHtml = true;	0
32337752	32336502	C# - How do I print a string in another listbox?	lstYourListBox.BeginInvoke(new MethodInvoker(() => lstYourListView.items.Add(clientIP));	0
12484967	12484905	Search string in Listbox	int index = -1;\n                            for (int i = 0; i < listBox3.Items.Count; ++i)\n                               if (listBox3.Items[i].Text == Nom2) { index = i; break; }\n                            if (index != -1)\n                            {\n                                this.listBox1.Items.Add(t);\n                                MessageBox.Show("Find It");\n                            }\n                            else { MessageBox.Show("Not Found :@");	0
10742889	10742517	Binding to property in code behind through window name	XYZ = "XYZ";	0
16673602	16604433	Datagrid: background colour + disable of selection depending on the cell value - using trigger	private void mydatagrid_SelectedCellsChanged(object sender, SelectedCellsChangedEventArgs e)\n        {\n            foreach (var item in e.AddedCells)\n            {\n                var col = item.Column as DataGridColumn;\n                var fc = col.GetCellContent(item.Item);\n\n                if (fc is TextBlock)\n                {\n                    if (((fc as TextBlock).Text == (""))||((fc as TextBlock).Text == null))\n                    {\n                        mydatagrid.SelectedCells.Remove(item);\n                        fc.Focusable = false; // not sure if neccesarry/working after the previous line\n                    }\n                }\n            }\n        }	0
9415090	9414735	LINQ results matching ALL relationships	var query = Products.AsQueryable();\n\nforeach (var feature in searchFeaturesList)\n{\n     // create here new values of featureId and featureValue otherwise will get the first ones from the iterator\n     var featureId = feature.FeatureID;\n     var featureValue = feature.FeatureValue;\n     // each feature id and value is tested if exists in the ProductFeatures\n     query = query.Where(p=>p.ProductFeatures\n                             .Any(pf=> pf.FeatureID == featureId && pf.FeatureValue == featureValue));\n}	0
17952850	17952829	How to search from a list inside a dictionary<string, List<string>>	var input = "456";\nvar matchingKeys = dictionary.Where(kvp => kvp.Value.Contains(input))\n                             .Select(kvp => kvp.Key);	0
4797785	4797681	c# - How to get the value of the defaultDatabase?	MyCustomConfigSection config = (MyConstomConfigSection)\n                               ConfigurationManager.GetSection(\n                                 "MyCustomConfigSectionName"\n                                 ) ;	0
9940622	9928670	C# , Regex replace all linebreak with <br /> outside a bbcode code block	Public Function BBCode(ByVal strTextToReplace As String) As String\n        Dim regExp As Regex\n        strTextToReplace = strTextToReplace.Replace(Chr(10), "<br />")\n\n        regExp = New Regex("\[code\]([^\]]+)\[\/code\]", RegexOptions.Singleline)\n        Dim mc As MatchCollection = regExp.Matches(strTextToReplace)\n        For Each m As Match In mc\n            Dim gs = m.Groups()\n            strTextToReplace = regExp.Replace(strTextToReplace, "<table cellpadding=""2"" cellspacing=""0"" class=""tbl_Quote""><tr><td dir=""rtl""><a class=""quote_Head"">code:</a></td></tr><tr><td><textarea class=""lined"" cols=""77"" readonly=""readonly"" rows=""1"" spellcheck=""false"">" & gs(1).Value.ToString.Replace("<br />", Chr(10)) & "</textarea></td></tr></table>", 1)\n        Next\nReturn strTextToReplace\nEnd Function	0
1366462	1365909	Parsing XML document with XPath, C#	mgr.AddNamespace( "someOtherPrefix", "http://www.w3.org/TR/html4/" );\nvar nodes = xmlDoc.SelectNodes( "/root/someOtherPrefix:node", mgr );	0
25925260	25922793	How to put Task<T> into ObservableCollection and process it with EventLoopScheduler?	var do= new Do();\n\n\nvar result = await do.Later(() => 1 + 2);\n\n\npublic class Do\n{\n    private Subject<Action> _backlog = new Subject<Action>();\n\n    public Do()\n    {\n         Observable.CombineLatest(_backlog, Observable.Timer(...), (l, r) => l)\n              .Subscribe(x => x());\n    }\n\n    public Task<T> Later(Func<T> getResult)\n    {\n        var tcs = new TaskCompletionSource<T>();\n        _backlog.OnNext(() => {\n             try\n             {\n                 var result = getResult();\n                 tcs.SetResult(result);\n             }\n             catch(Exception ex)\n             {\n                 tcs.SetException(ex);\n             }\n        });\n        return tcs.Task;\n    }\n}	0
9967694	9967558	Only allow two digits after decimal in textbox?	if (Regex.IsMatch(textBox1.Text, @"\.\d\d")) {\n   e.Handled = true;\n}	0
25264421	25264304	access dynamic properties of a dynamic class and set value in C#	public static string Grid<T>(IEnumerable<T> collection)\n{\n    ...........\n    ...........\n\n    foreach (T item in collection)\n    {\n        foreach (var p in classProperties )\n        {\n            string s = p.Name + ": " + p.GetValue(item, null);\n        }\n    }\n}	0
22216342	22206146	move to next column in excel	currentColumn = 1, currentRow = 2\n  For i=1 To 10 \n     Cells(currentRow, currentCoulmn).Value = "foo"\n     ' or \n     Sheets(2).Cells(currentRow, currentCoulmn).Value = "bar"\n     currentColumn = currentColumn +1\n  Next	0
2592202	2592180	How can I convert this column value to an integer?	myNum = int.Parse(dt.Rows[0][0].ToString());	0
31926541	31926255	How do I access this type of C++ shared memory in a C# application?	var mappedFile = System.IO.MemoryMappedFiles.MemoryMappedFile.OpenExisting(MemoryMappedFileRights.Read, "GInterface");\n\nusing (Stream view = mappedFile.CreateViewStream())\n{\n    //read the stream here.\n}	0
6849455	6849394	extracting integer from string	int ret;\n\nif (int.TryParse("0001234", out ret))\n{\n    return ret.ToString();\n}\n\nthrow new Exception("eep");	0
479717	479706	Best way to get whole number part of a Decimal number	Math.Truncate(number)	0
5927748	5927157	Moving A Method Inline - Resharper Possible	var fuu = new CustomClass(Enumerable.Range( 1, 1 ))	0
28895802	28895592	How do I autohide a form	private Timer t;\n    private int step = 1;\n\n    private void autohide()\n    {\n        t = new Timer();\n        t.Interval = 2;\n        t.Tick += T_Tick;\n        t.Start();\n    }\n\n    private void T_Tick(object sender, EventArgs e)\n    {\n        if (this.Location.X > 0 - this.Width)\n        {\n            this.Location = new Point(this.Location.X - step, this.Location.Y);\n        }\n        else\n        {\n            t.Stop();\n        }\n    }	0
8613778	8613673	Split string with ' in C#	string line ="1014,'0,1031,1032,1034,1035,1036',0,0,1,1,0,1,0,-1,1" ;\nvar values = Regex.Matches(line, "(?:'(?<m>[^']*)')|(?<m>[^,]+)");\nforeach (Match value in values) {\n  Console.WriteLine(value.Groups["m"].Value);\n}	0
1423678	1423622	Replace QueryString value using regular expressions	static string replace(string url, string key, string value)\n{\n    return Regex.Replace(\n    url, \n    @"([?&]" + key + ")=[^?&]+", \n    "$1=" + value);\n}	0
16673523	16673378	C# How to set StructLayoutAttribute.Pack via Reflection?	public TypeBuilder DefineType(\n    string name,\n    TypeAttributes attr,\n    Type parent,\n    PackingSize packsize\n)	0
13483915	13483837	Where to store windows program data files?	Environment.SpecialFolder.ApplicationData	0
18162802	18162687	XML comments - refer to property in class	/// ...\n/// This constructor sets <see cref="Encoding"/> to its default value.\n/// ...	0
15529740	15529692	Elegant way to manage a lot of fields of the same type	private List<List<MyClass>> myClasses { get; set; }	0
17023910	17023867	Convert Code from VB to C#	if (sqlObj.sel_all_airlines(row["COMPANY"] as string).Tables[0].Rows.Count > 1){\n}	0
9775208	9775123	Set XML serialziation resulting doc root	[Serializable()] \n[XmlRoot("Email-Settings")] \npublic class Config	0
25051398	25051137	Fetching keys using value in KeyValuePair in List	Dictionary<string, List<int>> result = items.GroupBy(d => d.Value).ToDictionary(t => t.Key, t => t.Select(r => r.Key).ToList());	0
26004378	26004079	Loading remote image and writing it from controller	var Img = generatedImage.Image\n\nvar encoder = new JpegBitmapEncoder();\nvar bmFrame = BitmapFrame.Create(Img);\nencoder.Frames.Add(bmFrame);\nencoder.QualityLevel = 100;\n\nvar res = new byte[0];\n\nusing (var stream = new MemoryStream())\n{               \n    encoder.Frames.Add(bmFrame);\n    encoder.Save(stream);\n    res = stream.ToArray(); \n    stream.Close();\n}\n\nreturn File(res, "image/jpeg");	0
11624920	11624862	Download an Excel from a URL and open it for reading?	var client = new WebClient();\n\nString url = "http://...";\nvar fullPath = Path.GetTempFileName();\nclient.DownloadFile(url, fullPath);	0
4686343	4686182	WPF contextmenu is slow with many items - how can I speed it up?	ContextMenu cm = new ContextMenu();\n\n        for (int i = 0; i < 1000; i++)\n        {\n            MenuItem mi = new MenuItem();\n            mi.Header = "test";\n            mi.Tag = this;\n\n            object dummySub = new object();\n            mi.Items.Add(dummySub);\n            cm.Items.Add(mi);\n\n            mi.SubmenuOpened += delegate\n            {\n                mi.Items.Clear();\n\n                for (int j = 0; j < 10; j++)\n                {\n                    MenuItem mi2 = new MenuItem();\n                    mi2.Header = "test";\n                    mi2.Tag = this;\n                    mi.Items.Add(mi2);\n                }\n            };\n        }\n\n        cm.IsOpen = true;	0
32811144	32808735	How to get wlan transfer speed?	var speed = NetworkInterface.GetAllNetworkInterfaces()\n            .Where(inf => inf.NetworkInterfaceType == NetworkInterfaceType.Wireless80211)\n            .Where(inf => inf.OperationalStatus == OperationalStatus.Up)\n            .Select(inf => inf.Speed)\n            .First();	0
30399658	30399573	Get directory name from full directory path regardless of trailing slash	var result = System.IO.Directory.Exists(m_logsDir) ? \n              m_logsDir: \n              System.IO.Path.GetDirectoryName(m_logsDir);	0
18756544	18756409	Setting DateTimePicker to Null	dateTimePicker1.Format = DateTimePickerFormat.Custom;\ndateTimePicker1.CustomFormat = " ";	0
3298845	3298790	Saving file with the same name	string fileName = "/FileHeader_" + m_strDate + ".txt";\nif (File.Exists(fileName))\n{\n  int index = 1;\n  fileName = "/FileHeader_" + index + m_strDate + ".txt";\n  while (File.Exists(fileName))\n    fileName = "/FileHeader_" + ++index + m_strDate + ".txt";\n}	0
15571842	15571728	How to retrieve the name of a Panorama-Item at runtime?	PanoramaItem currentItem = myPanorama.SelectedItem as PanoramaItem;\nif(currentItem != null)\n{\n   //if you want the name for other reasons\n   string name = currentItem.Name;\n\n   //Items returns an ItemsCollection object\n   myPanorama.Items.Remove(currentItem);       \n}	0
14394189	14385455	How to split string with more then one pair of brackets	string test = "((12-5=10)&&(5-4>6))";\n        string[] Arr= test.Split(new string[{"(",")"},StringSplitOptions.RemoveEmptyEntries);\n        List<string> newArr = new List<string>();\n         int h=0;\n        foreach (string s in Arr)           \n        { \n            if (s != "&&")\n                newArr.Add( s.Replace(s, "(" + s + ")"));\n            else \n                newArr.Add(s);\n            h++;\n        }\n        newArr.Insert(0, "(");\n        newArr.Insert(newArr.Count , ")");	0
12206280	12195208	Can WCF Data Service cascade update an object down to it's children?	context.SaveChanges(SaveChangesOptions.Batch);	0
20030655	20029315	HOw to make in mvc4 custome valdation attribute that alllow to view who is allowed to view page only?	[Authorize(Roles = "Admin")]\npublic ActionResult AdminController()\n{\n    //Some process \n     return View(); //This returns admin view if user access this controller.\n}\n\n\n  [Authorize(Users = "someUser")]\n  public ActionResult AdminProfile()\n  {\n    return View();\n  }	0
21821745	21821691	disable third column of data grid view if first two column having data	String Cell1=dataGridView1.Rows[0].Cells[0].Value.ToString();\nString Cell2=dataGridView1.Rows[0].Cells[1].Value.ToString();\n\nif(String.IsNullOrWhiteSpace(Cell1) && String.IsNullOrWhiteSpace(Cell2))\n{\ndataGridView1.Rows[0].Cells[2].ReadOnly = true;\n}	0
8565236	8392001	How do I get CopyFileEx to report back so I can cancel a file copy operation?	this.Update();	0
20778112	20763311	SSIS script to remove date from file name	public void Main() \n    {\n        const string DIRECTORY_PATH = @"C:\temp\";\n        const string FILE_NAME_TEMPLATE = "*_??????.CSV";\n        int underscoreAt = 0; \n\n        if (Directory.Exists(DIRECTORY_PATH))\n        {\n            string[] filePathList = Directory.GetFiles(DIRECTORY_PATH,FILE_NAME_TEMPLATE);\n\n            foreach (string filePath in filePathList)\n            {\n                if (File.Exists(filePath))\n                {\n                    underscoreAt = filePath.LastIndexOf('_');\n\n                    string newName = string.Format ("{0}.CSV", filePath.Substring(0, underscoreAt));\n                    File.Move(filePath,newName );\n                }\n            }\n        }\n    }	0
11388189	11388141	C#: Get the 5 newest (last modified) files from a directory	Directory.GetFiles(path)\n             .Select(x => new FileInfo(x))\n             .OrderByDescending(x => x.LastWriteTime)\n             .Take(5)\n             .ToArray()	0
23684835	23684692	Printing list of enums in a particular namespace C#	List<string> allEnums = new List<string>();\nvar allTypes = AppDomain.CurrentDomain.GetAssemblies().SelectMany(assembly => assembly.GetTypes());\n\nforeach (Type type in allTypes)\n{\n    if (type.Namespace == "MyCompany.SystemLib" && type.IsEnum)\n    {\n        string enumLine = type.Name + ",";\n        foreach (var enumValue in Enum.GetValues(type))\n        {\n            enumLine += enumValue + "=" + ((int)enumValue).ToString() + ",";\n        }\n\n        allEnums.Add(enumLine);\n    }\n}	0
19252049	19251789	Setting a Private Dictionary	private Dictionary<string, int> docTypeValue = new Dictionary<string, int> \n{ \n    { "OSD", 1 },\n    {"POD", 2},\n    {"REC", 3},\n    {"CLAINF", 4},\n    //...\n};	0
22071100	22071019	Pattern for multiple methods with same implementation	public static Helper\n{\n    public static void FactoryFaulted(object sender, EventArgs e)\n    {\n        ChannelFactory factory = (ChannelFactory)sender;\n\n        try\n        {\n            factory.Close();\n        }\n        catch\n        {\n            factory.Abort();\n        }\n    }\n}\n\npublic class YourClass\n{\n   public void DoSomething()\n   {\n       var channelFactory = new ChannelFactory();\n       Helper.FactoryFaulted(channelFactory, null);\n   }\n}	0
5863064	5863048	How to move bold text to another richtextbox?	richtextbox2.Rtf = richtextbox1.Rtf	0
4564817	4564650	How would I use HTMLAgilityPack to extract the value I want	HtmlDocument doc = new HtmlDocument();\ndoc.Load("file.htm"); //or whatever HTML file you have\nforeach(HtmlNode div in doc.DocumentNode.SelectNodes("//div[@class='name' and @id]")\n{\n   HtmlAttribute att = div["id"];\n   //Do something with att.Value\n}	0
34525397	34520541	How to run DNX 'console app' as a background service on Linux?	dnx run &	0
771693	771642	How to display difference between two dates as 00Y 00M	DateTime date1 = ...\nDateTime date2 = ...\n\n// date2 must be after date1\n\nTimeSpan difference = date2.Subtract(date1);\nDateTime age=new DateTime(tsAge.Ticks); \n\nint years = age.Years - 1;\nint months = age.Month - 1;\n\nConsole.WriteLine("{0}Y, {1}M", years, months);	0
24392362	24383874	EF sorting & paging - slow as ordered twice?	ORDER BY	0
13719496	13719415	creating a batch file in c#	Process myprocess = new Process();\n myprocess.StartInfo.FileName = @"C:\WHERE_EVER\bcdedit.exe";\n // I dont know the exact switch, but im sure you would be able to work this out.\n myprocess.StartInfo.Arguments = @"Install PortName=COM50 -set TESTSIGNING OFF";\n myprocess.Start();	0
7025698	7025300	How to make the following join?	FROM table1 t1, OUTER table2 t2\nWHERE t1.batch_no = t2.batch_no and ...	0
21398910	21398696	How to get index of list in foreach loop	foreach (ListItem li in chkUnitCategory.Items)\n{\n   li.Selected = chkUnitCategory.Items[0].Selected;\n}	0
33934084	33934027	How to ignore integer start with 0	int num = Convert.ToInt32(txtEmployeeID.Text);\nstring idNum = num.ToString("00000000");\ntxtEmployeeID.Text = idNum.ToString();	0
14694017	14693937	Windows Service, proper way to get installation path	System.IO.Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)	0
20994333	20993647	Double to String Conversion without losing exponential part	static void Main(string[] args)\n{\n     double d = 1234567890123456;\n     double d2 = 1;\n     double d3 = d + d2;\n\n     Console.WriteLine(d3);\n     Console.WriteLine(d3.ToString("R"));\n}	0
64167	64041	WinForms DataGridView font size	private void UpdateFont()\n    {\n        //Change cell font\n        foreach(DataGridViewColumn c in dgAssets.Columns)\n        {\n            c.DefaultCellStyle.Font = new Font("Arial", 8.5F, GraphicsUnit.Pixel);\n        }\n    }	0
29176996	29176642	How can I generate a tree with duplicate values	void makeTree() \n{\n  addNode(0, null);\n}\n\nfunction node addNode(nodeNumber, parent) \n{\n  nodeCollection nodes;\n  if (parent != null)\n    nodes = parent.nodes;\n  else\n    nodes = tree.nodes;\n\n  node addNode = nodes.add(nodeNumber);\n  for (int i = 1; i <= 5; i++)\n  {\n    bool alreadyexists = false;\n    node ancestor = addNode;\n    while (ancestor != null)\n    {\n      if (ancestor == childNode)\n      {\n        alreadyExists = true;\n        break;\n      }\n      ancestor = ancestor.parent;\n    }\n    if (!alreadyExists) \n      addNode(childNode, addNode);\n  }\n}	0
11972824	11972759	Calling a public method in Windows Forms	((MyMDIForm)this.MDIParent).displayInit();	0
21098334	21086969	how to show only my query result in datagridview c#	private void search_tlstb_txtbox_TextChanged(object sender, EventArgs e)\n    {\n        if (search_tlstb_txtbox.Text != string.Empty && owners_dgv.RowCount > 0)\n        {\n            for (int i = 0; i < owners_dgv.Rows.Count - 1; i++)\n            {\n                for (int j = 0; j < owners_dgv.Rows[i].Cells.Count; j++)\n                {\n                    if (owners_dgv.Rows[i].Cells[j].Value.ToString().Contains(search_tlstb_txtbox.Text))\n                    {\n                        owners_dgv.Rows[i].Visible = true;\n                        break;\n                    }\n                    else\n                    {\n                        owners_dgv.CurrentCell = null;\n                        owners_dgv.Rows[i].Visible = false;\n                    }\n                }\n            }\n        }\n        else\n            this.OwnersTBLTableAdapter1.Fill(this.rtmS_DS1.OwnersTBL);\n    }	0
11263335	11263107	how to get current page number in msword	Selection.Information(wdActiveEndPageNumber)	0
29574838	29574787	how to retrieve data from arraylist which store in object array formate in c#	Object[] obj = (Object[])aStru[nCtr]	0
19400698	19398813	LINQ to XML set value if it is not null otherwise use default value from the constructor	var constructor = typeof(Ignore).GetConstructor(new Type[]{typeof(string),typeof(IgnoreMode),typeof(IgnorePattern)});\nvar parameters = constructor.GetParameters(); // this return list parameters of selected constructor\nvar defaultIgnoreMode = (IgnoreMode)parameters[1].DefaultValue;\nvar defaultIgnorePattern = (IgnorePattern)parameters[2].DefaultValue;	0
30476272	30475053	How to return data in object format for web api?	[HttpGet]\npublic List<object> GetAllCompanies2()\n{\n    List<object> myCo = DefCompany.AllDefCompany2;         \n\n    object json = JsonConvert.SerializeObject(myCo);\n    return  json;\n}	0
5077599	5077475	Specifying a relative path	var chmFile = "CHM/test.chm";\nHelp.ShowHelp(ctrl, chmFile);	0
11648798	11648701	Making a control to be visible only for a particular amount of time in c#	System.Windows.Forms.Timer timer = new System.Windows.Forms.Timer();\ntimer.Interval = 3000;\ntimer.Tick += (source, e) => {label1.Visible = false; timer.Stop();};\ntimer.Start();	0
7674952	7674670	split string with a start and end character	string str = "|1 Test 1|This is my first line.|2 Test 2|This is my second line.";\nvar pattern = @"(\|(?:.*?)\|)";\nforeach (var m in System.Text.RegularExpressions.Regex.Split(str, pattern))\n{\n    Console.WriteLine(m);\n}	0
10852139	10852023	LINQ - convert group to array	var posttags = _db.PostTags\n    .GroupBy(x => x.TagID)\n    .OrderBy(x => x.Count())\n    // Take each group and pass the first tag of the group\n    .Select(g => g.First())\n    .Take(4)\n    .ToArray();	0
29160216	29160010	I want to convert columns to rows based on the condition	DECLARE @columns AS NVARCHAR(MAX), @query AS NVARCHAR(MAX)\n\nselect @columns = STUFF((SELECT ', ' + QUOTENAME(ColumnName) \n                    from YOURTABLE\n                    group by ColumnName, ColumnSequesnce\n                    order by ColumnSequesnce\n            FOR XML PATH(''), TYPE\n            ).value('.', 'NVARCHAR(MAX)') \n        ,1,1,'')\n\nset @query = N'SELECT ' + @columns + N' from \n             (\n                select RowSequence, ColumnValue, ColumnName\n                from YOURTABLE\n            ) x\n            pivot \n            (\n                max(ColumnValue)\n                for ColumnName in (' + @columns + N')\n            ) p '\n\nexec sp_executesql @query;	0
7566528	7566463	Two threads communicating	System.Windows.Threading.Dispatcher.CurrentDispatcher.Invoke(\n     new Action(() => \n         {\n               //do stuff with proba\n         }\n     ));	0
9026770	9026708	How can I obtain the id returned from the sp in my case	observationEntity.ObservationID	0
19844140	19843022	Add row to Datagridview with no columns	dataGridViewSummary.ColumnHeadersVisible = false;	0
13703680	13703477	Modify element property on key press	Attached Event	0
29999235	29999195	how to remove time part	DateTime start = Convert.ToDateTime(txtStart.Text);\nDateTime end = Convert.ToDateTime(txtEnd.Text);\n\nvar date1 = start.ToShortDateString();\nvar date2 = end.ToShortDateString();	0
32938993	32936053	How to Bold and Change Font Size of Chart Title	Title title = new Title();\n        title.Font = new Font("Arial", 14, FontStyle.Bold);\n        title.Text = "My Chart Title";\n        Chart1.Titles.Add(title);	0
17243646	17243543	Get JobDetail by string job name	Quartz.Collection.ISet<JobKey> jobKeys = scheduler.GetJobKeys(GroupMatcher<JobKey>.GroupEquals(SchedulerConstants.DefaultGroup));\njobKeys.Where(key => key.Name == "Your job name")	0
11580537	11580128	How to convert SID to String in .net	var sidInBytes = (byte[]) *somestuff*\nvar sid = new SecurityIdentifier(sidInBytes, 0);\n// This gives you what you want\nsid.ToString();	0
3299573	3299545	Linq-to-entities: Easy to find max value in SQL, but difficult in LINQ?	var query = from item in db.T\n            where item.FOO == 555\n            group item by item.BAR into g\n            select new { Bar = g.Key, Max = g.Max(x => x.FOO_INDEX) };	0
20421151	20420962	Cant get Gridview to refresh on update inside Update panel	{\n    DailySheetGV.DataSourceID = null;\n    DailySheetGV.EditIndex = -1;\n    DailySheetGV.DataBind();\n\n    UpdatePanel0.DataBind();\n    UpdatePanel0.Update(); // new line added to get updatepanel to refresh\n\n    SqlDataSource1.SelectCommand = "SELECT * FROM ReportTempTable";\n    DailySheetGV.DataSourceID = "SqlDataSource1";\n    DailySheetGV.EditIndex = -1;\n    DailySheetGV.DataBind();\n}	0
11430291	11429900	How to calculate and change treeview width	private void treeViewAfterExpand(object sender, TreeViewEventArgs e)\n{\n    int maxRight = treeView.ClientSize.Width;\n\n    if(e.Node.Nodes != null)\n        foreach (TreeNode node in e.Node.Nodes)\n        {\n            maxRight = Math.Max(maxRight, node.Bounds.Right);\n        }\n\n    treeView.ClientSize = new Size(maxRight, treeView.ClientSize.Height);\n}	0
3028963	3028680	Dependency Properties, change notification and setting values in the constructor	private bool SupressCalculation = false;\nprivate void recalculate() \n{ \n    if(SupressCalculation)\n        return;\n    // Using A, B, C do some cpu intensive caluclations \n} \n\n\npublic DPChangeSample(int a, int b, int c) \n{\n    SupressCalculation = true; \n    SetValue(AProperty, a); \n    SetValue(BProperty, b); \n    SupressCalculation = false;\n    SetValue(CProperty, c); \n}	0
21711640	21221470	Windows Store App 8.1 Crashes. PRISM	protected override IList<SettingsCommand> GetSettingsCommands()\n{\n    return new List<SettingsCommand>();\n}	0
5205933	5096096	C# JSON decoding using Web Matrix helpers	string input = "{ \"foo\": true, \"array\": [ 42, false, \"Hello!\", null ] }";\ndynamic value = new JsonReader().Read(input);\n// verify that it works\nConsole.WriteLine(value.foo); // true\nConsole.WriteLine(value.array[0]); // 42\nConsole.WriteLine(value.array.Length); // 4\n\nstring output = new JsonWriter().Write(value);\n// verify that it works\nConsole.WriteLine(output); // {"foo":true,"array":[42,false,"Hello!",null]}	0
8041445	8041329	Refuse the connection to a service	[ServiceContract(SessionMode = SessionMode.Required)]\npublic interface IMyServiceContract\n{\n   ...\n}\n\n[ServiceBehavior(InstanceContextMode = InstanceContextMode.PerSession)]\npublic class MyServiceImplementation: IMyServiceContract\n{\n   ...\n}	0
16734675	16725848	How to split text into words?	var text = "'Oh, you can't help that,' said the Cat: 'we're all mad here. I'm mad. You're mad.'";\nvar punctuation = text.Where(Char.IsPunctuation).Distinct().ToArray();\nvar words = text.Split().Select(x => x.Trim(punctuation));	0
32281613	32268822	Paste DataObject into Word C#	object oMissing = System.Reflection.Missing.Value;\n                    object oEndOfDoc = "\\endofdoc";\n                    Word._Application oWord;\n                    Word._Document oDoc;\n                    oWord = new Word.Application();\n                    oDoc = oWord.Documents.Add(ref oMissing, ref oMissing,\n                        ref oMissing, ref oMissing);\n                    Word.Paragraph oPara1;\n                    oPara1 = oDoc.Content.Paragraphs.Add(ref oMissing);\n                    oPara1.Range.Paste();\n                    oDoc.SaveAs(docOutput);	0
26203818	26203752	C# Order of Operations Syntax Explanation	int[] myArray = { 0, 1, 2, 3, 4, 5, 6};\nint myValue = myArray[3]; // Value is 3\nint preDays = myValue - 2; // Value is 1	0
18651390	18651329	How data can shown in datagridview of selected date from date time picker?	private void dtTmPkrWtr_ValueChanged(object sender, EventArgs e)\n{            \n       LoadGridData(dateTimePicker1.Value);\n}\n\nprivate void btnDisplay_Click(object sender, EventArgs e)\n{ ? ? ? ? ? ?\n? ? ? ?LoadGridData(DateTime.Now); ? ? \n}\n\nprivate void LoadGridData(DateTime selectedDate)\n{\n    String query = "SELECT sno,currDate,WtrNm,Type,No FROM WtrTblAllot WHERE currDate = @SelectedDate";\n    SqlCommand command = new SqlCommand(query, con);\n    command.Parameters.AddWithValue("@SelectedDate", dateTimePicker1.Value);\n    SqlDataAdapter da = new SqlDataAdapter(command);\n    DataSet ds = new DataSet();\n    da.Fill(ds);\n    dgvWtrAllot.DataSource = ds.Tables[0];\n}	0
33685202	33685153	How to add an image to a Code Generated MSWord with C#	// Create a .docx file\nusing (DocX document = DocX.Create(@"Example.docx"))\n{\n  // Add an Image to the docx file\n   Novacode.Image img = document.AddImage(@"Donkey.jpg");\n\n   // Insert an emptyParagraph into this document.\n   Paragraph p = document.InsertParagraph("", false);\n\n  #region pic1\n  Picture pic1 = p.InsertPicture(img.Id, "Donkey", "Taken on Omey island");\n\n   // Set the Picture pic1?s shape\n   pic1.SetPictureShape(BasicShapes.cube);\n\n   // Rotate the Picture pic1 clockwise by 30 degrees\n   pic1.Rotation = 30;\n    #endregion\n\n   #region pic2\n   // Create a Picture. A Picture is a customized view of an Image\n   Picture pic2 = p.InsertPicture(img.Id, "Donkey", "Taken on Omey island");\n\n   // Set the Picture pic2?s shape\n   pic2.SetPictureShape(CalloutShapes.cloudCallout);\n\n  // Flip the Picture pic2 horizontally\n   pic2.FlipHorizontal = true;\n   #endregion\n\n   // Save the docx file\n   document.Save();\n}// Release this document from memory.	0
15650296	15646768	Range for int treated as string	// convert the value to a number for number inputs, and for text for backwards compability\n        // allows type="date" and others to be compared as strings\n        if ( /min|max/.test( method ) && ( type === null || /number|range|text/.test( type ) ) ) {\n            value = Number(value);\n        }\n\n        if ( value ) {\n            rules[method] = value;\n        } else if ( type === method && type !== 'range' ) {\n            // exception: the jquery validate 'range' method\n            // does not test for the html5 'range' type\n            rules[method] = true;\n        }	0
9290707	9290479	Setting control to be content of several controls	public partial class MainWindow : Window\n{\n    TextBlock textBlock = new TextBlock();\n    public MainWindow()\n    {\n        InitializeComponent();\n    }\n\n    private void Button_Click(object sender, RoutedEventArgs e)\n    {\n        TestWindow testWindow = new TestWindow();\n        testWindow.Content = textBlock;\n        testWindow.Closing += HandleTestWindowClosing;\n        testWindow.Show();\n    }\n\n    void HandleTestWindowClosing(object sender, System.ComponentModel.CancelEventArgs e)\n    {\n        var testWindow = sender as TestWindow;\n        if(testWindow!=null)\n        {\n            testWindow.Content = null;\n            testWindow.Closing -= HandleTestWindowClosing;\n        }\n    }\n}	0
10749619	10716617	Nservicebus doesn't store subscribers in msmq	.IsTransactional(true)	0
929269	929240	ASP.NET: How to apply CSS class for a Table generated in C# codebehind	iTblCart.Attributes.Add("Class", "clsTradeInCart");	0
21285784	21285304	Sitecore serialized items with Git autocrlf	* text=auto\n\n# These files are text and should be normalized (convert crlf => lf)\n*.cs      text diff=csharp\n*.xaml    text\n*.csproj  text\n*.sln     text\n*.tt      text\n*.ps1     text\n*.cmd     text\n*.msbuild text\n*.md      text\n\n# TDS files should be treated as binary\n*.item -text	0
23103771	23051980	Office Open XML SDK Spreadsheet how to display currency symbol in front of number?	// Currency\n        stylesheet.GetFirstChild<DocumentFormat.OpenXml.Spreadsheet.NumberingFormats>().InsertAt<DocumentFormat.OpenXml.Spreadsheet.NumberingFormat>(\n           new DocumentFormat.OpenXml.Spreadsheet.NumberingFormat()\n           {\n               NumberFormatId = 164,\n               FormatCode = "\"" + System.Globalization.CultureInfo.CurrentUICulture.NumberFormat.CurrencySymbol + "\"\\ " + "#,##0.00"\n           },\n           0);	0
19660437	19659984	C# Linq GroupBy, get list of a column in each group	var sales = db.Sales\n    .Where(sale => sale.DateOfSale > startDate && sale.DateOfSale < endDate)\n    .GroupBy(\n        sale => new {sale.ItemID, sale.EstimatedShipping},\n        sale => sale.ActualShipping)\n    .ToList();	0
19128319	19128026	Monotouch - Changing size and position of table view	MainScreen controller;\n        UINavigationController navcontroller;\n\n        public override bool FinishedLaunching (UIApplication app, NSDictionary options)\n        {\n\n            // create a new window instance based on the screen size\n            window = new UIWindow (UIScreen.MainScreen.Bounds);\n            controller = new MainScreen ();\n\n            var initialControllers = new List<UIViewController>();\n            initialControllers.Add (controller);\n\n            navcontroller = new UINavigationController ();\n            navcontroller.ViewControllers = initialControllers.ToArray ();\n            window.RootViewController = navcontroller;\n            window.MakeKeyAndVisible ();\n            return true;\n        }	0
32375724	32375551	Need to use a VAR inside an If	var ContactDetails = string.Empty;\nif (Session["Step01Tel"] != "")\n{\n     ContactDetails = Step01TelLabel.Text + " " + Session["Step01Tel"].ToString();\n}\nelse if (Session["Step01Email"] != "")\n{\n     ContactDetails = Step01EmailLabel.Text + " " + Session["Step01Email"].ToString();\n}	0
15251612	15017506	Using FileSystemWatcher to monitor a directory	private void watch()\n{\n  FileSystemWatcher watcher = new FileSystemWatcher();\n  watcher.Path = path;\n  watcher.NotifyFilter = NotifyFilters.LastWrite;\n  watcher.Filter = "*.*";\n  watcher.Changed += new FileSystemEventHandler(OnChanged);\n  watcher.EnableRaisingEvents = true;\n}	0
33365764	33353121	POST JSON to webservice using WebClient C#	WebClient client = new WebClient();\nstring result = client.UploadValues("http://Server.com/MyService/Account/Register", new NameValueCollection()\n{\n{"Name","Lorem"},\n{"Email","abc@abc.com"},\n{"interest","[\"1\"]"},\n{"sectors","[\"1\",\"2\"]"},\n{"interest","false"}\n});	0
5132714	5132701	In SQL Query ,How to set table name	SqlDataAdapter da = new SqlDataAdapter(...);\nDataSet ds = new DataSet();\nDataTableMapping dtm1, dtm2, dtm3;\ndtm1 = da.TableMappings.Add("Table", "Employees"); \ndtm2 = da.TableMappings.Add("Table1", "Products");\ndtm3 = da.TableMappings.Add("Table2", "Orders");\nda.Fill(ds);	0
26760340	26741440	How to check with linq to sql that all users of a group have a user role?	from user in session.Query<User>()\n                      where user.Group == @group\n                      group user by new { RoleId = user.UserRole.Id } into groupedUsers\n                      select groupedUsers.Select(t => t.UserRole.Id).Distinct().Count() < 2 || groupedUsers.Where(t => t.UserRole == userRole).Any()	0
9078330	9077722	How to enable navigation buttons of jQuery grid in mvc3 and assign buttons to specific links?	caption: 'Device list'\n    }).navGrid("#pager, { add: false, edit: false, del: false }	0
5887118	5887050	how to extract a property value from a object sender?	public void seektomediaposition_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)\n    {\n\nstring name = Convert.ToString(e.Source.GetType().GetProperty("Name").GetValue(e.Source, null));\nMessageBox.Show(name);\nif(name=="seektomediaposition")\n  // whatever is the code\nif(name=="seektomediaposition2")\n  // whatever is the code\n\n    }	0
19332433	19332417	Passing arguments from static Main in C#	static void Main(string[] args)\n{\n    Input input = new Input();\n    input.debug = true;\n\n    SpaceApiTest st = new SpaceApiTest();\n    st.GetIp(ref input); //don't forget ref keyword.\n}\n\npublic int GetIp(ref Input input)\n{\n    input.ip.Add("192.168.119.2");\n    return 0;    \n}	0
23565546	23565498	simple.data orm, how to search by date?	list.Where(_db.DocumentLog.CreatedDate >= dt \n        && _db.DocumentLog.CreatedDate < dt.AddDays(1));	0
12661470	12660497	How do multi rows insert with MySqlCommand and prepare statement?(#C)	using (var connection = new MySqlConnection("your connection string"))\n{\n    connection.Open();\n    // first we'll build our query string. Something like this :\n    // INSERT INTO myTable VALUES (NULL, @number0, @text0), (NULL, @number1, @text1)...; \n    StringBuilder queryBuilder = new StringBuilder("INSERT INTO myTable VALUES ");\n    for (int i = 0; i < 10; i++)\n    {\n        queryBuilder.AppendFormat("(NULL,@number{0},@text{0}),", i);\n        //once we're done looping we remove the last ',' and replace it with a ';'\n        if (i == 9)\n        {\n            queryBuilder.Replace(',', ';', queryBuilder.Length - 1, 1);\n        }\n    }\n\n\n    MySqlCommand command = new MySqlCommand(queryBuilder.ToString(), connection);\n    //assign each parameter its value\n    for (int i = 0; i < 10; i++)\n    {\n        command.Parameters.AddWithValue("@number" + i, i);\n        command.Parameters.AddWithValue("@text" + i, "textValue");\n    }\n\n    command.ExecuteNonQuery();\n}	0
17081392	17080675	Sort a List<string> comparing with a string	list = (from str in list\n        let idx = str.IndexOf(keyword, StringComparison.OrdinalIgnoreCase)\n        let change = idx != 0 ? idx : int.MinValue\n        orderby change\n        select str).ToList();	0
15223734	15222749	how to get assemblyinfo into XAML in windows 8?	var myPackage = Windows.ApplicationModel.Package.Current;	0
11770676	11770630	JSON to XML Convertion	XmlDocument doc = (XmlDocument)JsonConvert.DeserializeXmlNode(json, "friends");	0
33223619	32657241	Web deploy publishes wrong version of assembly	obj\Release\Package\PackageTmp\bin	0
23313285	23311645	Deserialize XML into Object	[System.Xml.Serialization.XmlTypeAttribute (Namespace = "http://sdb.amazonaws.com/doc/2009-04-15/")]\n[System.Xml.Serialization.XmlRootAttribute ("ListDomainsResponse", Namespace = "http://sdb.amazonaws.com/doc/2009-04-15/")]\npublic class ListDomainsResponse  : Response\n{\n    public ListDomainsResult ListDomainsResult { get; set; }\n}\n\n[System.Xml.Serialization.XmlTypeAttribute (Namespace = "http://sdb.amazonaws.com/doc/2009-04-15/")]\n[System.Xml.Serialization.XmlRootAttribute (Namespace = "http://sdb.amazonaws.com/doc/2009-04-15/")]\npublic class ListDomainsResult\n{\n    [System.Xml.Serialization.XmlElementAttribute ("DomainName")]\n    public string[] DomainName { get; set; }\n\n    public string NextToken { get; set; }\n}	0
9099432	9099394	convert a string length to a hex value to add to List<byte>	lb.Add((byte)theLength);	0
26916940	26914174	How to set Auto-Tagging to true through Google Adwords API	private void updateAdwordsCustomer(AdWordsUser adwordsUser)\n{\nCustomerService CustSer = (CustomerService)adwordsUser.GetService(\n        AdWordsService.v201409.CustomerService);\n\n\n    Customer customer = new Customer();\n    customer.autoTaggingEnabled = true;\n\n    var s = CustSer.mutate(customer);\n}	0
7576089	7576020	80 byte wrapped format text file?	writer.Write("{0}\r\n", record);\nwriter.Write("{0}\n", record);	0
6509378	6509291	Get the number of rows of data with SpreadSheetGear?	IWorksheet.UsedRange	0
18530817	18530627	Nullable integer values from reader	mb.Mem_ResAdd4 = reader["Mem_ResAdd4"] == System.DBNull.Value ? null : (string)reader["Mem_ResAdd4"];\n//\n    mb.Mem_ResPin = reader["Mem_ResPin"]== System.DBNull.Value ? default(int):(int)reader["Mem_ResPin"]	0
11515811	11455478	Linking the model in weka with c#	weka.classifiers.functions.MultilayerPerceptron cl = (weka.classifiers.functions.MultilayerPerceptron)weka.core.SerializationHelper.read("..\\..\\MLPModel.model");	0
10350102	10349753	Converting a string of ASCII into normal string C#	private static string GetStringFromAsciiHex(String input)\n{\n    if (input.Length % 2 != 0)\n        throw new ArgumentException("input");\n\n    byte[] bytes = new byte[input.Length / 2];\n\n    for (int i = 0; i < input.Length; i += 2)\n    {\n        // Split the string into two-bytes strings which represent a hexadecimal value, and convert each value to a byte\n        String hex = input.Substring(i, 2);\n        bytes[i/2] = Convert.ToByte(hex, 16);                \n    }\n\n    return System.Text.ASCIIEncoding.ASCII.GetString(bytes);\n}	0
13385946	12748438	Binding keeps my controls in memory even after I'm done with them. How can I free them?	jp.Owner = propertiesWindowOwner;	0
11612034	11611835	How can I read the XML file Node attributes and Child node attributes values?	XDocument xDoc = XDocument.Parse(xml);\nvar result = xDoc.Descendants("B")\n    .Select(b => new\n    {\n        BValue = b.Attribute("value").Value,\n        Alg = b.Element("Hash").Attribute("algo").Value,\n        AlgValue = b.Element("Hash").Attribute("value").Value,\n    })\n    .ToArray();	0
4128616	4128584	GetHashCode Equals implementation for a class in C#	Name    Email    Hash\n  n1       e1      h1\n  n2       e1      h1 (because emails are equal\n  n2       e2      h1 (because names are equal to previous)	0
7553590	7553561	How to remove a string from a string	c = c.Replace(b, "");	0
15520745	15520601	Validate bool methods (constraints) in list	List<Func<bool>> constraints = new List<Func<bool>> ();\n\n// add your functions\nconstraints.Add(check1);\nconstraints.Add(check2);\n\n// and then determine if all of them return true\nbool allTrue = constraints.All (c => c());\n\n// or maybe if any are true\nbool anyTrue = constraints.Any(c => c());	0
1363596	1357231	Restrict plugin access to file system and network via appdomain	System.Security.PermissionSet ps = \n    new System.Security.PermissionSet(System.Security.Permissions.PermissionState.None);\nps.AddPermission(new System.Security.Permissions.FileIOPermission(System.Security.Permissions.FileIOPermissionAccess.NoAccess, "C:\\"));\nSystem.Security.Policy.PolicyLevel pl = System.Security.Policy.PolicyLevel.CreateAppDomainLevel();\npl.RootCodeGroup.PolicyStatement = new System.Security.Policy.PolicyStatement(ps);\nAppDomain.CurrentDomain.SetAppDomainPolicy(pl);\nSystem.Reflection.Assembly myPluginAssembly = AppDomain.CurrentDomain.Load("MyPluginAssembly");	0
32465002	32464921	c# look in text file for a certain string if exists do something	string filename=@"D:\file.txt";\nstring value="your value"\nvar content = System.IO.File.ReadAllText(filename);\nif (content.Contains(value))\n    this.Button1.Enabled = false;\nelse\n    System.IO.File.AppendAllLines(filename, new string(){value} );	0
10887169	10887146	How to get all the rows from a table	var allRecords = context.SomeTable;	0
6184790	6184743	How to make the User's Control's BackGround transparent?	this.BackColor = Color.Transparent;	0
8149030	8148942	How to assign the link path out of the application in asp.net?	file:///c:/Documents and Settings/ITEMS....	0
7947478	4949205	How do i use linq as datasource for a Microsoft report	var exams = (from appointment in appointments\n               select new\n                    {\n                          ((Exam)appointment.CustomFields["Field"]).Id,\n                          ((Exam)appointment.CustomFields["Field"]).Name,\n                          ((Exam)appointment.CustomFields["Field"]).Date,\n                                     ((Exam)appointment.CustomFields["Field"]).Period.StartTime,\n                                     ((Exam)appointment.CustomFields["Field"]).Period.EndTime,\n                                     Location = ((Exam)appointment.CustomFields["Field"]).Location.Name\n                                });\n\n        SetDataSource(exams);\n\n\n    private void SetDataSource(object exams)\n    {          \n        scheduleBindingSource.DataSource = exams;\n        this.rpTTViewer.ProcessingMode = Microsoft.Reporting.WinForms.ProcessingMode.Local;\n        this.rpTTViewer.RefreshReport(); \n    }	0
32377162	32377107	How to set right BackGroundImage in C#?	ImageLayout.Tile	0
16523918	16523654	Display a number with culture info but without formatting	num.ToString("###,###,###.####");	0
31049272	31049087	Parsing XML by position using XDocument	var list = doc.Descendants("Name").Select(MakeBreakfast).ToList();\n...\n\nstatic Breakfast MakeBreakfast(XElement nameElement)\n{\n    string name = (string) nameElement;\n    var nextElement = nameElement.ElementsAfterSelf().FirstOrDefault();\n    string description = \n        nextElement != null && nextElement.Name.LocalName == "Description"\n        ? (string) nextElement\n        : null;\n    return new Breakfast { Name = name, Description = description };\n}	0
4347313	4339932	Messaging interop between c# and VB6 mdi applications	public struct COPYDATASTRUCT\n{\n    public IntPtr dwData;\n    public UInt32 cbData;\n    [MarshalAs(UnmanagedType.LPStr)]\n    public string lpData;\n}  \n\n[DllImport("User32.dll", EntryPoint = "SendMessage")]\n        public static extern IntPtr SendMessage(IntPtr hWnd, int Msg, int wParam, ref COPYDATASTRUCT lParam);\n\nIntPtr result;\n\n            byte[] sarr = System.Text.Encoding.Default.GetBytes(sendMsg);\n            int len = sarr.Length;\n            COPYDATASTRUCT cds;\n\n            cds.dwData = (IntPtr)3;\n            cds.lpData = sendMsg;\n            cds.cbData = (UInt32)len + 1;\n            result = SendMessage(hwndTarget, WM_COPYDATA, 0, ref cds);	0
23641217	23641147	How do I create a generic repository with entity framework?	return entityContext.Set<T>().Add(entity);	0
7055359	7055322	How to suspend execution for a random amount of time at random intervals	private DateTime GetNextSleep()\n{\n    // Between 3 and 20 minutes, adjust as needed.\n    return DateTime.Now + new TimeSpan(0, 0,\n        RandomNumber(60 * 3, 60 * 20));\n}\n\nprivate void button1_Click(object sender, EventArgs e)\n{\n    //this section sends data to the number validation function\n    string ValidateNum = NumberOfItems.Text;\n    NumberCheck(ValidateNum);\n    int Clicks = Convert.ToInt16(NumberOfItems.Text);\n\n    DateTime nextSleep = GetNextSleep();\n\n    for (int i = 1; i < Clicks; i++)\n    {\n        int SleepTime1 = RandomNumber(819, 1092);\n        DoMouseClickLeft();\n        Thread.Sleep(SleepTime1);\n        DoMouseClickLeft();\n        Thread.Sleep(SleepTime1);\n\n        if (DateTime.Now >= nextSleep)\n        {\n            // Sleep between 1 and 5 minutes, adjust as needed.\n            Thread.Sleep(new TimeSpan(0, 0,\n                RandomNumber(60 * 1, 60 * 5)));\n\n            nextSleep = GetNextSleep();\n        }\n    }\n}	0
31989000	31986753	Convert to Sentence Case Using Regex and C#	using System;\nusing System.Text.RegularExpressions;\n\npublic class Program\n{\n    public static void Main()\n    {\n        string toConvert = "<BOLD_HTML_TAG>lorem ipsum is simply dummy</BOLD_HTML_TAG> text of the printing and typesetting industry."+\n                "<PARAGRAPH_TAG>LOREM ipsum has been the industry's standard dummy "+\n                "text ever since the 1500s</PARAGRAPH_TAG>.";\n        var sentenceRegex = new Regex(@"(?<=<(?<tag>\w+)>).*?(?=</\k<tag>>)", RegexOptions.ExplicitCapture);\n        var result = sentenceRegex.Replace(toConvert, s => s.Value.Substring(0,1).ToUpper()+s.Value.ToLower().Substring(1));\n\n        Console.WriteLine(toConvert + "\r\n" + result);\n    }\n}	0
21130539	21130039	How to change my networkstream code to write the data directly to file	byte[] buffer = new byte[1024];\n    int numberOfBytesRead = 0;\n\n    FileStream fs = new FileStream(@"C:\file.png", FileMode.Create, FileAccess.Write);\n    do\n    {\n        numberOfBytesRead = serverStream.Read(buffer, 0, buffer.Length); //Read from network stream\n        fs.Write(buffer, 0, numberOfBytesRead);\n    } while (serverStream.DataAvailable);\n    fs.Close();	0
9158746	9157710	extend log4net SmtpAppender for dynamic To email address	Add this to your Web.Config:\n\n <appSettings>\n  <add key="log4net.Internal.Debug" value="true" />\n </appSettings>\n <system.diagnostics>\n  <trace autoflush="true">\n   <listeners>\n    <add\n     name="textWriterTraceListener"\n     type="System.Diagnostics.TextWriterTraceListener"\n     initializeData="c:\\log4net.txt" />\n   </listeners>\n  </trace>\n </system.diagnostics>	0
7160488	7160414	TCP Client to Fill a DataTable which populates a bound DataGridView, UI Unresponsive	private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)\n    {\n        //do your time consuming stuff\n        while (m_Active)\n        {\n            Thread.Sleep(100);\n            int lData = m_Stream.Read(m_Buffer, 0,\n                  m_Client.ReceiveBufferSize);\n            String myString = Encoding.UTF7.GetString(m_Buffer);\n            e.result = myString.Substring(0, lData);\n\n            ParseString(e.Result.ToString());\n        }\n\n    }\n\n private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)\n    {\n        //update your UI if needed\n    }	0
8310893	8310869	How to add Item to Static Property Typeof List?	public class Util\n{\n  static Util()\n  {\n     PersonList = new List<Person>();\n  }\n  static public List<Person> PersonList{get;set;}\n}	0
31219020	31218753	Sort Alphabetic ObservableCollection binded to ListBox	_scanResultItems = _scanResultItems.OrderBy(item => item.Name).ToList();	0
1615393	1615380	How can I know the day name from a selected date?	//default locale\nSystem.DateTime.Now.DayOfWeek.ToString();\n//localized version\nSystem.DateTime.Now.ToString("dddd");	0
29282946	29282496	How to properly setup a class structure to properly de-serialize XML?	public enum CurrencyType\n{\n    USD = 0,\n    EUR = 1 //etc..\n}\npublic class Money\n{\n    public CurrencyType CurrenyType { get; set; }\n    public decimal Value { get; set; }\n\n    public Money(XElement element)\n    {\n        if (element.Name.LocalName != "Money")\n            throw new Exception(...);\n        var aCurrency = element.Attribute("currency");\n        this.CurrencyType = aCurrency == null || string.IsNullOrEmpty(aCurrency.Value) ? CurrencyType.USD : (CurrencyType)Enum.Parse(typeof(CurrencyType), aCurrency.Value);\n        this.Value = element != null && !string.IsNullOrEmpty(element.Value) ? element.Value : 0;\n    }\n}	0
16760336	16759679	Accessing embedded resources in C++/CLI	auto resourceAssembly = Reflection::Assembly::GetExecutingAssembly();\n// .Resources is the name generated by resxgen, e.g., from the input file name Resources.resx\nauto resourceName = resourceAssembly->GetName()->Name + ".Resources"; \nauto resourceManager = gcnew Resources::ResourceManager(resourceName, resourceAssembly);\nauto String1 = cli::safe_cast<String^>(resourceManager->GetObject("String1"));	0
25247740	25247635	Setting the text in the top left header cell is a Data Grid View	dataGridView.TopLeftHeaderCell.Value = "Your Text";	0
4935526	4935344	Read First Node from XMLDocument	XmlDocument xml = new XmlDocument();\n        xml.LoadXml("<Message><Event1 Operation=\"Amended\" Id=\"88888\"> Other XML Text</Event1></Message>");\n        Debug.WriteLine(xml.DocumentElement.ChildNodes[0].Name);\n        Debug.WriteLine(xml.DocumentElement.ChildNodes[0].Attributes["Operation"].Value);	0
8197994	8197919	Trouble with Regex in C#	int count = 0;\n    foreach (var c in subjectString)\n    {\n        if (!char.IsLetterOrDigit(c)) count++;\n    }\n    Console.WriteLine("{0}", count);	0
13239997	13239924	How do I insert a string into a JsonArray?	JsonArray jsonArray= new JsonArray();\njsonArray.Add(JsonValue.CreateStringValue(myString));	0
13234625	13233715	Connect to SQL Server 2008 Database via C#	string sCon = @"Data Source=David-PC; Initial Catalog=ZarTrackDB; Integrated Security = true";\nSqlConnection dbConn;\ndbConn = new SqlConnection(sCon);\ndbConn.Open();	0
18577982	18577955	Get selected Object from Combobox	private void ComboBox1_SelectedIndexChanged(object sender, System.EventArgs e)\n{\n     if(ComboBox1.SelectedItem==null) return;\n     var b= (Bird) ComboBox1.SelectedItem;\n     if(b!=null)\n         Console.WriteLine(b.Gender +" - " + b.Name +" - " + b.Risk + " - " +b.Reference);\n}	0
27382543	27382451	How to end a process using C#	foreach (var process in Process.GetProcessesByName("chromedriver"))	0
25018500	25014687	Map query expression from DTO to Entity Object	var dtos = context.Employees.Where(e => e.IsActive)\n    .Project().ToArray<EmployeeShowViewModel>();	0
18029926	18029881	How to pass multiple parameter in Task	public Form1()\n{\n    InitializeComponent();\n\n    Task task = new Task(() => this.GetPivotedDataTable("x",DateTime.UtcNow,1,"test"));\n    task.Start();\n}\n\npublic void GetPivotedDataTable(string data, DateTime date, int id, string flag)\n{\n    // Do stuff\n}	0
33799953	33799733	System.XML Read values into an array	var ids = XElement.Parse(mystring)\n    .Descendants("nodeId")\n    .Select(x => x.Value); // or even .Select(x => int.Parse(x.Value));\n\nforeach(var id in ids) {\n    Console.WriteLine(id);\n}	0
15873978	15847367	Read a huge Excel column from C#	public void test()\n{\n    object[,] RaWData = null;\n\n    dynamic range = xlWorkSheet.UsedRange;\n\n    //i am unsure here about the correct order - I do not work with excel at Work, so you might have to change the following lange, if columns needs to be before rows or so\n    RaWData = range.value2;\n\n    //I am using a list here, because Lists are a lot easier to work with then simple arrays\n    List<List<string>> RealData = new List<List<string>>();\n\n    //start at 1  because the excel-delivered array do not have values at index 0 - this is the only 1-based array you will ever encounter in .net\n    for (x = 1; x <= Information.UBound(RaWData, 1); x++) {\n        List<string> templist = new List<string>();\n        for (y = 1; y <= Information.UBound(RaWData, 2); y++) {\n            templist.Add(RaWData[x, y].ToString());\n        }\n        RealData.Add(templist);\n    }\n\n    //you should be finished here...\n}	0
29812505	29812367	How can I make that approach's opposite	public partial class Form1 : Form\n{\n    public delegate void IdentityUpdateHandler(object sender, EventArgs e);\n    public event IdentityUpdateHandler IdentityUpdated;\n\n    public Form1()\n    {\n        InitializeComponent();\n\n    }\n\n    private void button1_Click(object sender, EventArgs e)\n    {\n        Form2 form2 = new Form2();\n        form2.Show();\n        IdentityUpdated(this, new EventArgs());\n    }\n}\n\npublic partial class Form2 : Form\n{\n    public Form2()\n    {\n        InitializeComponent();\n        Form1 form1 = (Form1)Application.OpenForms["Form1"];\n        form1.IdentityUpdated += Form1OnIdentityUpdated;\n    }\n\n    private void Form1OnIdentityUpdated(object sender, EventArgs eventArgs)\n    {\n        MessageBox.Show("received");\n    }\n}	0
12320908	12320879	How to know if PropertyInfo is MEF import	GetCustomAttributes()	0
4903116	4887479	How to write a general function to create a list of Dto from an excel file?	public interface IWorksheetHandler\n{\n    void LoadFromWorksheet(Worksheet worksheet);\n}\n\npublic class DtoLoader\n{\n     public static IList<T> CreateLookupList<T>(string currentFileName) where T:IWorksheetHandler, new()\n     {\n          List<T> items = new List<T>();\n          Workbook internalWorkBook = Workbook.Load(currentFileName);\n          foreach (Worksheet worksheet in internalWorkBook.Worksheets)\n          {\n              T dto = new T();\n              dto.LoadFromWorksheet(worksheet );\n              items.Add(dto);\n          }\n          return items;\n      }\n}	0
6634974	6634941	Time based Method execution in C#	public class Timer1\n {\n\n     public static void Main()\n     {\n         System.Timers.Timer aTimer = new System.Timers.Timer();\n         aTimer.Elapsed+=new ElapsedEventHandler(OnTimedEvent);\n         // Set the Interval to 5 seconds.\n         aTimer.Interval=5000;\n         aTimer.Enabled=true;\n\n         Console.WriteLine("Press \'q\' to quit the sample.");\n         while(Console.Read()!='q');\n     }\n\n     // Specify what you want to happen when the Elapsed event is raised.\n     private static void OnTimedEvent(object source, ElapsedEventArgs e)\n     {\n         Console.WriteLine("Hello World!");\n     }\n }	0
25954834	25954012	How to save a pdf with the objects property	var filename = string.Format(@"C:\Users\texas_000\Desktop\TexasExterior\TexasExterior\JobSetupPdfs\{0}{1}.pdf", job.JobName, job.JobDate);\n    document.Save(filename);	0
21884898	21884668	Copy one datatable into another	foreach (DataRow sourcerow in dtOld.Rows)\n{\n    DataRow destRow = dtNew.NewRow();\n    destRow["D"] = sourcerow["c"];\n    destRow["F"] = sourcerow["E"];\n    dtNew.Rows.Add(destRow);\n}	0
14231880	14231825	How to optimize true states on assignation	private void MyMethod(List<PictureBox> pictureBoxes)\n{\n    foreach (var pictureBox in pictureBoxes)\n    {\n        var user = ReturnUser(pictureBox);\n        if (user != null)\n        {\n             usersFirstRow.Add(user);\n             // This line not needed: user = null; \n        }\n    }\n}\n\nList<PictureBox> pictureBoxes = \n    new List<PictureBox>() { pictureBoxUpOne, pictureBoxUpTwo }\n\nMyMethod(pictureBoxes);	0
9258065	9255367	How to select aggregate of multiple columns (no group by)?	var fromDate = new DateTime(2011, 02, 01);\nvar toDate = new DateTime(2012, 02, 01);\nvar esql = @"select \n          sum(it.TransactionCount) as SumOfTransactionCount,\n          sum(it.RejectCount) as SumOfRejectCount\n               from ActivityCaches as it\n               where it.Date > @fromDate and it.Date <= @toDate";\nvar query = CreateQuery<DbDataRecord>(esql,\n        new ObjectParameter("fromDate", fromDate) ,\n        new ObjectParameter("toDate", toDate));	0
9491914	9491858	Convert Unsigned Long to an string in ascii	std::string convert(unsigned long value, unsigned long base) {\n    std::string rc;\n    do {\n        rc.push_back("0123456789abcde"[value % base]);\n    } while (base - 1? value /= base: value--);\n    std::reverse(rc.begin(), rc.end());\n    return rc;\n}	0
28297517	28297331	How can modify the same variable when I pass it as parameter on a method?	class ClassA\n{\n    private void myMthod()\n    {\n        MyClassB myClassB = new ClasB();\n        CustomObject myCustomObject = new CustomObject();\n        myClassB.MyMethodOnClassB(ref myCustomObject);\n\n        if(miCustomObject == null)\n        {\n             //code in case of null\n        }\n        else\n        {\n            //code in case of not null\n        }\n    }\n}\n\n\nclass ClassB\n{\n    CustomObject _myCustomObjectOnB;\n\n    public ClassB(CustomObject paramCustomObject)\n    {\n        _myCustomObjectOnB = paramCustomObject;\n    }\n\n    public MyMethodOnClassB(ref CustomObject customObject)\n    {\n        _myCustomObject = customObject = null;\n    }\n}	0
13282337	13282273	How to get index of sender item from "multiplexed" event handler?	private void AddImages(List<string> photoUrls)\n{\n    PhotosView.Items.Clear();\n    int nextIndex = 0;\n    foreach (var url in photoUrls)\n    {\n        int n = nextIndex++;\n        var image = new Image();\n        var source = new BitmapImage(new Uri(url));\n        source.DownloadProgress += (sender, args) => \n        {\n            Debug.WriteLine("image {0} progress={1}%", n, args.Progress);\n        };\n        image.Source = source;\n        image.Tag = source;\n        PhotosView.Items.Add(image);\n    }\n}	0
5331351	5331291	CSharp: How do I make a SQL declare/set command persist in a SQLConnection?	command.Parameters.AddWithValue("@InstitutionId",this.InstitutionId);	0
33435262	33434718	How to group a list of connected pairs	var groups = new List<List<int>>();\nforeach (var con in connectionList)\n{\n    if(!groups.Any(g => g.Contains(con.X) || g.Contains(con.Y)))\n    {\n        groups.Add(new List<int>() { con.X, con.Y }); //con.X is not part of any group, so we can create a new one with X and Y added, since both a are in the group       \n    } \n    else \n    {\n        var group = groups.First(g => g.Contains(con.X) || g.Contains(con.Y));\n        if(!group.Contains(con.X)) group.Add(con.X);\n        if(!group.Contains(con.Y)) group.Add(con.Y);\n    }\n}	0
8400373	8400273	How to select certain strings (by index) from a list in a list with linq?	var indexes = new List<int>() {0, 2};\nvar whatYouWant = strings.Select(item => indexes.Select(index => item[index]).ToList())	0
19517919	19516746	WPF Borderless window is maximized only to primary screen size	WindowState = "Maximized"	0
3381072	3381066	Expose Unmanaged Code's Constant to Manage Dll	#define	0
28002910	28002787	Access object without knowing the name beforehand	private void pb1_Click(object sender, EventArgs e)\n{\n    SwapImages(sender as PictureBox);\n}\n\nprivate void SwapImages(PictureBox pb)\n{   \n    if (pb.Image == img1)\n    {\n        pb.Image = img2;                    \n    }            \n}	0
14653097	14652974	How to Alter behavior of a console application depending on Scheduled or Manual execution?	private static void Main(string[] args)\n    {\n        var yourFirstMagicNumber = -1;\n        var yourSecondMagicNumber = -1;\n\n        // Let's use the third argument as indicator that you need user input\n        if (args.Length > 2 && "true".Equals(args[2]))\n        {\n            Console.WriteLine("enter magic nr 1: ");\n            var firstArgument = Console.ReadLine();\n            yourFirstMagicNumber = Int32.Parse(firstArgument);\n\n            Console.WriteLine("enter magic nr 2: ");\n            var secondArgument = Console.ReadLine();\n            yourSecondMagicNumber = Int32.Parse(secondArgument);\n        }\n        else\n        {\n            yourFirstMagicNumber = Int32.Parse(args[0]);\n            yourSecondMagicNumber = Int32.Parse(args[1]);\n        }\n    }	0
32248499	32248258	Limit checked items in CheckedListBox	private void checkedListBox1_ItemCheck(object sender, ItemCheckEventArgs e)\n{\n    if (e.NewValue == CheckState.Checked && checkedListBox1.CheckedItems.Count >= 2)\n        e.NewValue = CheckState.Unchecked;\n}	0
21362390	21362333	combine foreach and for loop using C#	int j = 1;\nforeach (DataRow row in table.Rows) // Loop over the rows.\n{\n    for (int i = 0; i < row.ItemArray.Length; i++, j++)\n    {\n       excell_app.createHeaders(1, 1, "" + row.ItemArray[i] + "", j, j, 1, "black", false, 10, "n");\n    }\n}	0
7186711	7186648	How to remove first 10 characters from a string?	str = "hello world!";\nstr.Substring(10, str.Length-10)	0
21557954	21539411	Getting the ScrollPosition of a RichEditBox	myRichEditTextBox.GetFirstDescendentOfType<ScrollViewer>()	0
8361741	8361708	One line bool from a QueryString	bool isSearch = !string.IsNullOrEmpty(Request.QueryString["q"]);	0
26333372	26333206	C# Create a list of objects from an 2 IEnumerable instances containing only those objects with a value found in the second list	var list = (from classOne in classOneEnumerable\n            from classTwo in classTwoEnumerable\n            where classOne.ClassOneID == classTwo.ClassTwoID\n            select classOne).ToList();\n\nvar list2 = (from classOne in classOneEnumerable\n             join classTwo in classTwoEnumerable\n             on classOne.ClassOneID equals classTwo.ClassTwoID\n             select classOne).ToList();	0
23749927	23749803	Group by multiple columns linq count nested row	records\n    .GroupBy(x => new { x.Div, x.Bus, x.Dept })\n    .Select(g => new \n        { \n            g.Key.Div, \n            g.Key.Bus, \n            g.Key.Dept, \n            Entered = g.Count(r => r.Status == Entered),\n            Progress= g.Count(r => r.Status == Progress),\n            Finished= g.Count(r => r.Status == Finished),\n        });	0
320877	268381	Using SMO to copy a database and data	ServerConnection conn = new ServerConnection("rune\\sql2008");\nServer server = new Server(conn);\n\nDatabase newdb = new Database(server, "new database");\nnewdb.Create();\n\nTransfer transfer = new Transfer(server.Databases["source database"]);\ntransfer.CopyAllObjects = true;\ntransfer.CopyAllUsers = true;\ntransfer.Options.WithDependencies = true;\ntransfer.DestinationDatabase = newdb.Name;\ntransfer.DestinationServer = server.Name;\ntransfer.DestinationLoginSecure = true;\ntransfer.CopySchema = true;\ntransfer.CopyData = true;\ntransfer.Options.ContinueScriptingOnError = true;\ntransfer.TransferData();	0
10501377	10500911	Linq to Sql select mapping items with one of many id's	var results = from p in data \n              where catIds.All(i => p.CategoryMappings.Contains(i))\n              select p;	0
19548645	19548130	Entity Framework: How to specify the name of Foreign Key column on a self-referencing Parent-Child relationship?	public class ProductMap : EntityTypeConfiguration<Product>\n{\n    public ProductMap() {\n        HasKey(p => p.ProductId);\n\n        Property(p => p.Name)\n            .IsRequired();\n\n        // Self referencing foreign key association \n        Property(c => c.ParentId)\n            .IsOptional();\n\n        HasOptional(x => x.Parent)\n            .WithMany(x => x.ChildProducts)\n            .HasForeignKey(x => x.ParentId)\n            .WillCascadeOnDelete(false);\n    }\n}	0
13479428	13478767	Removing elements from JSON based on a condition in C#	var jObj = (JObject)JsonConvert.DeserializeObject(json);\n        var docsToRemove = new List<JToken>();\n        foreach (var doc in jObj["response"]["docs"])\n        {\n            var id = (string)doc["id"];\n            if (knownIds.Contains(id))\n            {\n                docsToRemove.Add(doc);\n            }\n            else\n            {\n                knownIds.Add(id);\n            }\n        }\n        foreach (var doc in docsToRemove)\n            doc.Remove();	0
14673555	14673292	Deserialise JSON with random key	var jObj = JObject.Parse(data);\nvar sense = jObj["list"]\n    .Select(x => (JProperty)x)\n    .Select(p => new { \n                   propName = p.Name,\n                   itemId = p.Value["item_id"],\n                   fave = p.Value["fave"]});	0
1504421	1502867	How to get reference to SqlConnection (or Connection string) in Castle ActiveRecord?	System.Configuration.ConfigurationManager.GetSection("activerecord") as IConfigurationSource;	0
18677082	18676653	How to play a particular item from media play list?	// Declare a variable to hold the position of the media item \n// in the current playlist. An arbitrary value is supplied here.\nint index = 3;\n\n// Get the media item at the fourth position in the current playlist.\nWMPLib.IWMPMedia media = player.currentPlaylist.get_Item(index);\n\n// Play the media item.\nplayer.Ctlcontrols.playItem(media);	0
13054035	13045247	How do I make the ServiceStack MiniProfiler work with EF?	MiniProfilerEF.Initialize_EF42()	0
21372632	21371972	How to delete a RabbitMQ exchange?	IModel.ExchangeDelete	0
3471888	3471839	How can I trap all mouse events on a control?	using System;\nusing System.Windows.Forms;\n\nclass MyBrowser : WebBrowser {\n    protected override void WndProc(ref Message m) {\n        if (m.Msg >= 0x200 && m.Msg <= 0x20a) {\n            // Handle mouse messages\n            //...\n        }\n        else base.WndProc(ref m);\n    }\n}	0
418043	418006	How can I disable a tab inside a TabControl?	public static void EnableTab(TabPage page, bool enable) {\n    foreach (Control ctl in page.Controls) ctl.Enabled = enable;\n}	0
19438910	19438472	JSON.NET deserialize a specific property	public T GetFirstInstance<T>(string propertyName, string json)\n{\n    using (var stringReader = new StringReader(json))\n    using (var jsonReader = new JsonTextReader(stringReader))\n    {\n        while (jsonReader.Read())\n        {\n            if (jsonReader.TokenType == JsonToken.PropertyName\n                && (string)jsonReader.Value == propertyName)\n            {\n                jsonReader.Read();\n\n                var serializer = new JsonSerializer();\n                return serializer.Deserialize<T>(jsonReader);\n            }\n        }\n        return default(T);\n    }\n}\n\npublic class MyType\n{\n    public string Text { get; set; }\n}\n\npublic void Test()\n{\n    string json = "{ \"PropOne\": { \"Text\": \"Data\" }, \"PropTwo\": \"Data2\" }";\n\n    MyType myType = GetFirstInstance<MyType>("PropOne", json);\n\n    Debug.WriteLine(myType.Text);  // "Data"\n}	0
9814138	9814077	Get Method for LINQ-TO-SQL object	var rep = new Repository<Questionnaire>(...);\n\nvar questionnaire = rep.GetById(1);	0
23394796	23394761	Only print an item once from Model in the View	bool found = false;\n\n@foreach (var item in Model)\n{\n    if (item.Site == "Source Search" && !found)\n    {\n        found = true;\n\n        <a href="@item.URL" target="_blank">More Results</a>\n    }\n}	0
17212257	17212169	How can you drag and drop a list item to a label so it's the label's text in C#?	private void posLB_DragDrop(object sender, DragEventArgs e)\n    {\n        if (e.Data.GetDataPresent(DataFormats.Text))\n        {\n            String s = e.Data.GetData(DataFormats.Text) as String;\n            if (!String.IsNullOrEmpty(s))\n                posLB.Text = s;\n        }\n    }	0
29564211	29564130	Is it possible to structure a generic method so T is optional?	public class BunnyManager\n{\n    public Bunny<T> GetBunny<T>(string someJson)\n    {\n       return new Bunny<T>(someJson);\n    }\n\n    public Bunny GetBunny()\n    {\n       return new Bunny();\n    }\n}\n\npublic class Bunny\n{\n\n}\n\npublic class Bunny<T> : Bunny\n{\n   T parsedJson { get; set; }\n\n    public Bunny(string someJson)\n    {\n        if (!string.IsNullOrEmpty(someJson))\n            parsedJson = ConvertJsonStringToObject<T>(someJson);\n    }\n}	0
2883605	2883591	Want to add a new property to a class, can I use anonymous functions for this?	users.ConvertAll(u => new {\n    u.NormalProperty, // repeat for properties you want\n    Count = userstats[user.ID].Count\n});	0
8409097	8409016	Reducing Objects to Categories based on arbitrary logic	Heading Record (Parent record, which defines the heading to be used)\n  Heading Selector (Child records which define the if statement)	0
13910708	13877264	Refreshing a ListView in a User Control from another User Control	protected void Page_Load(object sender, EventArgs e){     \n  foreach (ListViewItem item in lvStaffer.Items)\n        {\n           Control_ResourceListViewControl resourceListViewControlItem =\n        (Control_ResourceListViewControl)e.Item.FindControl("ResourceListViewControlItem");\n\n        if (resourceListViewControlItem != null)\n        {\n           // Each item in lvStaffer contains an instance of the          ResourceListViewControl object.\n          // Each object is a subscriber of the ResourceReassigned event.\n           resourceListViewControlItem.ResourceReassigned += new   EventHandler(lvStaffer_ResourceReassigned);\n        }\n       }	0
14215267	14157855	Incorrect datetime conversion from UTC after DataSet.GetXml()	objOrderRow.EndTime = objOrder.EndTime.ToLocalTime();	0
14241726	14241209	Check if a menu item event if coming from a click or shortcut	protected override bool ProcessCmdKey(ref Message msg, Keys keyData) \n{\n    if (keyData == (Keys.Control | Keys.F)) \n    {\n        Console.WriteLine("My code ran from shortcut");\n        myFunction();\n    }\n    return base.ProcessCmdKey(ref msg, keyData);\n}\n\nprivate void ToolStripMenuItem_click(object sender ...)\n{\n  Console.WriteLine("My code ran from menu item");\n  myFunction();\n}\n\nvoid myFunction()\n{\n  //your functionality here\n}	0
1629797	1621428	ASP.NET Caching with Session variable?	var cacheableUserData = (UserData)Cache("UserData");\nif (cacheableUserData== null)\n{\n    cacheableUserData= GetDataFromDB();\n    Cache.Add("UserData", cacheableUserData); // Set cache expiration here\n}\nvar dataToPresent = CombineData(userData, loggedInUserData);	0
25512	25158	Building C# .NET windows application with multiple views	tabControl1.Top = tabControl1.Top - tabControl1.ItemSize.Height;\ntabControl1.Height = tabControl1.Height + tabControl1.ItemSize.Height;\ntabControl1.Region = new Region(new RectangleF(tabPage1.Left, tabPage1.Top, tabPage1.Width, tabPage1.Height + tabControl1.ItemSize.Height));	0
8362611	8362585	binding app property to own dependency property	public static readonly DependencyProperty VisibleProperty = DependencyProperty.Register("Visible", typeof(bool), typeof(SpecialMenuItem), new FrameworkPropertyMetadata(false, OnVisibleChanged));\n\nprivate static void OnVisibleChanged(DependencyObject dependencyObject, DependencyPropertyChangedEventArgs e)\n{\n    // logic here will be called whenever the Visible property changes\n}	0
16096297	16096258	Count the number of the same words in richtextbox	string[] data = richTextBox1.Text.Split(' ');\nfor(int i=0;i<data.Length;i++)\n{\n   if(data[i]==textBox1.Text)\n      n++;\n}	0
9998185	9998052	How to avoid an opened Comport if it is already opened	using (var com3 = new SerialPort("COM3"))\n{\n    if (!com3.IsOpen) com3.Open();\n\n    for (int ii = 0; ii < 10; ++ii)\n    {\n        com3.WriteLine("AT" + Environment.NewLine);\n        com3.WriteLine("AT+CMGF=1" + Environment.NewLine);\n        com3.WriteLine("AT+CMGS=\"" + 03152800485 + "\"" + Environment.NewLine);\n        com3.WriteLine("Hello Kashif" + (char)26);\n        Thread.Sleep(5000);\n    }\n    com3.Close();\n}	0
2019038	2019021	Dictionary<int [], bool> - compare values in the array, not reference?	class IntArrayComparer : IEqualityComparer<int[]> {\n    public bool Equals(int[] x, int[] y) {\n        if (x.Length != y.Length) {\n            return false;\n        }\n        for (int i = 0; i < x.Length; ++i) {\n            if (x[i] != y[i]) {\n                return false;\n            }\n        }\n        return true;\n    }\n    public int GetHashCode(int[] obj) {\n        int ret = 0;\n        for (int i = 0; i < obj.Length; ++i) {\n            ret ^= obj[i].GetHashCode();\n        }\n        return ret;\n    }\n}\nstatic void Main(string[] args) {\n    Dictionary<int[], bool> dict = new Dictionary<int[], bool>(new IntArrayComparer());\n}	0
32379207	32378700	c# extract value from nextnode	Dictionary<string, string> elements = new Dictionary<string, string>();\n\nxml.Root.Elements().ToList().ForEach(xmlElement =>\n{\n    elements.Add(xmlElement.Descendants("key").First().Value,\n                 xmlElement.Descendants("value").First().Value);\n});	0
16167642	16152066	Add "columns" of controls dynamically based on container height	int labelY = 0;\nint textY = 0;\nint startX = 5;\nint startY = 5;\nint height = tabPageBicycle.Height;\nPoint startLocation = new Point(0, 0);\n\nfor (int x = 0; x < 75; x++)\n{\n    Label label = new Label();\n    TextEdit text = new TextEdit();\n    label.AutoSize = true;\n    label.Text = x.ToString();\n    text.Text = x.ToString();\n\n    //Determine if the next set of controls will be past the height of the container.\n    //If so, start on the next column (change X).\n    if ((height - textY) < ((label.Height + 10) + text.Height))\n    {\n        startX += 125;\n        labelY = 0;\n    }\n\n    //Start of new column.\n    if (labelY == 0)\n        label.Location = new Point(startX, startY);\n    else\n        label.Location = new Point(startX, textY + label.Height + 10);\n\n    tabPageBicycle.Controls.Add(label);\n    labelY = label.Location.Y;\n    textY = labelY + 15;\n\n    text.Location = new Point(startX, textY);\n    textY = text.Location.Y;\n    tabPageBicycle.Controls.Add(text);\n}	0
10317091	10316992	Nitpicky ReSharper behavior, null reference with Request.Cookies	if (Request.Cookies["id"] != null)	0
15819435	15818922	DbContext ExecuteSQLCommand with no parameters	var parms = new ParameterCollection();\n\nparms.Add("signOffId", signOffID);\n\ndb.Database.ExecuteSqlCommand("DELETE FROM SignoffCommentAttachment \nWHERE SignoffCommentAttachment.SignoffCommentID \nIN (SELECT [SignoffCommentID] FROM [SignoffComments] \nWHERE SignoffID = @signOffID)", parms);	0
6056166	6056098	How Can I refresh my Datagrid on WPF automatically for every 1 minute?	DataGrid.Items.Refresh()	0
25122339	25122042	How do I auto-generate objects containing a readonly list using AutoFixture?	var entity = fixture.Create<Entity>();\nfixture.AddManyTo(entity.Values);	0
11592294	11591621	Map image url with querystring to MVC3 Action	routes.MapRoute(\n    "",\n    "SomeFolder/SomeImage.gif",\n    new { controller = "SomeController", Action = "SomeAction" }\n  );	0
787902	787883	c#: how to force trailing zero in numeric format string?	yourNumber.ToString("N2");	0
5741678	5729337	Binding DataGridViewCheckBoxColumn to array of booleans	GridView.DataSource = Preferences \n   .Select(p => new Preference {Description = p.Key, Selected = p.Value})\n   .ToList();\nGridView.Columns[0].DataPropertyName = "Description";\nGridView.Columns[1].DataPropertyName = "Selected";	0
25300695	25261013	Copy or open external file in windows RT app	StorageFolder localFolder = Windows.Storage.ApplicationData.Current.LocalFolder;\nStorageFile file = null;\nHttpWebRequest request = (HttpWebRequest)WebRequest.Create(filepath);\n\n//TODO Systemuser\nrequest.Credentials = System.Net.CredentialCache.DefaultNetworkCredentials;\nvar response = await request.GetResponseAsync();\n\nList<Byte> allBytes = new List<byte>();\nusing (Stream imageStream = response.GetResponseStream()) {\n      byte[] buffer = new byte[4000];\n      int bytesRead = 0;\n      while ((bytesRead = await imageStream.ReadAsync(buffer, 0, 4000)) > 0) {\n           allBytes.AddRange(buffer.Take(bytesRead));\n      }\n}\n\nfile = await localFolder.CreateFileAsync(fileName, CreationCollisionOption.ReplaceExisting);\nawait FileIO.WriteBytesAsync(file, allBytes.ToArray());\n\nawait RenderPDFPage(fileName);	0
23341817	23330468	NHibernate SQLFunction group by	var t = Projections.SqlFunction("round", NHibernateUtil.Int32, Projections.GroupProperty("rating"));\n var output = sess.QueryOver<Song>()\n       .SelectList(list => list\n       .Select(Projections.SqlFunction("round", NHibernateUtil.Int32, Projections.GroupProperty(t)))\n       .SelectCount(s => s.song_id))\n       .List<object[]>()\n       .Select(prop => new RatingStat\n        {\n            rating = (int)prop[0],\n            count = (int)prop[1]\n        }).ToList<RatingStat>();	0
137324	137260	What are the dangers of making a method virtual?	class Base {\n    public Base() {\n       InitializeComponent();\n    }\n    protected virtual void InitializeComponent() {\n        ...\n    }\n}\n\nclass Derived : Base {\n    private Button button1;\n    public Derived() : base() {\n        button1 = new Button();\n    }\n    protected override void InitializeComponent() {\n        button1.Text = "I'm gonna throw a null reference exception"\n    }\n}	0
18487704	18487634	How to synchronize two tables stored in different databases	exec sp_addlinkedserver	0
9244126	9235295	Display Datarows in Datagridview	DataRow dRow;\nfor(i=0;i<results;i++)\n      {\n            dRow = returnedRows[i];\n            secondForm.dataGridView1.Rows.Add(dRow[0].ToString(), \n                dRow[1].ToString(),   dRow[2].ToString(), dRow[3].ToString());\n      }	0
17404739	17403893	how to get page url path from user control	var url = Request.Url.FilePath;\nvar folder = System.IO.Path.GetDirectoryName(url)\nhypAddItem.NavigateUrl = folder + "/Export.ashx";	0
12573671	12563399	WP7 XML insert into GPX	var root = doc1.Element("trk").Element("trkseg");	0
9607787	9607667	editing xml using C#	XElement newEl = new XElement(new XElement("reminder",\n                                new XElement("Title", "NEW-Alarm"),\n                                new XElement("Description", "New-Desc"),\n                                new XElement("Time", "03/07/2012 10:11AM"),\n                                new XElement("snooze", "15"),\n                                new XElement("repeat", "Daily")));\n                    doc.Root.Add(newEl);\n                    doc.Save(PATH);	0
8523245	8523061	How to verify whether a type overloads/supports a certain operator?	static bool HasAdd<T>() {\n    var c = Expression.Constant(default(T), typeof(T));\n    try {\n        Expression.Add(c, c); // Throws an exception if + is not defined\n        return true;\n    } catch {\n        return false;\n    }\n}	0
20978104	20977961	C# How to concatenate path and variable	var imgName = listBox2.SelectedItem.ToString();\npictureBox1.Image = Resources.ResourceManager.GetObject(imgName) as Bitmap;	0
571188	570949	WPF: Loading data in the constructor of a UserControl breaks the Designer	if (!System.ComponentModel.DesignerProperties.GetIsInDesignMode(this))\n{\n  using (var context = new Data.TVShowDataContext())\n  {\n    var list = from show in context.Shows\n               select show;\n\n    listShow.ItemsSource = list;\n  }    \n}	0
11554452	11554414	How to use LINQ to select into an object?	songs.UserSongs.GroupBy(x => x.User).Select(g => new SongsForUser() \n{ \n    User = g.Key,\n    Songs = g.Select(s => s.SongId).ToList()\n});	0
20641693	20641630	Distinct concat two IEnumerables and flag if it came from list B	var newInA = dateListA.Except(dateListB);\nvar results = newInA\n                 .Select(d => new { Date = d, WasInListB = false })\n                 .Concat(dateListB.Select(d => new { Date = d, WasInListB = true }));	0
6117198	6117168	How do you PerformClick(); for a button on a different tab?	myTabs.SelectedTab = specificTab;\nbtnExit.PerformClick();	0
1014855	1010690	Managing multiple configuration files in Visual Studio for a C# project	IF "$(ProjectName)"="devproject" (\n   copy ...\n   copy ...\n)	0
523463	523405	How to send text to Notepad in C#/Win32?	[DllImport("user32.dll", EntryPoint = "FindWindowEx")]\n    public static extern IntPtr FindWindowEx(IntPtr hwndParent, IntPtr hwndChildAfter, string lpszClass, string lpszWindow);\n    [DllImport("User32.dll")]\n    public static extern int SendMessage(IntPtr hWnd, int uMsg, int wParam, string lParam);\n    private void button1_Click(object sender, EventArgs e)\n    {\n        Process [] notepads=Process.GetProcessesByName("notepad");\n        if(notepads.Length==0)return;            \n        if (notepads[0] != null)\n        {\n            IntPtr child= FindWindowEx(notepads[0].MainWindowHandle, new IntPtr(0), "Edit", null);\n            SendMessage(child, 0x000C, 0, textBox1.Text);\n        }\n    }	0
7581229	7581212	Regex matching of simple expression	(\w+) -> (\w+)	0
12677902	12677803	Finding subsets of dates withing List<Tuple<date,double>>	var dataForOneMonth = dataList.Where(t => t.Item1 >= DateTime.Now.AddMonths(-1) \n                           && t.Item1 <= DateTime.Now);\n\n\n var sum = dataForOneMonth.Sum(t => t.Item2);\n var avg = dataForOneMonth.Average(t => t.Item2);	0
11019300	11019240	Running into an issue trying to extract links from htmlnode using htmlagiliypack	htmlSnippet.SelectNodes(".//a[@href]")	0
20256449	20255706	How can i fill my List<List<int>> from a text file using C#?	List<List<int>> values = new List<List<int>>();\nList<int> innerValues = new List<int>();\nforeach (string item in File.ReadAllLines(@"../../Archivos/TextFileTotalEspecies.txt"))\n{\n    if (item == "End Animal")\n    {\n        values.Add(innerValues);\n        innerValues = new List<int>();\n        continue;\n    }\n    else if (item == "End")\n    {\n        break;\n    }\n    else\n    {\n        innerValues.Add(int.Parse(item));\n    }\n}	0
15983054	15982958	Execute a query that joins tables from 2 or more db's with SQLConnector and SQLCommand	SELECT\n    c.Name\n    FROM db1.dbo.TableA a(nolock)\n    join db2.dbo.TableA b(nolock) on a.id = b.id\n    join db2.dbo.TableB c(nolock) on b.id = c.id\n    join db2.dbo.TableC as d on c.id = d.id\n    where c.id = '2314'	0
4869789	4869727	How to reference a property from a static member in XAML?	Foreground="{Binding Path=ForegroundColor,Source={x:Static Modules:OrganisationModule.Resources}}" />	0
14211323	14210919	RDLC exported to excel to show negative numbers in parentheses	#,0;(-#,0)	0
32775901	32775499	How can I use Json to pass a url from an web API?	private long bookid;\nprotected override void OnNavigatedTo(NavigationEventArgs e)\n{\n    dynamic bookDetails = e.Parameter;\n    bookid = bookDetails.ID;\n}\n\n    private async void download_btn_Click(object sender, RoutedEventArgs e)\n{\n    using (HttpClient client = new HttpClient())\n    {\n        var id = bookid;\n\n        var uri = "http://it-ebooks-api.info/v1/book/"+id;\n\n       //Here I should implement some code to convert from json to simple download url\n        await Launcher.LaunchUriAsync(new Uri(uri));\n\n    }	0
10766366	10766331	How do I assign a value to toolStripStatusLabel1 that is in Form1?	toolStripStatusLabel.Invoke((MethodInvoker)delegate\n        {\n            toolStripStatusLabel.Text = "foo";\n        });	0
18892942	18891997	how to change Authorize attribute's parameter at runtime	public sealed class AuthorizationAttribute : AuthorizeAttribute\n{\n    public override void OnAuthorization(AuthorizationContext filterContext)\n    {\n        //do custom authorization here\n        base.OnAuthorization(filterContext);\n    }\n}	0
23744380	23744328	How to keep an environment variable after program closes	Environment.SetEnvironmentVariable( "PATH" , "%new path%", EnvironmentVariableTarget.Machine);	0
14572856	14572690	Is it possible to have a "var" as a Global variable	public static	0
11779275	11779174	Launch a second instance of a WPF application from within the first	yourWindow.GetType().Assembly.Location	0
24660324	24658359	Selecting a sub XML as string	Dictionary<int, string> myDictionary = new Dictionary<int, string>();\n            XmlDocument xml = new XmlDocument();\n            xml.LoadXml(<myInputXMLAsString>);\n            XmlNodeList xnList = xml.SelectNodes("/Run/Roles");\n\n            foreach (XmlNode xn in xnList)\n            {\n                int roleId = int.Parse(xn["Role"].Attributes["id"].Value);\n                XmlDocument subXmlDocument = new XmlDocument();\n                subXmlDocument.LoadXml(xn.InnerXml);\n                XmlNodeList subXn = subXmlDocument.SelectNodes("/Role/ValidationInformation");\n                string validationInfo = subXn[0].InnerXml;\n                roleIdToValidationInformationDictionary.Add(roleId, validationInfo);\n            }	0
16479984	16479906	Displaying results on results page, SQL ASP.NET	try\n    { \n    con.Open();\n    string mysql; // generate an sql insert query for the database\n    mysql = "SELECT * FROM Cars WHERE Make LIKE (@p1)";\n    OleDbCommand cmd = new OleDbCommand(mysql, con);\n    cmd.Parameters.AddWithValue("@p1", tbMake.Text);\n    OleDbDataAdapter da=new OleDbDataAdapter(cmd);\n    DataSet ds=new DataSet();\n    da.Fill(ds);\n    gv.DataSourse=ds.Tables[0];\n    gv.DataBind();\n    con.Close();\n    }\n    catch(Exception ex)\n    {\n    }\n    finally\n    {\n     con.close();\n    }	0
9405493	9404533	CLR Trigger only particular column get updated	COLUMNS_UPDATED()	0
4599722	4599699	Generate checksum without opening the file	FileAccess.Read	0
8163543	8163397	how to assign value to readonly static field	public static class Constant\n{\n    public static string Name\n    {\n        get\n        {\n            return name;\n        }\n        set\n        {\n            if (name == null)\n                name = value;\n            else\n                throw new Exception("...");\n        }\n    }\n    private static string name;\n}	0
14910752	14910584	Get PropertyType.Name in reflection from Nullable type	var propertyType = propertyInfo.PropertyType;\n\nif (propertyType.IsGenericType &&\n        propertyType.GetGenericTypeDefinition() == typeof(Nullable<>))\n    {\n      propertyType = propertyType.GetGenericArguments()[0];\n    }\n\nmodel.ModelProperties.Add(new KeyValuePair<Type, string>\n                        (propertyType.Name,propertyInfo.Name));	0
32665242	32664956	Get top n records with top m of relative table in Entity Framework	var result = entity.Categories.Select\n                         (\n                            cats => new\n                                {   \n                                    cats.CategoryName,\n                                    cats.Description,\n                                    Products = cats.Products.Take(3)\n                                }\n                         ).Take(5);	0
3960311	3960285	How to convert a DropDownList Value in INT Variable	int myPageSize;\n\nif(int.TryParse(uxPageSizeUsersSelector.SelectedValue, out myPageSize))\n{\n     //SUCCESS\n}\nelse\n{\n    ///handle problem here.\n}	0
14170251	14170235	Regex for string matching following criteria	"^[^ put_anything_you_dont_want_like_specials_and_space_in_here]{6,50}$"	0
14080258	14079959	Get Month and Day value from valid gMonthDay format without splitting	string gMonthDay = "--12-21";\nstring output = DateTime.ParseExact(gMonthDay, "--MM-dd", CultureInfo.InvariantCulture).ToString("dd/MM", CultureInfo.InvariantCulture);	0
8418413	8418368	Followup: Bring a window to the front in WPF	Topmost = true;\nTopmost = false;	0
10090543	10090447	Retrieve and modify an entity without maintaining a database context?	public Save() {\n    DatabaseContect ct = new DatabaseContext();\n    ct.Entry(psn).State = EntityState.Modified;\n    ct.SaveChanges();\n}	0
604865	604804	String normalisation	using System;\nusing VB = Microsoft.VisualBasic;\n\n\nnamespace ConsoleApplication1\n{\n    class Program\n    {\n        static void Main(string[] args)\n        {\n            Console.WriteLine(VB.Strings.StrConv("QUICK BROWN", VB.VbStrConv.ProperCase, 0));\n            Console.ReadLine();\n        }\n    }\n}	0
13136995	13136920	Read an XML string in C#	XElement.Parse(xml).Descendants("daily")\n                   .Single()\n                   .Attribute("dayFrequency")\n                   .Value;	0
12763765	12763192	How to wait until my process will create my file on the disk to avoid null when i am checking this file	for (int i = 20 /* seconds till exception */; i > 0; i--)\n{\n    if (File.Exists(_pcapPath))\n        break;\n    else if (i == 1)\n        throw new Exception("File was not created within 20 seconds.");\n    else\n        Thread.Sleep(1000);\n}\n\nwhile (!tshark.WaitForExit(1000 /* file size update interval */))\n{\n    var fileInfo = new FileInfo(_pcapPath);\n    Console.WriteLine("File has grown to {0} bytes", fileInfo.Length);\n}\n\nConsole.WriteLine("Complete");	0
22868290	22868136	SQL Server - Using tinyint with enum	public enum enumSVMV : byte { SV = 0, MV = 1, none = 2 };	0
8870758	8870727	Properties and private set	public int Abc { get; private set; }	0
4461322	4460468	When using a handler how do I write a log once per rountrip?	System.Web.HttpContext.Current.Request.CurrentExecutionFilePathExtension	0
9061742	9061498	SortedList with value and simplified loops with lambda	SortedList<char, int> alpha = new SortedList<char, int>();\nalpha.Add('B',1);\nalpha.Add('A',2);\nalpha.Add('C',3);\nvar A= alpha.OrderByDescending(a =>a.Value)\n        .Select (a =>a.Key+":"+a.Value)\n        .ToList();	0
13752797	13752726	Get the seventh digit from an integer	int getSeventhDigit(int number)\n{\n    while(number >= 10000000)\n        number /= 10;\n\n    return number % 10;\n}	0
743590	743549	How to put image in a picture box from Bitmap	pictureBox.Image = bmp;	0
5611422	5611353	Format List<T> to concatenate fields	public static List<string> GetCitiesInCountryWithState(string isoalpha2)    \n{\n    const string delimiter = ", ";        \n    using (var ctx = new atomicEntities())        \n    {\n        var query = from c in ctx.Cities                        \n                    join ctry in ctx.Countries on c.CountryId equals ctry.CountryId \n                    where ctry.IsoAlpha2 == isoalpha2                        \n                    select c.CityName + delimiter + c.State ;            \n        return query.ToList();\n    }\n}	0
11250258	11249784	increasing image quality of treeview icons?	imagelist.ColorDepth = ColorDepth.Depth32Bit;	0
23699756	23699144	How to color a particular row of a grid in c# using silverlight	var greenBackgroundBorder = new Border(){\n    Background=new SolidColorBrush(Colors.Green)};\nmyGrid.Children.Add(greenBackgroundBorder);\n\n// stay always behind other elements\nCanvas.SetZOder(greenBackgroundBorder, -100);\n\n//entire second row\nGrid.SetColumnSpan(greenBackgroundBorder,3);\nGrid.SetRow(greenBackgroundBorder, 1 );	0
12981065	12976415	Change IP of IIS7 Bindings in C#	using (ServerManager iisServerManager = new ServerManager())\n{\n    foreach (Site site in iisServerManager.Sites)\n    {\n        foreach (Binding binding in site.Bindings)\n        {\n            string ipAddress = "*";\n            int port = binding.EndPoint.Port;\n            string hostHeader = binding.Host;\n\n            binding.BindingInformation = string.Format("{0}:{1}:{2}", ipAddress, port, hostHeader);\n        }\n\n        iisServerManager.CommitChanges();\n    }\n}	0
5188872	5188827	Easy way to compare values of more than 3 variables?	if (Array.TrueForAll<int>(new int[] {a, b, c, d, e, f, g, h, i, j, k },\n        val => (a == val))) {\n    // do something\n}	0
17833642	17618112	Console App to search outlook inbox with subject line filter skipping emails	List<MailItem> ReceivedEmail = new List<MailItem>(); \n\nforeach (Outlook.MailItem mail in emailFolder.Items)\n{\n     ReceivedEmail.Add(mail);\n}\n\nforeach (MailItem mail in ReceivedEmail)\n{ \n    //do stuff\n}	0
23720650	23720480	Validate empty text boxes in winforms using C#	private bool ValidateTextBoxes()\n    {\n        try\n        {\n            string textBoxData = string.Empty;\n\n            foreach (Control item in this.Controls)\n            {\n                if (item.GetType() == typeof(TextBox))\n                {\n                    textBoxData += item.Text;\n                }\n            }\n            return (textBoxData != string.Empty);\n        }\n        catch { return false; }\n    }\n\n    if(ValidateTextBoxes())\n    {\n         // your code..\n    }	0
21592998	21589855	Creating responsive hyperlink link in Winform DataGridView	using System.Diagnostics;\nusing System.IO;\n\n...\n\n    private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)\n    {\n        string filename = dataGridView1[e.ColumnIndex, e.RowIndex].Value.ToString();\n        if(e.ColumnIndex == 3 && File.Exists(filename))\n        {\n            Process.Start(filename);\n        }\n\n    }	0
19779727	19779005	Update with regex part of the string with delimeters	using System;\nusing System.Collections.Generic;\nusing System.IO;\nusing System.Text.RegularExpressions;\n\nclass Program\n{\n    static void Main(string[] args)\n    {\n        var dict = new Dictionary<string, string>();\n        dict.Add("CAT", "Kitty");\n        dict.Add("MOUSE", "Jerry");\n\n        var lines = File.ReadAllText("input.txt");\n        var regex = new Regex(@"(?<=(^=\[?(?:\w*?\.){3}))\w*?(?=(\.\w*?\]?){3}$?)",\n            RegexOptions.Multiline |\n            RegexOptions.Compiled);\n\n        var result = regex.Replace(lines, m =>\n            dict.ContainsKey(m.Value) ? dict[m.Value] : m.Value);\n        Console.WriteLine(result);\n    }\n}	0
17595907	17595486	Changing color and underline the content of link button	.pagenav:hover {\n    text-decoration: underline;\n    color: blue;\n}	0
31024707	31002154	Xceed WPF propertyGrid Custom Collection editor	class Properties\n{\n    private List<Assembly> assemblies = new List<Assembly>();\n\n    [DisplayName("ExpectedAssemblyVersions")]\n    [Description("The expected assembly versions.")]\n    [Category("Mandatory")]\n    [Editor(typeof(CollectionEditor), typeof(CollectionEditor))]\n    public List<Assembly> Assemblies\n    {\n        get\n        {\n            return assemblies;\n        }\n        set\n        {\n            assemblies = value;\n        }\n    }\n}\n\nclass Assembly\n{\n    public string Name { get; set; }\n\n    public string Version { get; set; }\n}	0
24002143	24001245	Can't get UserManager from OwinContext in apicontroller	using Microsoft.AspNet.Identity.Owin;\nusing Microsoft.AspNet.Identity; // Maybe this one too\n\nvar manager = HttpContext.Current.GetOwinContext().GetUserManager<UserManager<User>>();	0
31414558	31414429	C# get keys and values from List<KeyValuePair<string, string>	// #1: get all keys (remove Distinct() if you don't want it)\nList<string> allKeys = (from kvp in KV_List select kvp.Key).Distinct().ToList();\n// allKeys = { "qwer", "zxcv", "hjkl" }\n\n// #2: get values for a key\nstring key = "qwer";\nList<string> values = (from kvp in KV_List where kvp.Key == key select kvp.Value).ToList();\n// values = { "asdf", "ghjk" }\n\n// #3: get keys for a value\nstring value = "asdf";\nList<string> keys = (from kvp in KV_List where kvp.Value == value select kvp.Key).ToList();\n// keys = { "qwer", "zxcv" }	0
7417706	7414713	How can I change the text box within a frame from the outer page in wpf	class child\n{\n\n// this field cannot be accessed from a parent or anyone else\nprotected string Text="";\n\n// This property can be used by a parent and other objects.\npublic string Message\n{\nget{ return Text; }\nset{ if(value!=null) Text=value; } \n}\n\n}	0
6596634	6594915	Unicode strings in .Net with Hebrew letters and numbers	string A = "\u05E9"; //A Hebrew letter\nstring B = "23";\nstring AB = B + A; // !\ntextBlock1.Text = AB;\ntextBlock1.FlowDirection = FlowDirection.RightToLeft;\n//Ouput Ok - A is left to B as intended.	0
4439159	4439075	Create a polygon filled with a tiled image in c#	var brush = new TextureBrush(new Bitmap(imagefile));\n\nMatrix mtx = brush.Transform;\nmtx.Translate(xoffset, 0);\nbrush.Transform = mtx;	0
5736972	5702217	Injecting Dependency That Has Already Been Created With Ninject	public interfacte ITreeViewModel\n{\n    public TstTreeNode TestNode {get;}\n\n    ........\n    // Other members\n}\n\n// Sample Class\npublic class TreeViewModel : ITreeViewModel\n{\n    public TreeViewModel(TstTreeNode node) {\n       TestNode = node;\n    }\n\n    // Implemented from interface\n    public TstTreeNode TestNode {get; private set;}\n}\n\n// Your code\nIKernel kernel = new StandardKernel();\nkernel.Bind<ITeleStore>().To<TeleStore>();\nkernel.Bind<ITreeViewModel>().To<TreeViewModel>();\n\nvar tst = kernel.Get<TeleStore>();\n\n// rootnode already exists and is obtained from the telestore component\nTstTreeNode rootNode = tst.GetRootNode();\n\n// how do I use ninject to inject rootnode?\nITreeViewModel treeViewModel = kernel.Get<TreeViewModel>(new ConstructorArgument("node", rootNode));	0
15987585	15987179	C# - format specific number using format.string in runtime (live) on texbox	//In your form_load\n//Based on your code above, assuming textBox3 is a MaskedTextbox    \ntextBox3.KeyUp += CheckEvent()\ntextBox3.Mask = "000000000000";\ntextBox3.PromptChar = 'x'; //set this to a space or whatever you want ' ' for blank!\n\n//check AFTER every key press\nprivate void CheckEvent(object Sender, KeyEventArgs e)\n{\n    if(textBox3.Text.Count() < 12)\n    {\n        return;\n    }\n\n    //change the textboxMask when all chars present\n    maskedTextBox1.Mask = "0:000.000.000-00";\n}	0
17332265	17332143	serialize class object that contain secret data - serialization with encryption	// Save your password so you can reset it after the object has been serialized.\n[NonSerialized()] \nprivate string SavedPassword;\n\n// This saves the value of Password and Encrpts it so it will be stored Encrypted.\n// I am leaving out the Encrypt code to make it cleaner here.\n[OnSerializing()]\ninternal void OnSerializingMethod(StreamingContext context)\n{\n    SavedPassword = Password;\n    Password = Encrypt(Password);\n}\n\n// reset the Password after serialization so you can continue to use your object.\n[OnSerialized()]\ninternal void OnSerializedMethod(StreamingContext context)\n{\n    Password = SavedPassword;\n}\n\n// On deserialize you need to Decrypt your Password.\n[OnDeserialized()]\ninternal void OnDeserializedMethod(StreamingContext context)\n{\n    Password = Decrypt(Password);\n}	0
6710070	6710014	LZW compression on C# from string	private string CompressToLZW(string input)\n{\n    using (MemoryStream stream = new MemoryStream())\n    {\n        ComputeLZW(input, stream);\n        stream.Seek(0, SeekOrigin.Begin);\n        using (StreamReader reader = new StreamReader(stream))\n        {\n            return reader.ReadToEnd();\n        }\n    }\n}	0
27235789	27235728	Must declare the scalar variable "@UserId" in Insert statement	strSQL = "INSERT INTO LoginTable(UserId, Password) VALUES(@UserId, @Password)";          \n        objCommand.Parameters.AddWithValue("@UserId", tbxUserName.Text);	0
9935419	9935404	Opening Word document within C# that has spaces in the path	path="\"Cash Report\\30-03-2012 01-11-07 Cash Flow Report.Docx\""	0
11656312	11656217	Allow only integers in TextBoxes	int tester;\nif (!Int32.TryParse(textBox1.Text, out tester))\n{\n    errorProvider1.SetError(textBox1, "must be integer");\n    return;\n}	0
20514492	16243547	how to delete page from navigation stack - c# windows 8	Frame.BackStack.RemoveAt(Frame.BackStack.Count - 1);	0
30457331	30456309	Insert from multiple select MS Access 2013 C# Error	INSERT INTO Manuacturer_Item \n    (item_id, manufacturer_id) \nSELECT  \n    i.id, m.id \nFROM \n    [Item] AS i,\n    Manufacturer AS m \nWHERE   \n    i.iname like 'PC' AND m.mname like 'zaz'	0
18293484	18293442	is Windows Explorer created in a high level language?	mscoree.dll	0
15895628	15895497	How to disable cookies from a page?	string MyCookieValue;\n\n    if(Request.Cookies["ID"] != null)\n\n        Response.Cookies["ID"].Expires = DateTime.Now.AddDays(-1);	0
2168401	2168370	How to render bitmap into canvas in WPF?	class MyCanvas : Canvas {\n   protected override void OnRender (DrawingContext dc) {\n      BitmapImage img = new BitmapImage (new Uri ("c:\\demo.jpg"));\n      dc.DrawImage (img, new Rect (0, 0, img.PixelWidth, img.PixelHeight));\n   }\n}	0
11680037	11679528	Making a slideshow viewer, handling events fired from arbitrary controls	void OnClick(object sender, KeyEventArgs e) {\n    PictureEdit editor = (PictureEdit)sender;\n}\n\nSub OnClick(ByVal sender As Object, ByVal e As KeyEventArgs)\n    Dim editor as PictureEdit = CType(sender, PictureEdit)\nEnd Sub	0
20922960	20922939	Is it a bad idea to use the same function as event for different controls?	if (sender == control1) { ... }\nelse if (sender == control2) { ... }\n...	0
20057361	20057274	Sprite chasing player character in C#	xPos += Math.Cos(angle) * speed;\nyPos += Math.Sin(angle) * speed;	0
3013548	3013536	Getting a Type variable knowing the name of type C#	Type.GetType	0
22818180	22817859	Scripting Word doc from external app	using System;\nusing Microsoft.Office.Interop.Word;\n\nnamespace CSharpConsole\n{\n    static class Program\n    {\n        [STAThread]\n        static void Main()\n        {\n            var application = new ApplicationClass();\n            var document = application.Documents.Add();\n            document.SaveAs("D:\test.docx");\n            application.Quit();\n        }\n    }\n}	0
30855607	30854974	Unable to Plot Serial Data on Y2 Axis Zedgraph	myPane2.Y2Axis.IsVisible = true;\n myPane2.Y2Axis.Title = cbo_Instrument_3.Text;\n zedGraphControl2.AxisChange();\n LineItem myCurve = myPane2.AddCurve("",inst3time, Color.Blue, SymbolType.Circle);\n myCurve.IsY2Axis = true;\n zedGraphControl2.AxisChange();\n zedGraphControl2.Refresh();	0
20592382	20579989	Find a small scale image into a large scale image	double percentXZoom = (I_PLATE_MIN_X * 100) / 2560;\ndouble xCropedImage = xD - xU;\ndouble xDiff = (xCropedImage * percentXZoom) / 100;\ndouble x = xD + Math.Abs(xDiff);\n\ndouble percentYZoom = (I_PLATE_MIN_Y * 100) / 2560;\ndouble yCropedImage = yD - yU;\ndouble yDiff = (yCropedImage * percentYZoom) / 100;\ndouble y = yD + Math.Abs(yDiff);	0
3457609	3457521	How to check if object has been disposed in C#	class MyClient : TcpClient {\n    public bool IsDead { get; set; }\n    protected override void Dispose(bool disposing) {\n        IsDead = true;\n        base.Dispose(disposing);\n    }\n}	0
7301493	7301314	Setting priority when creating processes with batch file	/wait : Starts an application and waits for it to end.	0
6604586	6604565	Do transactions have to be in Stored Procedures in SQL Server?	using (TransactionScope scope = new TransactionScope())\n{\n     //Do operation 1 on connection 1 (open close connection)\n     //Do operation 2 on connection 2 (open close connection)\n\n     scope.Complete();\n}	0
1772202	1772102	c# Drag and Drop from my custom app to notepad	DataObject d = new DataObject();\n d.SetData(DataFormats.Serializable, myObject);\n d.SetData(DataFormats.Text, myObject.ToString());\n myForm.DoDragDrop(d, DragDropEffects.Copy);	0
31238148	31238106	Linq query with All rule in array	using System.Linq;\nusing System.Collections.Generic;\n\nstruct ImageItem {\n    public string Title { get; set; }\n    public string Name { get; set; }\n}\n\nbool Contains(string toSearch, string x) {\n    return toSearch != null && toSearch.ToLower().Contains(x);\n}\n\nIEnumerable<ImageItem> FilterItems(IEnumerable<string> targetKeywords, IEnumerable<ImageItem> items) {\n    return items.Where(item => targetKeywords.All(x => Contains(item.Name, x) || Contains(item.Title, x)));\n\n}	0
16449048	16441643	How to avoid screen flickering?	public void something_resize(object sender, EventArgs e)\n{\n    try\n    {\n        this.SuspendLayout(); \n\n        // Do your update, add data, redraw, w/e. \n        // Also add to ListViews and Boxes etc in Batches if you can, not item by item.  \n    }\n    catch\n    {\n    }\n    finally\n    {\n        this.ResumeLayout(); \n    }\n}	0
28539221	28537256	How to wait for a speech synthesis to complete	var tsc = new TaskCompletionSource<bool>();\nmediaElement.MediaEnded += (o, e) => { tsc.TrySetResult(true); }\nmediaElement.Play();\n\nawait tsc.Task;	0
22783131	22783091	Winforms DataGridView bound to List<T> - Show only specified properties of T	[System.ComponentModel.Browsable(false)]\npublic int SomeProperty{get;set;}	0
25443709	25443427	Randomly generating from a dictionary and returning the key and value	class Dealer\n{\n    private List<Card> shuffledCards; // keep state of the current shuffle\n\n    public Dealer(...)\n    {\n        shuffledCards = Shuffle(...); // use your method to get the shuffled cards\n    }\n\n    public Card Deal() // remove the first card from the deck and hand it out\n    {\n        Card c;\n\n        c = shuffledCards[0];\n        shuffledCards.RemoveAt(0);\n\n        return c;\n    }\n}	0
5029374	4932306	Problem disconnecting OpenVpn from application	foreach (Process p in Process.GetProcesses())\n        {\n            if (p.ProcessName.StartsWith("openvpn"))\n            {\n                p.Kill();\n                Console.WriteLine("Killed Process");\n                break;\n            }\n        }	0
17106467	17106316	How to insert the LINQ result to a string[] array	var query = (from a in this.hmdb.Servers\n                join b in this.hmdb.Components\n                on a.ServerID equals b.ServerID\n                select new {a.ServerID, b.Name}).AsEnumerable().Select(x=> string.Format("{0} - {1}",x.ServerID, x.Name)).ToArray();\n\n   string[] header = query;	0
16126383	16126068	Get the content of a div by class name using Web Browser control?	if (el.GetAttribute("className") == "cls")\n{...}	0
906735	906716	How do I change the application language in ASP.NET?	CultureInfo ci = new CultureInfo("en-US", false);\nThread.CurrentThread.CurrentCulture = ci;\nThread.CurrentThread.CurrentUICulture = ci;	0
15103309	15103223	change the value of a dropdown list	HtmlDocument document = webBrowser1.Document;\n        HtmlElement salutation = document.GetElementById("status");\n\n        var option = salutation.Children.Cast<HtmlElement>().First(x => x.GetAttribute("value").Equals("Mr"));\n        option.SetAttribute("selected", "selected");	0
14227277	14227258	How do I create a string[] from "many" "independent" "strings"?	string[] strings = new string[]{file, DestUri, DestStorage};	0
4030556	4030496	C# performance and readability with buttons enabling/disabling	bool ButtonEnabled = (Something > 0);\nbtnOne.Enabled = ButtonEnabled;\nbtnTwo.Enabled = ButtonEnabled;\nbtnThree.Enabled = !ButtonEnabled;\nbtnFour.Enabled = !ButtonEnabled;	0
2692703	2692274	Nested lock to the same object performance	public void AddRange(IEnumeratable<Item> items)\n{\n    lock (_syncObject) // Locking only once.\n    {\n        foreach (Item item in items)\n        {\n            InsertItemImpl(item);\n        }\n    }\n}\n\nprivate void InsertItemImpl(Item item)\n{\n     // inserting the item\n}\n\npublic void InsertItem(Item item)\n{\n    lock (_syncObject)\n    {\n        InsertItemImpl(item);\n    }\n}	0
489055	489051	How do I add a Python-style Get() method which takes a default value to my C# dictionaries?	using System.Collections.Generic;\n\nnamespace MyNamespace {\n    public static class DictionaryExtensions {\n        public static V GetValue<K, V>(this IDictionary<K, V> dict, K key) {\n            return dict.GetValue(key, default(V));\n        }\n\n        public static V GetValue<K, V>(this IDictionary<K, V> dict, K key, V defaultValue) {\n            V value;\n            return dict.TryGetValue(key, out value) ? value : defaultValue;\n        }\n    }\n}	0
13052535	13048220	Convert paired lists into one-to-many lookup	var nameLookup = sourceNames\n  .Zip(targetNames, (x, y) => new { Source = x, Target = y })\n  .ToLookup(x => x.Source, x => x.Target);	0
15464638	15464554	list of ints transform to array of integers	var integers = "123456";\nvar enumOfInts = integers.ToCharArray().Select(x => Char.GetNumericValue(x));	0
3214814	3214774	How to redirect from OnActionExecuting in Base Controller?	public override void OnActionExecuting(ActionExecutingContext filterContext)\n {\n    ...\n    if (needToRedirect)\n    {\n       ...\n       filterContext.Result = new RedirectResult(url);\n       return;\n    }\n    ...\n }	0
4555717	4555249	Invalid length for a Base-64 char array during decoding/decryption	public static string encodeSTROnUrl(string thisEncode)\n{\n    if (null == thisEncode)\n        return string.Empty;\n\n    return HttpUtility.UrlEncode(Encrypt(thisEncode));\n}\n\n\npublic static string decodeSTROnUrl(string thisDecode)\n{\n    return Decrypt(HttpUtility.UrlDecode(thisDecode));\n}	0
26100075	26099250	Onselect in Dropdown send mail to respective user	protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)\n   {\n\n   if(e.Row.RowType == DataControlRowType.DataRow)\n   {\n      DropDownList ddl = e.Row.FindControl("ddlCountries") as DropDownList;\n     if(ddl != null)\n     {\n        ddl.SelectedIndexChanged += new EventHandler(ddlCountries_SelectedIndexChanged);\n     }\n   }\n\n }\n\nprotected void ddlCountries_SelectedIndexChanged(object sender, EventArgs e)\n{\n     string selectedValue = ((DropDownList)sender).SelectedValue;\n     if(selectedValue== "Not Selected")\n     {\n        // Write code here for sending mail\n     }\n\n }	0
22078934	22078852	XBOX 360 Controller Check if Button Pressed in C#	GamePadState currentState = GamePad.GetState(PlayerIndex.One);\n\nif (currentState.IsConnected && currentState.Buttons.A == ButtonState.Pressed)\n{\n\n}	0
4408244	4408202	Parse and Split text from XML tag	XNamespace geoRssNs = "http://whatever/url/it/is";\n\nvar points = from point in parentElement.Elements(geoRssNs + "point")\n             let values = point.Value.Split(' ')\n             select new\n             {\n               Latitude = double.Parse(values[0], CultureInfo.InvariantCulture),\n               Longitude = double.Parse(values[1], CultureInfo.InvariantCulture)\n             };	0
24228156	24227936	Datagridview out of range	datagridtampil.Rows.Clear();\nif (reader.HasRows)\n{\n    int j = 0;\n    while (reader.Read())\n    {\n        j = datagridtampil.Rows.Add()\n        for (int i = 1; i < datagridtampil.Columns.Count; i++)\n        {\n            datagridtampil.Rows[j].Cells[i].Value = reader.GetValue(i-1).ToString();\n        }\n    }\n}	0
16710629	16710533	Passing static array in attribute	A.Months	0
6879062	6878465	Getting ToolStripItem that initiated ContextMenuStrip by keyboard	toolStrip.Items.Cast<ToolStripItem>().Where(x => x.Selected).First()	0
4821352	4821290	Console.ReadLine Break	System.Threading.Timer	0
10645049	10639271	Showing point values by default on ZedGraph	var zgc = msGraphControl1.zedGraphControl1;\n\nzgc.IsShowPointValues = true;\nzgc.PointValueFormat = "0.000";\nzgc.PointDateFormat = "d";	0
4913315	4912884	How can I disable node renaming for the TreeView in WinForms?	private void startLabelEdit() {\n        treeView1.LabelEdit = true;\n        treeView1.SelectedNode.BeginEdit();\n    }\n\n    private void treeView1_AfterLabelEdit(object sender, NodeLabelEditEventArgs e) {\n        treeView1.LabelEdit = false;\n    }	0
5738484	5722671	Selenium2: C#: Help with while loop	string url = "testpageurl";\n\nIWebdriver driver = new FirefoxDriver();\n\ndriver.Navigate().GoToUrl(url);\n\nvar links = driver.FindElements(By.TagName("a"));\n\nfor(int i=0; i<links.Count; i++ ) \n{\ndriver.Navigate().GoToUrl(url);\ndriver.FindElements(By.TagName("a"))[i].Click();\n\nAssert.IsFalse(driver.FindElement(By.TagName("body")).Text.Contains("404"));\n}	0
33057514	33057430	Remove last Character from Textbox in C#	private void button15_Click(object sender, EventArgs e)\n{\n    var text = txtSomething.Text;\n    txtSomething.Text = text.Remove(text.Length - 1);\n}	0
4248152	4248116	Using XDocument to search and extract Data	XDocument addresses = XDocument.Parse((string)returnScalar);\nvar address = addresses.Root.Elements("Address").Where(address => address.Element("LetterQueueOID").Value == "2").FirstOrDefault();	0
9181495	9181389	Linq to SQL Server - difficulty with sub-query example	db.Applog.GroupBy(a=>a.SessionID).Select(g=>g.OrderBy(m=>m.Timestamp).First());	0
3871285	3870276	Wlan information in mono on linux	iwconfig\niwlist	0
34156519	34155955	How to write mock unit test case for ExecuteNonQuery & ExecuteScalar & GetDataSet method	interface IDatabaseManager\n{\n  IDbConnection OpenConnection(string databaseName);\n  IDbCommand CreateCommand(string command, IDbConnection connection);\n}\n\n\nclass MyClass\n{\n    private IDatabaseManager  _databaseManager;\n    public MyClass(IDatabaseManager databaseManager)\n    {\n        _databaseManager = databaseManager;\n    }\n\n    public void ExecutScalarMethod()\n    {\n        using (var objCon = _databaseManager.OpenConnection(DBNAME))\n        {\n          objCon.Open();\n          using (SQLiteCommand objCmd = _databaseManager.CreateCommand(strSQL, objCon))\n          {\n                objRetValue = objCmd.ExecuteScalar();\n                objCmd.Dispose();\n          }\n          objCon.Close();\n          objCon.Dispose();\n        }\n    }\n}	0
33607956	33388314	Convert char[] to byte[] results in higher count	cc.Select(c=>(byte)c).ToArray();	0
8248685	8248579	C# using Tuple with Sum	CalculPoids = p.Poids/(Enumerable.Repeat(10, p.Sum / 10).Concat(Enumerable.Repeat(p.Sum % 10, 1))).Count()	0
33003056	32970171	How to get request headers from the CefSharp browser?	IRequestHandler.OnBeforeBrowse	0
6680683	6680262	Obtaining the datalists row details	protected void DataList1_ItemCommand(object source, DataListCommandEventArgs e)\n{\n    // Will give you current data key value\n    Int32 threadID = Convert.ToInt32(e.CommandArgument); \n    // if you want value of your control\n    (ControlTypd)e.Item.FindControl("ControldId")\n}	0
14585506	14585453	store query data in variables	foreach (var query in queryAD1)\n{\n    str1 = query.sortByColumn;\n    str2 = query.numberOfRow;\n    str3 = query.coloumnsInExcel;\n\n    //do something with the variables...\n}	0
21445149	21445052	Fastest way to insert data from a column in all DataTables in a DataSet to a List	var listEmail = (from DataTable table in emailTables.Tables \n                 from DataRow row in table.Rows \n                 select row["yourColumnNameHere"].ToString()).ToList();	0
29425585	29425134	Universal app HttpClient header: how to disable some of the headers?	Authorization: Basic ??aaaaaaa	0
1374039	1373966	Regex matching too much	(\[[cC]=)(#?([a-fA-F0-9]{3}){1,2})\](.*?)\[/[cC]\]\n//                                     ^- lazy match	0
10851345	10832014	Using DecelerationEnded interferes with other callbacks	public virtual Source CreateSizingSource (bool unevenRows)\n{\n    return unevenRows ? new SizingSource (this) : new Source (this);\n}	0
428799	428766	Quickest way to implement a new interface member in many classes?	internal interface IFoo\n{\n    void Boo()\n    {\n    }\n}\n\nclass Boo:IFoo\n{\n}\n\nclass Foo: IFoo\n{\n}	0
5374706	5374679	A Class with a generic constrainst while inheriting from another class?	public class MySubclass<T> : SomeClass where T : TBaseClass { }	0
863107	863094	Represent array in C#	ToString()	0
7120336	7120310	DateTime.now subtraction with value from database	DateTime dt1 = DateTime.Now;\nDateTime dt2 = DateTime.Parse(user[3]);\n\nTimeSpan ts = dt1 - dt2;\n\nint days = ts.Days;\n\nif (days == 30){\n   //do something\n}	0
20894997	20882884	Retrieve Single IP Address from WMI Query in C#.NET	foreach( ManagementObject NetworkObj in NetworkSearcher.Get() )\n{\nstring[] arrIPAddress = (string[])( NetworkObj["IPAddress"] );\n\nsIPAddress = arrIPAddress.FirstOrDefault( s => s.Contains( '.' ) );\n\nif( sIPAddress != null ) break;\n}	0
29589806	29589742	Accessing button's variable from diffrent button (c# form)	bool second, third , forth , fifth = false;\nprivate void button1_Click(object sender, EventArgs e)\n{\n    //Those my bool variable I want to access from the second button\n    second = false; \n    third = false; \n    forth = false; \n    fifth = false;\n}\nprivate void button4_Click(object sender, EventArgs e)\n{\n    second = true;\n}	0
27488884	27488787	How to find whether a number is even or odd using C#?	value % 2 == 0;	0
18870037	18869896	Use custom powershell module in C#	PowerShell pShell = PowerShell.Create();\npShell.Commands.AddCommand("import-module").AddParameter("Name","DocConverter2");\npShell.Invoke();\n...\nrest of you code here\n...	0
13579658	13563019	WCF https with only server certificate	System.Net.ServicePointManager.ServerCertificateValidationCallback += new System.Net.Security.RemoteCertificateValidationCallback(RemoteCertValidateCallback);\n public static bool RemoteCertValidateCallback(object sender, X509Certificate cert, X509Chain chain, System.Net.Security.SslPolicyErrors error)\n        {\n            return true;\n        }	0
913942	913694	Download a file over HTTPS C# - Cookie and Header Prob?	Using System.Net;\n\n// Create Cookie Container (Place to store cookies during multiple requests)\n\nCookieContainer cookies = new CookieContainer();\n\n// Request Page\nHttpWebRequest req = (HttpWebRequest)WebRequest.Create("https://www.amazon.com");\nreq.CookieContainer = cookies;\n\n// Response Output (Could be page, PDF, csv, etc...)\n\nHttpWebResponse resp= (HttpWebResponse)req.GetResponse();\n\n// Add Response Cookies to Cookie Container\n// I only had to do this for the first "login" request\n\ncookies.Add(resp.Cookies);	0
21265050	21249955	Is this possible to change or set the Padding Color of a Windows Form?	protected override void OnPaintBackground(PaintEventArgs e)\n{\n    //base.OnPaintBackground(e);  //comment this out to prevent default painting\n    using (SolidBrush brush = new SolidBrush(Color.Purple))  //any color you like\n        e.Graphics.FillRectangle(brush, e.ClipRectangle);\n}	0
17964813	17959359	Configuring Associated WCF Web Role IP on Azure	web.cloud.config	0
21379044	21337012	Transform a FrameworkElement to a Stream without saving to a file	private async void testCartoon_Tap(object sender, System.Windows.Input.GestureEventArgs e)\n{\n\n   //the panel I want as an Image\n   var rootElement = ContentPanel as FrameworkElement; \n\n   WriteableBitmap myWB = new WriteableBitmap((int)rootElement.ActualWidth,    (int)rootElement.ActualHeight);\n   myWB.Render(rootElement, new MatrixTransform());\n   myWB.Invalidate();\n\n\n    using (var stream = new MemoryStream())\n    {\n\n      myWB.SaveJpeg(stream, myWB.PixelWidth, myWB.PixelHeight, 0, 100);\n\n      stream.Seek(0, SeekOrigin.Begin);\n\n      var backgroundSource = new StreamImageSource(stream);\n\n      var filterEffect = new FilterEffect(backgroundSource);\n\n      CartoonFilter cartoonFilter = new CartoonFilter();\n\n      filterEffect.Filters = new[] { cartoonFilter };\n\n      var renderer = new WriteableBitmapRenderer(filterEffect, _cartoonImageBitmap);\n\n      _cartoonImageBitmap = await renderer.RenderAsync();\n\n      ImageCartoon.Source = _cartoonImageBitmap;\n    }\n\n}	0
22746710	22746681	Getting a datetime variable from a database using dataTableReader	var datetime = DateTime.Parse("string");	0
25841590	25841466	Load an xml file more than 0kb	var fileInfo = new System.IO.FileInfo(fileName); //where fileName is the full path to the XML file\n\nif (fileInfo.Length > 0)\n{\n    //read the xml\n}	0
12194571	12194333	Suggestions for starting a entity framework code first project from scratch	nvarchar(MAX)	0
11679887	11679828	Detecting light projections in 2D space using C#	Math.abs(lights[n].X - position.X) == Math.abs(lights[n].Y - position.Y)	0
29523435	29522102	How to fill a combobox from a MS Access text field then insert combobox selection into another table	string name = this.comboBox2.Text;	0
3902737	3902623	How do I implement this graph/tree data structure in C#/SQL?	Graph<T>	0
16978492	16977011	How to draw a board with chalky lines?	namespace DrawSomeStuff\n{\npublic partial class MainWindow : Window\n{\n    Point mousePosition;\n    Image chalk;\n\n    public MainWindow()\n    {\n        InitializeComponent();\n    }\n\n    private void Grid_MouseDown(object sender, MouseButtonEventArgs e)\n    {\n        //Get mouse position\n        mousePosition = Mouse.GetPosition(this);\n\n        //Set chalk\n        chalk = new Image();\n        chalk.RenderSize = new Size(5, 5);\n        //Set chalk image\n\n        //Move and add chalk\n        chalk.TranslatePoint(mousePosition, this);\n        this.AddChild(chalk);\n    }\n}\n}	0
22078496	22078204	How to get DataGridView AutoComplete to show for only one column?	private void dgvDVDetails_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)\n{\n    if (dgvDVDetails.CurrentCell.ColumnIndex == 1)\n    {\n        TextBox prodCode = e.Control as TextBox;\n        if (prodCode != null)\n        {\n            prodCode.AutoCompleteMode = AutoCompleteMode.SuggestAppend;\n            prodCode.AutoCompleteCustomSource = ClientListDropDown();\n            prodCode.AutoCompleteSource = AutoCompleteSource.CustomSource;\n\n        }\n    }\n   else\n   {\n       TextBox prodCode = e.Control as TextBox;\n       if (prodCode != null)\n        {\n            prodCode.AutoCompleteMode = AutoCompleteMode.None;\n        }\n   }\n}	0
16514018	16513931	Windows Phone 8 SDK - WebBrowser Control - How to refresh page from code	private void browser_Navigated(object sender, NavigationEventArgs e) {\n  lastUri = e.Uri;\n}\n\nprivate void Refresh() {\n  browser.Navigate(lastUri);\n}	0
31730800	31730759	Optional Parameters in Web Method	public string GetMatchingCompanies(string term, int companyPickerMode, int? officeId = null, int? proposalId = null)\n{\n    // ...\n}	0
2402849	2402823	Can I integrate many sources into one RSS reader?	System.ServiceModel.Syndication	0
11603037	11602977	Compare many pairs of bools	var tests = new[] { test1, test2, test3, test4, ... };\n\nfor (int i = 0; i < tests.Length - 1; ++i) {\n   if (tests[i] && tests[i + 1]) {\n     // Do stuff\n     break;\n   }\n}	0
2121528	2121500	What are the steps necessary in creating a community driven website?	* Enables job seekers to post resumes\n* Enables job seekers to search for job postings\n* Enables employers to enter profile of their company\n* Enables employers to post one or more job postings	0
1592380	1592136	WPF and 3D how do you change a single position point in 3D space?	for (var i = 0; i < positions.Count; i++)\n        {\n            Point3D position = positions[i];\n            position.Z += 5;\n            positions[i] = position;\n        }	0
6438902	6438858	How to bind a function to Click event of each control in an array of controls in C#	int index = i;    \nbuttons[index].Click += (sender, e) => myClick(index);	0
7300254	7300075	How to parse a string to find key-value pairs in it	string s = "from:devcoder hasattachments:true mySearchString on:11-aug";\n\nvar keyValuePairs = s.Split(' ')\n    .Select(x => x.Split(':'))\n    .Where(x => x.Length == 2)\n    .ToDictionary(x => x.First(), x => x.Last());	0
8986714	8985849	IPersistable Interface - Any trick or hack to change field name	class Persistable<T>\n{\n    public Persistable<T>(string PersistanceId, T Data)\n\n    public readonly string PersistanceId;\n    public readonly T Data;\n}	0
30367612	30367466	Having issue with paging in Asp.net Membership	public static MembershipUserCollection GetAllUsers(\n    int pageIndex,\n    int pageSize,\n    out int totalRecords\n);	0
17856763	17856682	remove item in dictionary using value	m_banlists[BanList.Items[BanList.SelectedIndex].ToString()].ToList().RemoveAll(x=>x.ID==someId);	0
8629429	8629418	How to get the first and the last parts of string separated by a space	string sString = "john depp lennon";\nstring[] sArray = sString.Split(' ');\n\nstring sStartEnd = sArray[0] + " " + sArray[sArray.Count()-1]; // "john lennon"	0
14095839	14095815	declaring var inside if statement c#	IEnumerable<DateTime> days;\n\nif (DateTime.Today.Day > 28 && DateTime.Today.Day < 2)\n{\n    days = GetDaysLikeMe(calendario.Value.Date).Take(50).Where(d => d.Date.Day > 28 && d.Date.Day < 2).Take(4);\n}\nelse\n{\n    days = GetDaysLikeMe(calendario.Value.Date).Take(50).Where(d => d.Date.Day < 28 && d.Date.Day > 2).Take(4);\n}	0
2382955	2382802	C# Read Sharepoint List - Without Automagic	Lists.asmx	0
31662998	31661857	Update object from the view inside the controller	[HttpPost]\n[ValidateAntiForgeryToken]\npublic ActionResult Edit(JobVM jobVM) {\n\n      // validate VM\n      // ...\n      // the following code should be in the Service Layer but I'll write it below to simplify\n      // get job from DB\n      var job = db.Jobs.SingleOrDefault(p => p.Id == jobVM.Id);\n\n      job.JobTypesID = jobVM.JobTypesID;\n\n      job.JobStatusID = jobVM.StatusId;\n\n      db.SaveChanges();\n      return RedirectToAction("Index");\n }	0
5394549	5393735	Visual Studio 2008 - SQL statement to update datagridview	Pseudo Code:\n    1.  Get the ID you want to filter for.\n    2.  Pass the ID to a SQL statement.\n    3.  Open a connection to the database.\n    4.  Execute the SQL via a SQL command.\n    5.  Store the result.\n    5.  Close the open connection.\n    6.  Databind the results to your datagrid.	0
28982912	28982869	How to manually deploy a CLR stored procedure?	CREATE ASSEMBLY HandlingLOBUsingCLR\nFROM '\\MachineName\HandlingLOBUsingCLR\bin\Debug\HandlingLOBUsingCLR.dll';\nGO\n\nCREATE PROCEDURE dbo.GetPhotoFromDB\n(\n    @ProductPhotoID int,\n    @CurrentDirectory nvarchar(1024),\n    @FileName nvarchar(1024)\n)\nAS EXTERNAL NAME HandlingLOBUsingCLR.LargeObjectBinary.GetPhotoFromDB;\nGO	0
19856000	19854759	Implement a generic C++/CLI interface in a C# generic interface	generic <class T>\n    public interface class IElementList {\n        property List<T>^ Elements {\n            List<T>^ get();\n        }\n    };	0
21456576	21456493	get file path from dialogresult	System.IO.Path.GetFullPath(....)	0
13438291	13437059	Trigger formatting cells of DataGridView from the SelectedIndexChanged event of a combobox?	private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)\n        {\n\n            var c = dataGridView1.Columns.Count;\n             foreach (DataGridViewRow row in this.dataGridView1.Rows)\n                {\n                    if (comboBox1.SelectedValue==1){\n                                row.Cells[0].Style.BackColor = Color.Green;\n                                row.Cells[0].ToolTipText = "test";\n                        }\n\n            else\n            {\n                        row.Cells[0].Style.BackColor = Color.Blue;\n                        row.Cells[0].ToolTipText = "test";\n                }\n            }\n    }\n\nThanks	0
12816899	12816860	Get screen size in pixels in windows form in C#	Screen.PrimaryScreen.Bounds.Width;\nScreen.PrimaryScreen.Bounds.Height;\nScreen.PrimaryScreen.Bounds.Size;	0
31301046	31259740	Accept mobile but not fixed-line numbers using Google's libphonenumber library	if (phoneUtil.GetNumberType(mobile).ToString() == "MOBILE") return true	0
2893326	2893059	Autoresize textbox control vertically	private void textBox1_TextChanged(object sender, EventArgs e) {\n        Size sz = new Size(textBox1.ClientSize.Width, int.MaxValue);\n        TextFormatFlags flags = TextFormatFlags.WordBreak;\n        int padding = 3;\n        int borders = textBox1.Height - textBox1.ClientSize.Height;\n        sz = TextRenderer.MeasureText(textBox1.Text, textBox1.Font, sz, flags);\n        int h = sz.Height + borders + padding;\n        if (textBox1.Top + h > this.ClientSize.Height - 10) {\n            h = this.ClientSize.Height - 10 - textBox1.Top;\n        }\n        textBox1.Height = h;\n    }	0
6953856	6941742	How to Kill the exe in taskmanager?	private void Form1_FormClosed(object sender, FormClosedEventArgs e)\n{\n    Application.Exit();                \n}	0
28384578	28383822	c# best way to match yahtzee	public bool Yahtzee()\n{\n     // check if all dobbelstenen[int] are the same\n     for(int i = 1; i < 5; i++) // start with second dobbelstenen\n     {\n          if(dobbelstenen[i] != dobbelstenen[0]) return false;\n     }\n     return true;\n}	0
23030509	23030405	Sort List Ascending and write to ListBox	MyList m = new MyList();\n\nm.Add("n1", DateTime.Now);\nm.Add("n2", DateTime.Now.AddDays(1));\nm.Add("n3", DateTime.Now.AddDays(-1));\n\nvar sortedList = from i in m\n    orderby i.expires\n    select i;\nlistBox1.Items.AddRange(sortedList.ToArray());	0
24872594	22602890	Compiled regex performance not as expected?	var regex = new Regex("/", RegexOptions.Compiled);	0
24010270	24010045	Stored procedure/query two variable comparison	CREATE PROCEDURE GetHash\n    @Name nvarchar(50),\n    @Hash nvarchar(200)\n\nAS\nBEGIN\n    SET NOCOUNT ON;\n\n    SELECT Orders.orderId, \n           Employee.name, \n           Employee.surname\n    FROM Orders \n    LEFT JOIN Employee\n        ON Orders.orderId=Employee.id\n    WHERE batchName = @Name\n    AND productCode = @Hash\nEND	0
1781704	1781569	How do I pass installation dir from the installer to a custom action?	Context.Parameters["TARGETDIR"]	0
16686547	16686511	Calling method from another class from another file C#	GetUser.MyFeedClass myfeed = new GetUser.MyFeedClass();\nstring result = myfeed.getUserID();	0
16555248	16555181	Getting name of Page being requested/was requested	public string GetPageName() \n{ \n    string path = System.Web.HttpContext.Current.Request.Url.AbsolutePath; \n    System.IO.FileInfo info = new System.IO.FileInfo(path); \n    return info.Name; \n}	0
20629741	20629565	How to Access Programmatically Added checkbox	var chkControl = Page.FindControl("chk");\nif(chkControl != null /*&& check type*/) {\n  CheckBox chk = (CheckBox)chkControl;\n// and do something\n}	0
33611255	33593020	Generic Method for Mock (Moq library) to verify a method was NEVER called with ANY parameter combination	Setup()	0
12656626	12656373	Start a console application from a WCFService	Program.Main(args);	0
13454598	13453992	Cell double click event in data grid view	System.Windows.Forms.Timer t;\n        public Form1()\n        {\n            InitializeComponent();\n\n            t = new System.Windows.Forms.Timer();\n            t.Interval = SystemInformation.DoubleClickTime - 1;\n            t.Tick += new EventHandler(t_Tick);\n        }\n\n        void t_Tick(object sender, EventArgs e)\n        {\n            t.Stop();\n            DataGridViewCellEventArgs dgvcea = (DataGridViewCellEventArgs)t.Tag;\n            MessageBox.Show("Single");\n            //do whatever you do in single click\n        }\n\n        private void dataGridView1_CellClick_1(object sender, DataGridViewCellEventArgs e)\n        {\n            t.Tag = e;\n            t.Start();\n        }\n\n        private void dataGridView1_CellDoubleClick(object sender, DataGridViewCellEventArgs e)\n        {\n            t.Stop();\n            MessageBox.Show("Double");\n            //do whatever you do in double click\n        }	0
3750178	3750144	Status Messageboxes going behind the application	MessageBox.Show(this,"Your Message");	0
5119323	5119256	How to fill a Combo Box on C# with the namefiles from a Dir?	private void Form1_Load(object sender, EventArgs e)\n    {\n        string[] files = System.IO.Directory.GetFiles(@"C:\Testing");\n\n        this.comboBox1.Items.AddRange(files);\n    }	0
7082479	7082419	How to calculate/determine Folder Size in .NET?	public static long Size(this DirectoryInfo Directory, bool Recursive = false)\n    {\n        if (Directory == null)\n            throw new ArgumentNullException("Directory");\n        return Directory.EnumerateFiles("*", Recursive ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly).Sum(x => x.Length);\n    }	0
5499964	5498509	Cropping a bitmap gives an empty bitmap	Rectangle rect = new Rectangle(625, 778, 475, 22);\n\n    Bitmap bitmap = Bitmap.FromFile(@"C:\m.png") as Bitmap;\n\n    Bitmap croppedBitmap = new Bitmap(bitmap, rect.Width, rect.Height);\n    croppedBitmap.SetResolution(bitmap.HorizontalResolution, bitmap.VerticalResolution);\n\n    using (Graphics gfx = Graphics.FromImage(croppedBitmap))\n    {\n        gfx.DrawImage(bitmap, 0, 0, rect, GraphicsUnit.Pixel);\n    }\n\n    croppedBitmap.Save(@"C:\m-1.png", System.Drawing.Imaging.ImageFormat.Png);	0
33409849	33409364	Calling a generic method with interface instances	public interface IFeature\n{\n    void Accept(Visitior visitor);\n}\n\npublic class FeatureA : IFeature\n{\n    public void Accept(Visitior visitor)\n    {\n        visitor.Visit(this);\n    }\n}\n\npublic class FeatureB : IFeature\n{\n    public void Accept(Visitior visitor)\n    {\n        visitor.Visit(this);\n    }\n}\n\npublic class Visitior\n{\n    public void Visit<TFeature>(TFeature feature) where TFeature : IFeature\n    {\n        Console.WriteLine(typeof(TFeature) == feature.GetType());//True\n    }\n}\n\nstatic void Main(string[] args)\n{\n    List<IFeature> features = new List<IFeature>\n    {\n         new FeatureA(),\n         new FeatureB()\n    };\n\n    Visitior visitor = new Visitior();\n    foreach (var item in features)\n    {\n        item.Accept(visitor);\n    }\n}	0
13162906	13162879	Split a string on the Empty Character literal. Break apart a string's symbols into an array	var chars = "00101010".Select(c => c.ToString()).ToArray();	0
3121624	3121353	Subsonic Simple Repository - Persist Private Property	namespace App.BackEnd // classes here are used for database storage\n{\n    public class X\n    {\n        public string abc { get; set; }\n        public string def { get; set; }\n\n        public FrontEnd.X ToFrontEnd()\n        {\n            return new FrontEnd.X\n            {\n                abc = abc\n            };\n        }\n    }\n}\n\nnamespace App.FrontEnd // classes here are used for public interfaces\n{\n    public class X\n    {\n        public string abc { get; set; }\n    }\n}	0
13366285	13365842	How can I access my ViewModel from the View and associated code behind file?	[HttpGet]\npublic ActionResult Index(int somethingICareAbout)\n{\n  return View(new IndexViewModel(somethingICareAbout));\n}\n\n[HttpPost]\npublic ActionResult Index(IndexViewModel viewModel)\n{\n  viewModel.SaveChanges()/DoWork()/Whatever();\n  return View(new viewModel());\n}	0
9069754	9069352	Responsive UI in windows form accessing device data	public void StartFooAsync() {\n    Thread thread = new Thread(new ThreadStart(DoFooAsync));\n    thread.IsBackground = true;\n    thread.Start();\n}\n\nprivate void DoFooAsync() {\n    while (m_Running) {\n        // Do something\n        Thread.Sleep(20ms); // Make the thread wait your 20ms\n    }\n}	0
4388030	4079258	How to resize the Smart-Tags panel to a bigger size when used on a usercontrol?	const int numCharsForSpacing = 30;\nnew DesignerActionTextItem (new string ('\x01', numCharsForSpacing ), null),	0
34399435	34399061	C# WPF mysql string	cmd.CommandText = "SELECT * FROM book left join author on book.author_id=author.id where book.name like ('" + Filter.Text + "%') and book.author_id=author.id";	0
783027	783011	LinqToXML: Getting elements with given value	xml.Descendants("value")	0
5816915	5816867	Application path	path = System.IO.Path.GetDirectoryName( \n      System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase );	0
3951846	3951693	How to RegEx replace regions into a collection	public partial class Form1 : Form\n{\n    public Form1()\n    {\n        InitializeComponent();\n    }\n\n    private void button1_Click(object sender, EventArgs e)\n    {\n        outputTextBox.Text = "";\n        Regex regex = new Regex("(<!--RegionStart url=\"http://(.*?)\"-->)(.*?)(<!--RegionFinish-->)", RegexOptions.Singleline);\n\n        string copy = inputTextBox.Text;\n        MatchCollection coll = regex.Matches(inputTextBox.Text);                \n        outputTextBox.Text = regex.Replace(copy, new MatchEvaluator(Replace));\n    }\n\n    public string Replace(Match m)        \n    {\n        // Format the text you want to get back:\n        return String.Format("{0}{1} {2}{3}", \n            m.Groups[1].ToString() + Environment.NewLine, \n            m.Groups[3].ToString().Replace("some", "all").Trim(),\n            m.Groups[2].ToString().Trim() + Environment.NewLine, \n            m.Groups[4].ToString());\n    }\n}	0
17564098	17560014	Microsoft Shims with a WCF Service	ShimChannelFactory<IService0>.AllInstances.CreateChannel = (_) => { return new Service0Mock(); }\nShimChannelFactory<IService1>.AllInstances.CreateChannel = (_) => { return new Service1Mock(); }\nShimChannelFactory<IService2>.AllInstances.CreateChannel = (_) => { return new Service2Mock(); }	0
13592670	13591727	How to return a list of entities that are not in a given list	var notGuids = from c in notClients\n               select c.ClientId;\n\nvar clients = unitOfWork.Session.CreateCriteria(typeof(Client))\n    .Add(Expression.Not(Expression.In("ClientId", notGuids.ToArray()))).List<Client>();	0
11274167	11274138	An alternative to Dictionary<T,T>	class PrintJob\n{\n    public int printRepeat {get; set;}\n    public string printText {get; set;}\n    // If required, you could add more fields\n}\n\nList<PrintJob> printJobs = new List<PrintJob>()\n{\n    new PrintJob{printRepeat = 2, printText = "Hello World"},\n    new PrintJob{printRepeat = 2, printText = "Goodbye World"}\n}\n\nforeach(PrintJob p in printJobs)\n    // do the work	0
19136810	19136706	WPF MVVM Binding refresh to display status	var task = Task.Factory.StartNew(() =>\n                      {\n                          //This invokes UI specific code inside module initialization\n                          LoadDataNow();\n                      });\ntask.ContinueWith(t => StatusMessageVisibility = Visibility.None, \n                       TaskScheduler.FromCurrentSynchronizationContext());	0
11476389	11476258	How can I internally keep an always nullable equivalent of a generic type parameter?	public class ListProperty<TListItem, TValueStruct, TValueClass> \nwhere TValueStruct : struct\nwhere TValueClass : class\n{\n\n}	0
2820859	2820238	Removing Elements Programatically in Silverlight	UIElement[] tmp = new UIElement[LayoutRoot.Children.Count];             \nLayoutRoot.Children.CopyTo(tmp, 0);  \n\nforeach (UIElement aElement in tmp)\n{\n    Shape aShape = aElement as Shape; \n\n    if (aShape != null && aShape.Tag != null)\n    {\n\n        if (aShape.Tag.ToString().Contains("Bullet"))\n        {\n            if (Canvas.GetTop(aShape) + aShape.ActualHeight < 0) // This checks if it leaves the top\n            {\n                LayoutRoot.Children.Remove(aElement);\n            }\n            else if(Canvas.GetTop(aShape) > Canvas.ActualHeight) // This condition checks if it leaves the bottom\n            {\n                LayoutRoot.Children.Remove(aElement);\n            }\n        }\n    }\n}	0
14559350	14559264	winforms MDI how to make a child form look like a natural part of the parent	private void FormLoad(object sender, EventArgs e)\n{\n    FormBorderStyle = FormBorderStyle.None;\n    WindowState = FormWindowState.Maximized;\n}	0
9908980	9908746	Adding new variables to variable array	GetComponent<productManager>().ingredient.Add(new ingredients { name = ingUnlock[locklevel].name, icon = ingUnlock[locklevel].icon });	0
7876398	7876333	Modify private readonly member variable?	typeof(MyClass)\n   .GetField("name",BindingFlags.Instance|BindingFlags.NonPublic)\n   .SetValue(myclassInstance, 123);	0
4781441	4781362	how to rotate pdf using itextsharp library	Document doc = new Document(PageSize.A4.Rotate());	0
16169329	16075856	Retrive data from xml file into a datagridview in c#.net	for (int i = 0; i <= 11; i++)\n{\n    ds.ReadXml(@"C:\Users\dell\Downloads\ChillerReport.xml");\n    dataGridView1.DataSource= ds.Tables[i].DefaultView;\n}	0
20836813	20834217	How to retieve a excel file from sql database	DataTable dtReport = GetDataFromDatabase(fileID: 20);     \n Response.Clear();\n Response.Buffer = true;\n Response.ContentType = Path.GetExtension(dtReport["FileName"]).ToString();\n Response.AddHeader("content-disposition", "attachment;filename=" + Path.GetFileName(dtReport["FileName"]).ToString());\n Response.ContentType = Path.GetExtension(dtReport["FileName"]).ToString();\n Response.Charset = "";\n Response.Cache.SetCacheability(HttpCacheability.NoCache);\n Response.BinaryWrite((byte[])dtReport["Data"]);\n Response.End();	0
33509400	33508861	Splitting String with exception?	string text = "224|3|0|0|0|0|0|0|0|0|0|0|0|0|2|You go back the person from the Future.|1|You will be moved.|82|0|0|0|0|0|0|0|0|0|0|0|0|0|0|81|0|0|0|";\n\nvar first = String.Join("", text.TakeWhile(c => Char.IsDigit(c) || c == '|'));\n\nvar third = String.Join("", text.Reverse().TakeWhile(c => Char.IsDigit(c) || c == '|').Reverse());\n\nvar second = text.Replace(first, "").Replace(third, "");	0
8711908	8711662	Representing a Char with equivalent string	public override string ToString()\n{\n    return ToLiteral(Text + " '" + Value + "'");\n}\n\nprivate string ToLiteral(string input)\n{\n    var writer = new StringWriter();\n    CSharpCodeProvider provider = new CSharpCodeProvider();\n    provider.GenerateCodeFromExpression(new CodePrimitiveExpression(input), writer, null);\n    return writer.ToString();\n}	0
24884890	24883770	DbSet Groups containing DbSets	public class Context : DbContext\n{\n    public DbSet<Group> Groups { get; set; }\n}\n\npublic class Group\n{\n    public List<User> Members { get; set; }\n    public List<Article> Articles { get; set; }\n    public List<Customer> Customers { get; set; }\n}	0
21990170	21989547	Calculating offset from two hex strings	private void getOffSet(byte one, byte two)\n{\n  byte baseByte = 0x80;\n\n  int defaultOffset = 0x0418;\n\n  int mul = (one - baseByte) % 8;\n\n  int result = mul * 0x2000 + defaultOffset;\n  result += two * 0x0020;\n\n  Console.WriteLine(result.ToString("X"));\n}	0
16711470	16711265	How to use save dialog to save an xml file from the cell click event of DataGridView Cells?	if (saveFileDialog1.ShowDialog() == DialogResult.OK)\n{\n                    doc.Save(saveFileDialog1.FileName);                   \n}	0
34158614	34158498	How to delete the auto-generate first line in a RichTextBox	rt.Document.Blocks.Remove(rt.Document.Blocks.FirstBlock);	0
1987252	1987245	Byte[] to String to Byte[] -- How to do so?	string s = Convert.ToBase64String(byteArray);\nbyte[] decoded = Convert.FromBase64String(s);	0
3032948	3032879	Can I pass a querystring that translates to a List<int> on the server?	?amenityTypes=1&amenityTypes=5	0
7655843	7655603	How to get data from TCPPacket using SharpPcap?	packet.PayloadPacket.PayloadPacket.PayloadData	0
2660551	2660532	Using a custom IList obtained through NHibernate	public class MyDTO\n{\n    public string thread_topic { get; set; }\n    public DateTime post_time { get; set; }\n    public string user_display_name { get; set; }\n    public string user_signature { get; set; }\n    public string user_avatar { get; set; }\n    public string post_topic { get; set; }\n    public string post_body { get; set; }\n}\n\nvar whatevervar = session.CreateSQLQuery(@"select thread_topic, post_time, user_display_name, user_signature, user_avatar, post_topic, post_body\n    from THREAD, [USER], POST, THREADPOST\n    where THREADPOST.thread_id=" + id + " and THREADPOST.thread_id=THREAD.thread_id and [USER].user_id=POST.user_id and POST.post_id=THREADPOST.post_id\n    ORDER BY post_time;")\n.SetResultTransformer(Transformers.AliasToBean(typeof(MyDTO)))\n.List();	0
13366163	13366048	Using Base Class as overload in MVC Action, but collecting all data	public ActionResult RowCheckedStatusChanged(BaseGridRowModel row, string otherdataItem1, string otherdataItem2)	0
6662324	6662280	Delayed firing of custom event	private void RaiseDelayedTextChangedEvent()\n    {\n        RoutedEventArgs newEventArgs = new RoutedEventArgs(DelayTextBox.DelayedTextChangedEvent);\n\n        this.Dispatcher.BeginInvoke(\n                System.Windows.Threading.DispatcherPriority.Normal,\n                (UpdateTheUI)delegate(RoutedEventArgs eArgs)\n                {\n                   RaiseEvent(eArgs);\n                }, newEventArgs );\n\n    }	0
10240108	10239518	How do I split a phrase into words using Regex in C#	new Regex(@"[^\p{L}]*\p{Z}[^\p{L}]*")	0
20561640	20560157	Stored Procedure for date ranges in a single column	declare @t table(EntryId int identity(1,1), StageId int,ContractId varchar(10),DateofStageChange date)\ninsert into @t values \n(1,'C1','2013-10-20'),(1,'C1','2013-10-22'),(2,'C1','2013-10-22'),(2,'C1','2013-10-25')\n,(3,'C1','2013-10-25'),(3,'C1','2013-10-26'),(1,'C1','2013-10-26'),(1,'C1','2013-10-28') \n\nSelect StageId,sum([noOfDays]) [totalNofDays] from \n(select a.StageId,a.ContractId,a.DateofStageChange [Fromdate],b.DateofStageChange [ToDate]  \n,datediff(day,a.DateofStageChange,b.DateofStageChange) [noOfDays]\nfrom @t a\ninner join @t b on a.StageId=b.StageId and b.EntryId-a.EntryId=1)t4\ngroup by StageId	0
6275653	6275616	Keeping a session when using HttpWebRequest	private CookieContainer cookieContainer = new CookieContainer();\npublic bool isServerOnline()\n{\n        Boolean ret = false;\n\n        try\n        {\n            HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(VPMacro.MacroUploader.SERVER_URL);\n            req.CookieContainer = cookieContainer; // <= HERE\n            req.Method = "HEAD";\n            req.KeepAlive = false;\n            HttpWebResponse resp = (HttpWebResponse)req.GetResponse();\n            if (resp.StatusCode == HttpStatusCode.OK)\n            {\n                // HTTP = 200 - Internet connection available, server online\n                ret = true;\n            }\n            resp.Close();\n            return ret;\n\n        }\n        catch (WebException we)\n        {\n            // Exception - connection not available\n            Log.e("InternetUtils - isServerOnline - " + we.Status);\n            return false;\n        }\n}	0
7591898	7591846	Help on extracting a string pattern, typically conference id from a meeting invitation	var str = "< meeting agenda text... .... Conference Id : *12322# .... more text.... />";\nvar re = new Regex(@"Conference Id : \*(\d+)");\nvar m = re.Match(str);\nif (m.Success)\n{\n    Console.WriteLine(m.Groups[1]);\n}	0
27686086	27686047	How to write sub queries using Linq extension methods with EF 6	var excludeIDs = db.TraineeCourseEnrollments.Where(w => w.TraineeID == traineeid).Select(s => s.CourseID);\nvar courses = db.Courses.Where(w =>!excludeIDs.Contains(w.ID)).ToList();	0
8083020	8080810	How to create auto dialer in iPhone using MonoTouch?	UIApplication.SharedApplication.OpenUrl(NSUrl.FromString("tel://1234567890"));	0
12287840	12195681	Read XML values Webservice	XmlDocument doc = new XmlDocument();\nSystem.Xml.Serialization.XmlSerializer serializer2 = new System.Xml.Serialization.XmlSerializer(Patients.GetType());\nSystem.IO.MemoryStream stream = new System.IO.MemoryStream();\nserializer2.Serialize(stream, Patients);\nstream.Position = 0;\ndoc.Load(stream);	0
12421152	12420141	deleting row from datagridview	_dt.AcceptChanges();	0
412644	412632	How do I retrieve disk information in C#?	using System;\nusing System.IO;\n\nclass Info {\n    public static void Main() {\n        DriveInfo[] drives = DriveInfo.GetDrives();\n        foreach (DriveInfo drive in drives) {\n            //There are more attributes you can use.\n            //Check the MSDN link for a complete example.\n            Console.WriteLine(drive.Name);\n            if (drive.IsReady) Console.WriteLine(drive.TotalSize);\n        }\n    }\n}	0
22740521	22740457	I want to get two specific directories using getdirectories method	var location = ConfigurationManager.AppSettings["SourceLocation"].ToString();\nDirectoryInfo sourcefolder = new DirectoryInfo(location);\nvar sourceRreportSubfolders = sourcefolder.GetDirectories("20120104")\n                             .Union(sourcefolder.GetDirectories("20130302"));\nforeach (var dir in sourceRreportSubfolders)\n{\n    // Do something with dir\n}	0
14291390	14291280	How to get all values in a certain GridView column?	protected void GridView1_RowDeleted(object sender, GridViewDeletedEventArgs e)\n{\n   var val = e.Values["img_cat"];\n   if (!(sender as GridView).Cast<GridViewRow>().Any(x => x["img_cat"] == val))\n   {\n       //It's the last one, do something.\n   }\n}	0
25788171	25787108	Launching debugger in windows service	Debugger.Launch();\nDebugger.Break();	0
508261	508227	How to import const char* API to C#?	[DllImport("zip4_w32.dll",\n       CallingConvention = CallingConvention.StdCall,\n       EntryPoint = "z4LLkGetKeySTD",\n       ExactSpelling = false)]\n   private extern static IntPtr z4LLkGetKeySTD();	0
19421621	19421310	DataGrid in WPF using VisualStudio C#	ObservableCollection<User> users = new  ObservableCollection<User>();\npublic MainWindow()\n{\n    InitializeComponent();\n\n                users.Add(new User() { Id = 101, Name = "gin", Salary = 10 });\n                users.Add(new User() { Id = 102, Name = "alen", Salary = 20 });\n                users.Add(new User() { Id = 103, Name = "scott", Salary = 30 });\n\n                dgsample.ItemsSource = users;\n}\n\nprivate void Get_Click(object sender, RoutedEventArgs e)\n{\n     if (this.tb1.Text != string.Empty) { User currentUser = users.Single(select => select.Id == Int32.Parse(this.tb1.Text)); this.tb2.Text = currentUser.Name; this.tb3.Text = currentUser.Salary; } \n}\n\nprivate void Add_Click(object sender, RoutedEventArgs e)\n{\n      users.Add(new User() { Id = 105, Name = "gin5", Salary = 100 });\n}\n\nprivate void Delete_Click(object sender, RoutedEventArgs e)\n{\n   users.RemoveAt(0);\n}	0
16894592	16894489	Filter data from DataTable	DataTable dtt = (DataTable)Session["ByBrand"];\n DataRow[] rows = dtt.Select("Price >= " + HiddenField1.Value + " and Price <= " + HiddenField2.Value + "");\nif(rows.Length > 0)\n{\n    var filldt = rows.CopyToDataTable();\n}	0
914807	914802	TimeSpan using a nullable date	weeksOnPlanSpan = DateTime.Now.Subtract(planStartDate.Value);	0
26793581	26792853	How to call a method with dynamic parameters (can pass or without) C#	public void Main(string[] args)\n{\n    MyMethod(param2: value);\n    MyMethod(param1: value);\n    MyMethod(param3: value);\n}\n\npublic void MyMethod(string param1=null, int? param2=null, Datetime? param3=null)\n{\n     //do something\n}	0
7628486	7628247	Switching between multiple Cameras using Emgu CV	private Capture _capture;\n\n    private void InitCapture(Int32 _camIndex) {         \n        try {\n            if (_capture != null) {\n                Application.Idle -= ProcessFrame;               \n            }\n\n            _capture = new Capture(_camIndex);\n            Application.Idle += ProcessFrame;\n        }\n        catch (NullReferenceException excpt) {\n            XtraMessageBox.Show(excpt.Message);\n        }\n    }\n\n    private void ProcessFrame(object sender, EventArgs arg) {\n        Image<Bgr, Byte> frame = _capture.QueryFrame();\n        ImageBoxCapture.Image = frame;\n    }\n\n    private void CharmsBarBase_ButtonTop01Click(object sender, EventArgs e) {\n        InitCapture(0);\n    }\n\n    private void CharmsBarBase_ButtonTop02Click(object sender, EventArgs e) {\n        InitCapture(1);\n    }	0
15031065	15028607	Binding fails when moved in to constructor from app.config	DomainManagementClient client = new DomainManagementClient(new NetTcpBinding(SecurityMode.None), new EndpointAddress("net.tcp://example.com/MyApp/DatabaseManagement"));	0
12485335	12484933	Serializing object using json.net using lambda selector	JsonConvert.SerializeObject(collection.Select(o => o.Index)).	0
18173899	18173844	How to automatically create a WPF data input form based on data source?	Server Explorer	0
24528235	24527072	Get images in WPF	for (var i = 0; i < VisualTreeHelper.GetChildrenCount(PlayerImagesGrid); i++)\n    {\n        var child = VisualTreeHelper.GetChild(PlayerImagesGrid, i);\n        var image = child as Image;\n\n        if (image != null)\n        {\n            one.Images.Add(image);\n        }\n    }	0
3141386	3141354	Help with getting two different data types from IEnumerable	ListViewItems.DataSource = f.Items.Select(\n    t => new { Value1 = t.value1, Value2 = t.value2[0] }\n);	0
2841277	2841258	Minimize a window in WPF?	WindowState = WindowState.Minimized;	0
6346711	6346531	I need to get rid of focus	private void TextBox_KeyUp(object sender, KeyEventArgs e)\n    {\n        if (e.Key == Key.A)\n            FocusManager.SetFocusedElement(this, this);\n    }	0
7801918	7801827	Failed to generate a user instance of SQL Server	exec sp_configure 'user instances enabled', 1.\nGo\nReconfigure	0
16663687	16663015	Automatic scrolling of textbox choppy	richTextBox1.AppendText(cmdOutputMsg + "\r\n");\nrichTextBox1.ScrollToCaret();	0
23880142	23874990	How to destroy google drive token after task done?	await credential.RevokeTokenAsync(CancellationToken.None);	0
5406305	5406216	How can I getpixel and setpixel from an Image as HSB instead of RGB?	Color c = Color.FromArgb(1, 2, 3);\nfloat h, s, b;\nh = c.GetHue();\ns = c.GetSaturation();\nb = c.GetBrightness();	0
284579	248923	Windows Workflow - Web Service - App_Data Directory - Database	string s = AppDomain.CurrentDomain.GetData("DataDirectory") as string;	0
19021825	19021721	Singleton Pattern In C#	public class MyClass   {\n\n    MyClass me  = null;\n\n    //private CTOR \n    private MyClass  () {\n    }\n\n    public static MyClass  ConstructMe(..parameters..) {\n\n         if(me != null) \n            return me;\n\n         me = new MyClass();\n         ....setup parameters .... \n         return me,\n    }\n\n}	0
6130543	6130297	C#: How to avoid TreeNode check from happening on a double click event	public class NoClickTree : TreeView\n    {\n        protected override void WndProc(ref Message m)\n        {\n            // Suppress WM_LBUTTONDBLCLK\n            if (m.Msg == 0x203) { m.Result = IntPtr.Zero; }\n            else base.WndProc(ref m);\n        }              \n    };	0
34438412	34422364	C# Selenium: Click button under iframe	driver.SwitchTo().Frame(driver.FindElement("iframe_1"))); \ndriver.FindElement(By.Id("sendRequest")).Click();	0
22056508	22056063	WMI escape characters on string variable programatically	ManagementObject pnpdevice = new ManagementObjectSearcher(String.Format(\n    "select * from Win32_PnPEntity where DeviceID='{0}'",\n    @device["DeviceID"].ToString().Replace("\\", "\\\\") )).First();	0
12772681	12772374	How to link to a specific system-setting in your Windows Phone app?	ConnectionSettingsTask connectionSettingsTask = new ConnectionSettingsTask();\nconnectionSettingsTask.ConnectionSettingsType = ConnectionSettingsType.WiFi;\nconnectionSettingsTask.Show();	0
4308740	4308591	help with a two table linq query	using (var dbm = new MyDataContext())\n{\n    var query = dbm.Categories\n                join s in dbm.SubCategories on c.CategoryID equals s.CategoryID\n                //group the related subcategories into a collection\n                into subCollection\n                select new { Category = c, SubCategories = subCollection };\n\n    foreach (var result in query)\n    {\n        //use result.Category here...\n\n        //now go through the subcategories for this category\n        foreach (var sub in result.Subcategories)\n        {\n            //use sub here...\n        }   \n    }\n}	0
18822206	18822123	Bind DataTable to Datagridview that already have column defined into data grid	SqlConnection CN = new SqlConnection(mysql.CON.ConnectionString);\ndataGridView1.AutoGenerateColumns = false;\nDataTable dt = new DataTable();\nSqlDataAdapter sda = new SqlDataAdapter("select id,name,age,notes  from test where id = '" + txtID.Text + "'", CN);\nsda.Fill(dt);\ndataGridView1.DataSource = dt;	0
21491832	21491346	How to correctly initialize the Windows desktop (explorer.exe) of Windows 8	myProcess = New Process()\n myProcess.StartInfo.FileName = "C:\Windows\explorer.exe"\n myProcess.StartInfo.UseShellExecute = True\n myProcess.StartInfo.WorkingDirectory = Application.StartupPath\n myProcess.StartInfo.CreateNoWindow = True\n\n myProcess.Start()	0
10356358	10356204	Build DateTime from string value based on the current system culture	DateTime.TryParse(string, out DateTime result)	0
23956449	23956403	MemoryStream to sbyte[]	Array.ConvertAll(bytes, b => (sbyte)b)	0
28395407	28381995	How to create dynamic parameters in SQL Server stored procedure	create type dbo.ValueTableType as table (Value varchar(255))\nGO\n\ncreate procedure dbo.InsertValues\n    @Values dbo.ValueTableType readonly\nas\nbegin\n\n    insert into dbo.YourTable (Value)\n    select Value from @Values;\nend	0
3636720	3636642	Need to upload file, and use it in the pre-init event	protected void Page_PreInit(object sender, EventArgs e)\n{\n    HttpPostedFile file = Request.Files["IDOfFileUploadControl"];\n}	0
21334959	17670749	gmap c# point lat long to screen position/location	private void myMap_Click(object sender, MouseEventArgs e)\n{\n    using (Form customForm = new Form())\n    {\n        customForm.StartPosition = FormStartPosition.Manual;\n        customForm.DesktopLocation = MainMap.PointToScreen(e.Location);\n        customForm.ShowDialog();\n    }\n}	0
17874486	17866283	Creating custom attributes for methods that has specific signature	[AttributeUsage(AttributeTargets.All)]\npublic class HelpAttribute : System.Attribute\n{\n    // Required parameter\n    public HelpAttribute(string url) \n    {\n        this.Url = url;\n    }\n\n    // Optional parameter\n    public string Topic { get; set; }\n\n    public readonly string Url;\n\n\n}\n\npublic class Whatever\n{\n    [Help("http://www.stackoverflow.com")]\n    public int ID { get; set; }\n\n    [Help("http://www.stackoverflow.com", Topic="MyTopic")]\n    public int Wew { get; set; }\n\n    // [Help] // without parameters does not compile\n    public int Wow { get; set; }\n}	0
20183910	20183765	C# interop with CUDA C dll - redux	Bitmap img = new Bitmap(1920, 1080, 1920 * 3, PixelFormat.Format24bppRgb, unmanagedPtr);	0
21514873	21514706	How to dynamically get the position in a two dimensional array	int max_n = 2;\nint max_m = 10;\nint current_position_x = 0;\nint current_position_y = 8;\ncurrent_position_y += 3;   // here you add a shift to your current position\nif (current_position_y >= max_m)\n{\n     current_position_x += current_position_y / max_m;\n     current_position_y %= max_m;\n}	0
29729132	29729092	Converting Stream to byte[] array always returns 0 length in windows phone 8 C#	using (BinaryReader br = new BinaryReader(mystream))\n{\n    mystream.Position = 0;\n    imageData = br.ReadBytes(Convert.ToInt32(mystream.Length));\n}	0
15799817	15785704	How to import a Public Key into RSA For decryption	var encryptionKey = new BigInteger(_session.EncryptionKey);\nvar result = encryptionKey.modPow(12345, BigInteger.Parse("HEX of public key", System.Globalization.NumberStyles.HexNumber).ToByteArray());\n_session.EncryptionKey = result.ToByteArray();	0
6073545	6073382	Read SQL Table into C# DataTable	using System;\nusing System.Data;\nusing System.Data.SqlClient;\n\n\npublic class PullDataTest\n{\n    // your data table\n    private DataTable dataTable;\n\n    public PullDataTest()\n    {\n    }\n\n    // your method to pull data from database to datatable   \n    public void PullData()\n    {\n        string connString = @"your connection string here";\n        string query = "select * from table";\n\n        SqlConnection conn = new SqlConnection(connString);        \n        SqlCommand cmd = new SqlCommand(query, conn);\n        conn.Open();\n\n        // create data adapter\n        SqlDataAdapter da = new SqlDataAdapter(cmd);\n        // this will query your database and return the result to your datatable\n        da.Fill(dataTable);\n        conn.Close();\n        da.Dispose();\n    }\n}	0
6202339	6200284	Bind a DependencyProperty in DataGrid.ElementStyle for each Column	{Binding RelativeSource={RelativeSource AncestorType=Page}, Path=DataContext.SelectDataList_Column0IsWrapping}	0
24255055	24157629	RestSharp: Deserialize Xml to c# Object return null	public auditypes Execute<auditypes>(RestRequest request) where auditypes : new()\n{\n    var client = new RestClient();\n    client.BaseUrl = "https://www.myurl.com/auditypes";\n    var response = client.Execute<auditypes>(request).Data;\n\n    return response;\n}\n\npublic auditypes GetCall()\n{\n    var request = new RestRequest();\n    request.RequestFormat = DataFormat.Xml;\n    return Execute<auditypes>(request);\n}	0
32914251	32914027	Trouble printing out results of averaging an array	string [] months;\ndouble[] rain;\n\nmonths = new string [12] {  "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"};\nrain = new double[12];\n\nfor (int i = 0; i < rain.Length; i++) {\n    Console.Write("Rainfall in {0}: ", months[i]);\n    rain[i] = double.Parse(Console.ReadLine());\n\n    while (rain[i] < 0) {\n        Console.Write("Rainfall in {0}: ", months[i]);\n        rain[i] = double.Parse(Console.ReadLine());\n    }\n}\ndouble avg;\ndouble sum = 0;\nfor (int i = 0; i < rain.Length; i++) {\n    sum = sum + rain[i];\n}\navg = sum / 12;\nConsole.WriteLine("");\nConsole.WriteLine("Average Month Rain: " + avg);	0
18570217	18570073	how to close xmldocument in c#	var doc = new XmlDocument();\n\n        var filePath = "myXmlFile.xml";\n\n        doc.Load(filePath);\n\n        using (var writer = new StreamWriter(filePath))\n        {\n            doc.Save(writer);\n        }	0
3279595	3252514	C#.Net Windows application - Getting Logged user name in My NT	try {\n    object[] objArr = new object[2];\n    ManagementScope ms = new ManagementScope("Path");\n    ms.Connect();\n    if (ms.IsConnected)\n    {\n        ObjectQuery Query = new ObjectQuery("SELECT * FROM Win32_Process WHERE Name='explorer.exe'");\n        ManagementObjectSearcher searcher = new ManagementObjectSearcher(ms, Query);\n        foreach(ManagementObject objQuery in searcher.Get())\n        {\n            objQuery.InvokeMethod("GetOwner", objArr); // objArr[0] contains the userId and objArr[1] contains Domainname\n            userName = Convert.ToString(objArr[0]);\n        }\n    }\n}\ncatch (System.Exception ex)\n{\n    throw ex;\n}	0
11359167	11359018	I can't build AwesomiumSharp version from github	D:\Awesomium\1.6.6\wrappers\Awesomium.NET\AwesomiumSharp	0
3956830	3956679	IEnumerable and Datareader extension method, suggestions needed	List<T>	0
5995090	5994755	c# using library	// ----------------------------------------------------------------------\n  private static string ConvertRtfToHtml()\n  {\n    const string sampleRtfText = @"{\rtf1foobar}";\n\n    IRtfDocument rtfDocument = RtfInterpreterTool.BuildDoc( sampleRtfText );\n\n    RtfHtmlConvertSettings settings = new RtfHtmlConvertSettings();\n    settings.ConvertScope = RtfHtmlConvertScope.Content;\n\n    RtfHtmlConverter htmlConverter = new RtfHtmlConverter( rtfDocument, settings );\n    return htmlConverter.Convert();\n  } // ConvertRtfToHtml	0
24433604	24432640	How to read SecurityToken and Signature value from Soap Request	string filename = "SOAP.xml";\n    XmlDocument document = new XmlDocument();\n    document.Load(filename);\n    XPathNavigator navigator = document.CreateNavigator();\n    // use XmlNamespaceManager to resolve ns prefixes\n    XmlNamespaceManager manager = new XmlNamespaceManager(navigator.NameTable);\n    manager.AddNamespace("h", "http://tempuri.org/");\n    // use XPath expression to select XML nodes\n    XPathNodeIterator nodes = navigator.Select("//h:SecurityToken",manager);\n    if ( nodes.MoveNext() )\n        Console.WriteLine(nodes.Current.ToString());\n    else\n        Console.WriteLine("Empty Element");\n    // and now for the Signature Element, without ns prefix\n    nodes = navigator.Select("//Signature", manager);\n    if (nodes.MoveNext())\n        Console.WriteLine(nodes.Current.ToString());\n    else\n        Console.WriteLine("Empty Element");	0
18895816	18895751	Subtract a generic list from another	var result = firms.Except(trackedFirms); // returns all the firms except those in trackedFirms	0
6788244	6788120	InvalidOperationException when using Keyboard.Modifiers in a Task	Task.Factory.StartNew(\n                        () =>\n                        {\n                            if ((bool)Dispatcher.Invoke(DispatcherPriority.Normal, new Func<bool>(() =>\n                            {\n                                 return Keyboard.Modifiers == ModifierKeys.Alt;\n                             })))\n                             {\n                                Thread.Sleep(1000);                            \n                             }\n                        })\n                        .ContinueWith(t =>\n                        {\n                          // do somthing\n                        });	0
28426464	28415161	How to load a CascadeClassifier using Emgu c#	private static readonly CascadeClassifier Classifier = new CascadeClassifier("haarcascade_frontalface_alt_tree.xml");	0
9567324	9562775	How to retrieve the latitude and longitude of the inputed address using google geo coder?	function DoMapSearch(placeName) {\n    var geocoder = new GClientGeocoder();\n    geocoder.getLatLng(placeName, function (point) {\n      if (point != null) {\n        GoogleMapCnt.loadAddress(addr);\n      }\n    });\n\n    return false;\n  }	0
2648432	2648407	Parse numbers in singe textbox for query	string[] lines = textBox.Text.Split( '\n' );\nforeach( var line in lines )\n{\n    var values = line.Split( ' ' );\n    var num1 = int.Parse( values[0] );\n    var num2 = int.Parse( values[1] );\n    // do what you need to with num1, num2\n}	0
19022001	19012734	Query the Active Directory for all users with a custom attribute	Parallel.ForEach	0
5161202	5161157	get computer from OU	string selectDomain = "CN=myCompany,CN=com";\nstring selectOU = "OU=LosAngeles,OU=America";\nDirectoryEntry entry = new DirectoryEntry("LDAP://" + selectOU + "," + selectDomain);	0
33957034	33956752	Try-Catch Loop until success	Clipboard.ContainsText	0
20096028	20095474	How to substring concerning many delimiters in between	String JSLines = "DefineEvent(20140208,'Starting of Study for (old and new) student's ','','',17,5)";\n\nstring result = JSLines;\nint methodBodyStart = JSLines.IndexOf("DefineEvent(");\nif (methodBodyStart >= 0)\n{\n    methodBodyStart += "DefineEvent(".Length;\n    int methodBodyEnd = JSLines.LastIndexOf(')');\n    if (methodBodyEnd >= 0)\n    {\n        string methodBody = JSLines.Substring(methodBodyStart, methodBodyEnd - methodBodyStart);\n        var twoParams = methodBody.Split(',')\n           .Select(str => str.Trim(' ', '\'')).Take(2);\n        result = string.Join("|", twoParams);\n    }\n}	0
5569606	5569576	Is it possible to use reflection to turn a string into a function in c#?	void Main()\n{\n    var simpleDelegate = "test".CreateDelegate<Func<string>>(new Test());\n    simpleDelegate().Dump();\n}\n\nclass Test\n{\n    public string test() { return "hi"; }\n}\n\npublic static class ExtensionMethods\n{\n    public static T CreateDelegate<T>(this string methodName,object instance) where T : class\n    {\n        return Delegate.CreateDelegate(typeof(T), instance, methodName) as T;\n    } \n}	0
13095314	13094684	MouseLeave doesn't fire when moving from child control to parent's parent	public class MyPanel : Panel\n    {\n        protected override void OnControlAdded(ControlEventArgs e)\n        {\n            e.Control.MouseLeave += DidMouseReallyLeave; \n            base.OnControlAdded(e);\n        }\n        protected override void OnMouseLeave(EventArgs e)\n        {\n            DidMouseReallyLeave(this, e);\n        }\n        private void DidMouseReallyLeave(object sender, EventArgs e)\n        {\n            if (this.ClientRectangle.Contains(this.PointToClient(Control.MousePosition)))\n                return;\n            base.OnMouseLeave(e);\n        }\n    }	0
3574780	3573138	how to create GUID Autonumber programaticaly in ms access	CurrentProject.Connection.Execute "CREATE TABLE hede (Id Guid DEFAULT GenGUID())"	0
7722811	7711477	How to use SetBytesProperty and GetBytesProperty in WebSphere MQ?	MQMessage message = new MQMessage();\n                message.SetBytesProperty("testBytesValue", new sbyte[] { 8, 12, 22, 48, 68, 71, 92, 104 });\n                message.WriteUTF(MessageContent);\n                queue.Put(message);\n\n                MQMessage readMessage = new MQMessage();\n                queue.Get(readMessage);\n\n                sbyte[] array = readMessage.GetBytesProperty("testBytesValue");\n                Console.Write(array);	0
6378314	6347386	Generic Enum string value parser in c#?	public static T GetConfigEnumValue<T>(NameValueCollection config, string configKey, T defaultValue)\n{\n    if (config == null)\n    {\n        return defaultValue;\n    }\n\n    if (config[configKey] == null)\n    {\n        return defaultValue;\n    }\n\n    T result = defaultValue;\n    string configValue = config[configKey].Trim();\n\n    if (string.IsNullOrEmpty(configValue))\n    {\n        return defaultValue;\n    }\n\n    try\n    {\n        result = (T)Enum.Parse(typeof(T), configValue, true);\n    }\n    catch\n    {\n        result = defaultValue;\n    }\n\n    return result;\n}	0
29376067	29375699	Ajax + webservice + array of object	var serializer = new JavaScriptSerializer();\nvar result = serializer.Deserialize(mail, typeof(List<object>));	0
10777577	10777481	Updating db entry with childrens	try {\n   context.SaveChanges();\n} \ncatch (OptimisticConcurrencyException) \n{\n    context.Refresh(RefreshMode.ClientWins, db.table);\n    context.SaveChanges();\n}	0
915138	915073	Use "convert to auto property" on multiple properties at once	Options -> Code Cleanup -> Use auto-property, if possible	0
2546064	2546049	Running an exe in C# with commandline parameters, suppressing the dos window	using( var process = new Process() )\n{\n    process.StartInfo.FileName = "...";\n    process.StartInfo.WorkingDirectory = "...";\n    process.StartInfo.CreateNoWindow = true;\n    process.StartInfo.UseShellExecute = false;\n    process.Start();\n}	0
13034323	13034214	Find entities from list of entities	var dates = from e in EntityList\n            orderby e.Id\n            group e by new { e.From, e.To } into g\n            select g.First();	0
3791524	3791139	Detect an open project in visual studio	private DTE2 dte2;\n\npublic void OnConnection(object application, ext_ConnectMode connectMode, object addInInst, ref Array custom)\n{\n    dte2 = (DTE2)application;\n    var events = (Events2)dte2.Events;\n    solutionEvents = events.SolutionEvents;\n\n    solutionEvents.Opened += OnSolutionOpened;\n}\n\nprivate void OnSolutionOpened()\n{\n    Projects projects = dte2.Solution.Projects;\n\n    foreach (Project project in projects)\n    {\n        ProcessProject(project);\n    }\n}\n\nprivate void ProcessProject(Project project)\n{\n    string directoryName = Path.GetDirectoryName(project.FileName);\n    string fileName = Path.GetFileName(project.FileName);\n\n    if (directoryName == null || fileName == null)\n    {\n        return;\n    }\n\n    var directory = new DirectoryInfo(directoryName);\n    var fileInfo = new FileInfo(fileName);\n\n    //do work\n}	0
700933	695591	Is there any tool to convert from XAML to C# (code behind)?	Storyboard storyboard3 = new Storyboard();\n\nstoryboard3.AutoReverse = false;\nRotation3DAnimationUsingKeyFrames r3d = new Rotation3DAnimationUsingKeyFrames();\nr3d.BeginTime = new TimeSpan(0, 0, 0, 0, 0);\nr3d.Duration = new TimeSpan(0,0,0,1,0);\n\nr3d.KeyFrames.Add(new SplineRotation3DKeyFrame(new AxisAngleRotation3D(new Vector3D(1,0,0),1)));\nr3d.KeyFrames.Add(new SplineRotation3DKeyFrame(new AxisAngleRotation3D(new Vector3D(1, 0, 0), 37)));\nr3d.Name = "r3d";\n\nStoryboard.SetTargetName(r3d, "DefaultGroup");\nStoryboard.SetTargetProperty(r3d, new PropertyPath("(Visual3D.Transform).(Transform3DGroup.Children)[2].(RotateTransform3D.Rotation)")); \n\nstoryboard3.Children.Add(r3d);\nthis.BeginStoryboard(storyboard3);	0
9948454	9948418	ASPX Accessing master page function	public partial class Main : System.Web.UI.MasterPage\n{\n    protected void Page_Load(object sender, EventArgs e)\n    {\n    ...\n\n    }\n\n    public bool test()\n    {\n        return true;\n    }\n}	0
26103155	26065427	Automapper: How do I map Lazy<TFrom> to TTo?	// Get the Values of the Lazy<Employee> items and use the result for mapping\nvar nonLazyEmployees = employees.Select(i => i.Value).ToList();\nvar dataDTO = MyMapper<Employee, EmployeeDTO>.MapList(nonLazyEmployees);\n\npublic static IList<TTo> MapList(IList<Lazy<TFrom>> fromModel)\n{\n     Mapper.CreateMap<Lazy<TFrom>, TTo>();\n     return Mapper.Map<IList<Lazy<TFrom>>, IList<TTo>>(fromModel);\n}\n\n// Maps the child classes\nMapper.CreateMap<Employee, EmployeeDTO>()\n     .ForMember(x => x.AccidentDTO, i => i.MapFrom(model => model.GetAccident()))\n     .ForMember(x => x.CriticalIllnessDTO, i => i.MapFrom(model => model.GetCriticalIllness()))\n     .ForMember(x => x.ValidationMessages, i => i.MapFrom(model => model.ValidationMessages));	0
12218549	12218056	Get parameter values from method at run time	class Program\n    {\n        static void Main(string[] args)\n        {\n            Program p = new Program();\n            p.testMethod("abcd", 1);\n            Console.ReadLine();\n        }\n\n        public void testMethod(string a, int b)\n        {\n            System.Diagnostics.StackTrace st = new System.Diagnostics.StackTrace();\n            StackFrame sf = st.GetFrame(0);\n            ParameterInfo[] pis = sf.GetMethod().GetParameters();\n\n            foreach (ParameterInfo pi in pis)\n            {\n                Console.Out.WriteLine(pi.Name);\n            }\n        }\n    }	0
28541212	28541079	Pass List of strings to a stored procedure	USE [App]\nGO\n/****** Object:  StoredProcedure [dbo].[GetWorkspaceMapDetailsForUserByGroups]    \n     Script Date: 16/02/2015 10:37:46 ******/\nSET ANSI_NULLS ON\nGO\nSET QUOTED_IDENTIFIER ON\nGO\nALTER PROCEDURE [dbo].[GetWorkspaceMapDetailsForUserByGroups]   \n    @workspaceID int,\n    @viewMap nvarchar(256)\n AS \n\nSELECT \n  m.*\nFROM \n  GeoAppMapDef m\nWHERE\n m.workspaceID = @workspaceID\n and m.IsDeleted = 0\n and m.ViewMap IN \n (\n  SELECT \n     Split.a.value('.', 'VARCHAR(100)') AS CVS  \n  FROM  \n  (\n    SELECT CAST ('<M>' + REPLACE(@viewMap, ',', '</M><M>') + '</M>' AS XML) AS CVS \n  ) AS A CROSS APPLY CVS.nodes ('/M') AS Split(a)\n)	0
28208524	28208349	How to read response code from TcpClient	byte[] buffer = new byte[1024];\nint bytesRead = stream.Read(buffer, 0, buffer.Length);\nresponse = Encoding.ASCII.GetString(buffer, 0, bytesRead);\nConsole.WriteLine(response);	0
31096775	31096684	Waiting on a Task from multiple threads	public static void Main(string[] args)\n{\n    Task t = Task.Delay(10000);\n    new Thread(() => { ThreadRun(t); }).Start();\n    new Thread(() => { ThreadRun(t); }).Start();\n    Console.WriteLine("Main thread exits"); // this prints immediately.\n}\n\nprivate static void ThreadRun(Task t)\n{\n    t.Wait();\n    Console.WriteLine(Thread.CurrentThread.ManagedThreadId + " finished waiting"); // this prints about 10 seconds later.\n}	0
31469683	31465091	Ninject: GetAll instances that inherit from the same abstract class	_kernel.Bind<MyAbstractClass, MyDerivedClass1>()\n       .To<MyDerivedClass1>().InSingletonScope();\n_kernel.Bind<MyAbstractClass, MyDerivedClass2>()\n       .To<MyDerivedClass1>().InSingletonScope();	0
29136731	29136685	WPF ObjectCollection to a List	_MyDataList = new ObservableCollection<BillMetaData>(entity.ToList());	0
5321209	5321174	Get Item From List<T> and update a property on that Item	List<Person> persons;\nvar person = persons.Find(p => p.DisplayName == "Fred");\nperson.DisplayValue = "Flinstone";	0
22433619	22433196	ASP.NET MVC [Authorize] from controller in area can't find Account/Login ActionResult in root folder	public override void RegisterArea(AreaRegistrationContext context)\n{\n    context.MapRoute(\n        "Admin_default",\n        "Admin/{controller}/{action}/{id}",\n        new { area="Admin", action = "Index", id = UrlParameter.Optional }\n    );\n}\n\n\npublic static void RegisterRoutes(RouteCollection routes)\n{\n    routes.IgnoreRoute("{resource}.axd/{*pathInfo}");\n\n    routes.MapRoute(\n        name: "Default",\n        url: "{controller}/{action}/{id}",\n        defaults: new {controller = "Startup", action = "Index", id = UrlParameter.Optional }\n    );\n}	0
371993	371987	Validate a DateTime in C#	DateTime temp;\nif(DateTime.TryParse(startDateTextBox.Text, out temp))\n//yay\nelse\n// :(	0
15093692	15093624	Trim string with trim.End	XDocument doc = XDocument.Parse(xml);\nstring inquiryId = (string)doc.Root.Element("inquiry_id");	0
31827261	31826308	Entity framework group locations by proximity	var threshold = 1609344.0;\n\nvar groups = from p1 in dbContext.Points\n    let isCloseToOtherPoint = dbContext.Points.Any(p2 => p1.Geography.Distance(p2.Geography) < threshold)\n    group p1 by isCloseToOtherPoint into g\n    select g	0
9130759	9130665	Assigning ID to Objects transmitted in XML document	var result = new XDocument(\n                 new XElement("People",\n                     people.Select((p, i) =>\n                         new XElement("Person",\n                             new XAttribute("ID", i + 1),\n                             new XElement("Name", p.Name),\n                             new XElement("Age", p.Age),\n                             new XElement("Company", p.Company)\n                         )\n                     )\n                 )\n             );	0
18790942	18790085	Find Min value in row from Dynamic Datatable	if (userpoints.Rows.Count > 1)\n{\nforeach (DataRow dr in selectedPanels.Rows)\n{\nList<string> alluserpoints = new List<string>();             \nfor (int i = 0; i < userpoints.Rows.Count; i++)\n{\nif (Convert.ToDouble(userpoints.Rows[i].radius) > Convert.ToDouble(dr["DistanceFromUserpoint" + i]))\n{\n    alluserpoints.Add(dr["DistanceFromUserpoint" + i]+"+userpoint"+i);\n}\n}\nif(alluserpoints.Count>0)\ndr["Closest_UserPoint"] = alluserpoints.Min();  \nelse\ndr["Closest_UserPoint"] ="none";                        \n}\n}\nelse\n{\nforeach(DataRow dr in selectedPanels.Rows)\n{\nif(Convert.ToDouble(userpoints.Rows[0].radius>Convert.ToDouble(dr["DistanceFromUserpoint0"])\n{\ndr["Closest_UserPoint"]=dr["DistanceFromUserpoint0"]+"+userpoint0";\n}\nelse\n{\ndr["Closest_UserPoint"]="none";\n}\n}\n}	0
6751831	6751173	how to make multilingual site in asp.net	protected override void InitializeCulture() \n{ \n    Thread.CurrentThread.CurrentUICulture = new CultureInfo("en-US"); //'en-US' these values are may be in your session and you  can use those\n    Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US");//'en-US' these values are may be in your session and you  can use those\n    base.InitializeCulture(); \n}	0
3576434	3576266	Parsing text file for hexadecimal content	string value = "A34d (Text, Optional)";\n\n        string hex = value.Substring(0, 4);\n        string text = value.Split('(')[1];\n\n        if (text.Contains(','))\n            text = text.Substring(0, text.IndexOf(','));\n        else\n            text = text.Substring(0, text.Length-1);	0
2720043	2720009	How to use custom IComparer for SortedDictionary?	int comp = xLastname.CompareTo(yLastname);\nif (comp == 0)\n   return x.CompareTo(y);\nreturn comp;	0
28742236	28736692	How to store a zip file in sql server table	byte[] bytes = System.IO.File.ReadAllBytes(filename);	0
6725914	6725848	c# pass a string from an action to another	return RedirectToAction("Error", new { ErrorId = 4 });\n\npublic ActionResult Error(int errorId){ ... }	0
18296981	18288744	HttpWebRequest and HttpWebResponse shows old data	response.setHeader("Cache-Control", "no-cache");	0
16529406	16528666	How to print rectangle with exact size in c#?	private void button1_Click(object sender, EventArgs e)\n    {\n        using (Graphics formGraphics = this.CreateGraphics())\n        {\n            formGraphics.PageUnit = GraphicsUnit.Millimeter;\n            formGraphics.DrawRectangle(Pens.Blue, 0, 0, 20, 80);\n        }\n    }	0
15850156	15850001	Cannot download a particular file from the website	WebClient webClient = new WebClient();\nwebClient.Headers.Add("user-agent", "CustomClient");\nwebClient.DownloadFile("http://www.mbank.pl/bin/sfi/sfi_do_csv.php?sh=0,3,4,5,6,7,8,9,10,11&date=2013-04-05&sorted=StopaZw1r_down&fund_type=&collection=&show=all", @"d:\myfile.csv");	0
3183019	3182839	AvalonDock - Bind MenuItem to State of DockableContent	public static class ContentAttach\n{\n    public static readonly DependencyProperty StateProperty = DependencyProperty.RegisterAttached(\n        "State", typeof(DockableContentState), typeof(ContentAttach), new PropertyMetadata(StateChanged));\n    public static void SetState(DockableContent element, DockableContentState value)\n    {\n        element.SetValue(StateProperty, value);\n    }\n    public static DockableContentState GetState(DockableContent element)\n    {\n        return (DockableContentState)element.GetValue(StateProperty);\n    }\n    private static void StateChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)\n    {\n        var element = (DockableContent)d;\n        var state = (DockableContentState)e.NewValue;\n        switch (state)\n        {\n            // Call methods in here to change State.\n        }\n    }\n}	0
7094267	7094234	update a generic List Item using C#	LInfo.Percent = Convert.ToInt32((RealProduced / DesireProd) * 100);\nLines[aCurrentLine] = LInfo;	0
24219423	24219361	SubQuery using Lambda Expression	names.Where (x => x.Length == names.Min (n2 => n2.Length));	0
722794	722788	How do I access a C++ subscript operator from within the class in which it resides?	(*this)[0] = ...	0
29406085	29406010	DataGridViewComboboxColumn for Bound Grid	DataTable dtComboData = getQueryResult("SELECT DISTINCT Result FROM T_Result");\n        DataGridViewComboBoxColumn col = new DataGridViewComboBoxColumn();\n        col.DataSource = dtComboData;\n        col.DisplayMember = dt.Columns[0].ColumnName;\n\n\n        dgvResult.Columns.Add(col);	0
3786326	3785549	How can I put a return string value in the Text property of a text block?	System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString());	0
8633945	8633921	How do you pass null values for dbtype decimal?? 	param.Value = testresults.Result==0?DBNull.Value:(object)testresults.Result;	0
31647960	31647928	How to join two customer lists into one list	List<customer> customers = new List<customer>();\n List<customer_details> details = new List<customer_details>();\n\n var query = (from c in customers\n                join d in details on c.customer_id equals d.customer_id\n                select new\n                {\n                    c.customer_id,\n                    c.name,\n                    d.address,\n                }).ToList();	0
14734371	14717844	Create Access Table from SQLDataReader	static void CreateTableFromReader(string tableName, SqlDataReader reader) {\n  List<string> columns = new List<string>();\n  string createTable = @"CREATE TABLE {0} ({1})";\n\n  var dt = reader.GetSchemaTable();\n  foreach (DataRow dr in dt.Rows) {\n    switch (dr["DataTypeName"].ToString().ToLower()) {\n      case "varchar":\n        columns.Add(String.Format("[{0}] {1}({2})",\n          dr["ColumnName"],\n          dr["DataTypeName"],\n          dr["ColumnSize"]\n        ));\n        break;\n      case "money": //i know this is redundant but being explicit helps clarity sometimes\n      case "date":\n      case "integer":\n      default:\n        columns.Add(String.Format("[{0}] {1}",\n          dr["ColumnName"],\n          dr["DataTypeName"]\n        ));\n        break;\n    }\n  }\n  using (var cmd = conn_Access.CreateCommand()) {\n    cmd.CommandType = CommandType.Text;\n    cmd.CommandText = String.Format(createTable, tableName, String.Join(", ", columns));\n    cmd.ExecuteNonQuery();\n  }\n}	0
11949348	11949210	DropDown dependency based on 3 tables	String strQuery ="select pof.FirstName, pof.POCID from PointOfCContact pof Inner Join Client_POC_Bridge cpb On pof.POCID =cpb.POCID where cpb.ClientID=@ClientID";	0
9027334	9027301	Get one unique List<T> from three non-unique List<T>'s	var res = listOne.Concat(listTwo).Concat(listThree)\n    .GroupBy(u => u.Email)\n    .Select(g => g.First());	0
29939358	29939305	split list to multiple list on property basis	var lista = flights.Select(f => f.CompanyId).ToArray();\nvar listb = flights.Select(f => f.Number).ToArray();\nvar listc = flights.Select(f => f.Set).ToArray();	0
9650512	9639762	Select Row In RadGrid Button_Click	foreach (GridDataItem item in RadGridLeadHistory.MasterTableView.Items)\n{\n    Label lb = item["LabelHistoryNote"].Controls[1] as Label;\n    str = lbl.Text;\n}	0
5159009	5158936	C# MySql query result to combobox	...\nforeach (DataRow row in dt.Rows)\n{\n   string rowz = string.Format("{0}:{1}", row.Item[0], row.Item[1]);\n   yourCombobox.Items.Add(rowz);\n}\n....	0
10226004	10225863	Extracting Data From DataGridView and Populating in XML	BindingSource bs = (BindingSource)dgv.DataSource;\nDataSet ds = (DataSet)bs.DataSource;\nDataTable dt = ds.Tables["Customers"];  // or Tables[0]	0
1285036	1284674	How Do I Stop An Application From Opening	REGEDIT4\n\n[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Image File Execution Options\notepad.exe]\n"Debugger"="calc.exe"	0
10960856	10960681	Two windows opening when page loads	[STAThread]\n    static void Main()\n    {\n        Application.EnableVisualStyles();\n        Application.SetCompatibleTextRenderingDefault(false);\n        Form form;\n\n        StreamReader tr = new StreamReader(Application.StartupPath + "\\" + "config.txt");\n\n        string config = tr.ReadToEnd();\n        tr.Close();\n        if (string.IsNullOrWhiteSpace(config))\n        {\n            form = new Configuration_Form();\n        }\n        else\n        {\n            form = new Form1();\n        }\n\n        Application.Run(form);\n    }	0
17804018	17803883	How to check for internet connection?	var asd = NetworkInterface.GetInternetInterface();	0
27716074	27715240	Managing SignalR connections for Anonymous user	FormsAuthentication.SetAuthCookie	0
16499131	16499083	c# implement contextual help on dll to use on designtime	/// <summary>\n/// This text will show up in the contextual help box.\n/// </summary>\npublic void SomePublicMethod() {\n    ...\n}	0
4850081	2313487	Intrasession Communication with .NET Remoting	System.ServiceModel.Channels.SecurityDescriptorHelper.GetProcessLogonSid()	0
6868764	6868680	How to combine two image byte[] arrays together quickly utilizing a mask array in C#	static void MaskImage(byte[] background, byte[] foreground, byte[] mask)\n{\n    for (var i = 0; i < background.Length; ++i)\n    {\n        background[i] &= mask[i];\n        background[i] |= foreground[i];\n    }\n}	0
9796690	9784142	How do you encapsulate a MonoTouch.Dialog view into a view controller?	class NewItemViewController : DialogViewController\n{\n    private Item _item;\n    public NewItemViewController(bool pushing) : base(null, pushing)\n    {\n        _item = new Item();\n        BindingContext bc = new BindingContext(this, _item, "Add Item");\n        this.Root = bc.Root;\n        // more setup\n    }\n    // more methods\n}	0
33322395	33322132	Recursively find object property via reflection?	static class Program\n{\n    static readonly BindingFlags flags = BindingFlags.Static | BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic;\n\n    static void Main() {\n        var a = new A { PropA = new B() { PropB = "Value" } };\n        var prop = GetPropertyRecursive("PropA.PropB", a);\n    }\n\n    static object GetPropertyRecursive(string property, object obj) {\n        var splitted = property.Split('.');\n        var value = obj.GetType().GetProperty(splitted[0], flags).GetValue(obj);\n\n        if (value == null) {\n            return null;\n        }\n\n        if (splitted.Length == 1) {\n            return value;\n        }\n\n        return GetPropertyRecursive(string.Join(".", splitted.Skip(1)), value);\n    }\n}	0
12762843	12762786	How to display an image or file in c# without copying it to application(resources)?	pictureBox1.ImageLocation = Path.Combine(\n  Path.GetDirectoryName(Application.ExecutablePath),\n  "file.jpg");	0
7354278	7353993	FTP Changing PGP File During Transfer in C#	using (var reader = File.Open(source, FileMode.Open))\n        {\n            var ftpStream = request.GetRequestStream();\n            reader.CopyTo(ftpStream);\n            ftpStream.Close();\n        }	0
7161742	7161674	How to get the value of a System.String object instead of returning "System.String[]"	case EsfValueType.Binary4E: //System.String[]\n{\n    int size = (int)(this.reader.ReadUInt32() - ((uint)this.reader.BaseStream.Position));\n    var strings = new StringBuilder();\n    for (int i = 0; i < size / 4; i++)\n    {\n        strings.Append(this.stringValuesUTF16[this.reader.ReadUInt32()]); //or AppendLine, depending on what you need\n    }\n    esfValue.Value = strings.ToString();\n    break;\n}	0
20412910	20412420	How to bind a Dictionary to DataSource of DataGridView	List<KeyValuePair<string, string>> d = new List<KeyValuePair<string, string>>();\nd.Add(new KeyValuePair<string, string>("1", "2323"));\nd.Add(new KeyValuePair<string, string>("2", "1112323"));\n\nDataGridView v = new DataGridView();\nv.DataSource = d;	0
2729230	2675978	c# -> javascript, Json decoding misses property	public class RankingListForDisplay \n{\n    public List<RankingListLine> Lines { get; set; }\n    public string Period { get; set; }\n\n    public RankingListForDisplay()\n    {\n        Lines = new List<RankingListLine>();\n        Period = "<Unspecified>";\n    }\n}	0
32840022	32839685	multiple same cast on object	v = (V)(T)e.Current;	0
2545220	2545025	how to deep copy a class without marking it as serializable	class A\n{\n  // copy constructor\n  public A(A copy) {}\n}\n\n// a referenced class implementing \nclass B : IDeepCopy\n{\n  object Copy() { return new B(); }\n}\n\nclass C : IDeepCopy\n{\n  A A;\n  B B;\n  object Copy()\n  {\n    C copy = new C();\n\n    // copy property by property in a appropriate way\n    copy.A = new A(this.A);\n    copy.B = this.B.Copy();\n  }\n}	0
7726043	7725974	Adding items to the beginning of a list array	myList.Insert(0, new MyClass());	0
2531836	2531830	how do you implement Async Operations in C# and MVVM?	_dispatcher.BeginInvoke( () => _results.AddRange( entries) )	0
9746244	9746130	Byte to bits in a BMP getting RGB	int x = 33808;  // 1000010000010000, for testing\n\nint r = (x & 63488) >> 11;    // 63488 = 1111100000000000\nint g = (x & 2016) >> 5;      //  2016 = 0000011111100000\nint b = (x & 31);             //    31 = 0000000000011111\n\n// r = 10000\n// g = 100000\n// b = 10000	0
16943053	16941914	Identify items in one list not in another of a different type	// Create a query\nICriteria query = Session.CreateCriteria<WorkShopItem>("wsi");\n\n// Restrict to items due within the next 14 days\nquery.Add(Restrictions.Le("DateDue", DateTime.Now.AddDays(14));\n\n// Return all TaskNames from Todo's\nDetachedCriteria allTodos = DetachedCriteria.For(typeof(Todo)).SetProjection(Projections.Property("TaskName"));\n\n// Filter Work Shop Items for any that do not have a To-do item \nquery.Add(SubQueries.PropertyNotIn("Name", allTodos);\n\n// Return results\nvar matchingItems = query.Future<WorkShopItem>().ToList()	0
633226	633203	Convert some JavaScript to JQuery	var href = this.href;\nvar startPos = href.indexOf("(") + 1;\nvar endPos = href.indexOf(")");\n\nvar parms = href.substr(startPos, endPos - startPos).split(",");	0
1761385	1761328	Chunkinfying stream. Is code correct? Need a second set of eyes	int pos = 0;\nint chunkSize = 10000;\n\nwhile (pos < bytes.Length)\n{\n    if (pos + chunkSize > bytes.Length)\n        chunkSize = bytes.Length - pos;\n\n    stream.Write(bytes, pos, chunkSize);\n    pos += chunkSize;\n}	0
16833167	16824555	First Item in ComboBox in other color	private void cmb_DrawItem(object sender, DrawItemEventArgs e)\n{\n    if (e.Index > -1)\n    {\n        e.DrawBackground();\n\n        Brush brush = Brushes.Black;\n\n        if (e.Index == 0)\n        {\n            brush = Brushes.Red;\n        }\n\n        e.Graphics.DrawString(((ComboBox)sender).Items[e.Index].ToString(), ((Control)sender).Font, brush, e.Bounds.X, e.Bounds.Y);\n    }\n}	0
2855330	2835232	asp.net gridview set format for unbound field	protected void SummaryGrid_RowDataBound(object sender, GridViewRowEventArgs e)\n    {\n         if (e.Row.RowType == DataControlRowType.DataRow)  \n         {  \n             double value = Convert.ToDouble(e.Row.Cells[4].Text);  \n             e.Row.Cells[4].Text = value.ToString("#,#.##");              \n         }	0
17304299	17302739	How to find ASP.NET DataGrid current cell contents	Sub MYGrid_Click(ByVal Src As Object, ByVal e As DataGridCommandEventArgs)	0
30682381	30682166	How to use Compare Validator for dates if the date is split in several fields?	string dateString = String.Format("{0} {1}:{2}:00", DateField.Text, TimeSelector1.Hour, TimeSelector1.Minute);\nDateTime selectedDateTime = new DateTime();\nif (DateTime.TryParse(dateString, out selectedDateTime))\n{\n    if (selectedDateTime > DateTime.Now.AddHours(24))\n    {\n        // code\n    }\n}	0
8101158	8101117	image opacity level to 100%	private void playButton_MouseEnter(object sender, System.Windows.Input.MouseEventArgs e)\n{\n   if ( sender is Button )\n      ((Button)sender).Opacity = 1;\n}	0
31921043	31920966	capture keystroke without blocking	Console.KeyAvailable	0
12388995	12388912	How to run a command in terminal and capture the output	Process p = new Process(); // Redirect the output stream of the child process.\np.StartInfo.RedirectStandardOutput = true;\np.StartInfo.FileName = "program.exe"; \np.Start();  // Do not wait for the child process to exit before reading to the end of its     redirected stream.\np.WaitForExit(); // Read the output stream first and then wait.\nstring output = p.StandardOutput.ReadToEnd();\np.WaitForExit();	0
19299151	19298323	Skip Sat and Sunday and get the date by from the current date in ASP.NET?	public static DateTime GetDateIn(int numWorkingHours)\n{\n    int numDays = numWorkingHours / 8;\n    DateTime date = DateTime.Now;\n    // normalize to monday\n    if (date.DayOfWeek == DayOfWeek.Saturday || date.DayOfWeek == DayOfWeek.Sunday)\n        date = date.AddDays(date.DayOfWeek == DayOfWeek.Sunday ? 1 : 2); \n    int weeks = numDays / 5;\n    int remainder = numDays % 5;\n    date = date.AddDays(weeks * 7 + remainder);  \n    // normalize to monday\n    if (date.DayOfWeek == DayOfWeek.Saturday || date.DayOfWeek == DayOfWeek.Sunday)\n        date = date.AddDays(date.DayOfWeek == DayOfWeek.Sunday ? 1 : 2);    \n    return date;\n}	0
22482957	22481065	How to show labels in custom range on AxisX in MSchart?	foreach (Series series in chart1.Series)\n    foreach (DataPoint p in series.Points)\n        if (Math.Abs(p.YValues[0]) < 0.00000001)\n            p.AxisLabel = String.Empty;	0
7501174	7501071	C# - Is it possible to make divide-by-zeros return a number, instead of throwing an exception?	double SafeDiv(double num, double denom) {\n   if(denom == 0) {\n      return 1;\n   }\n   return num/denom;\n}	0
19268814	19242776	Store password on device	void StoreLoginCredentials(string password)\n{\n    var userDetails = NSUserDefaults.StandardUserDefaults;\n    userDetails.SetString(password, "password");\n    userDetails.Synchronize();\n}\n\nbool CheckUserSession()\n{\n    var userDetails = NSUserDefaults.StandardUserDefaults;\n    return userDetails["password"] != null;\n}\n\nbool DestroyLoginCredentials()\n{\n    var defaults = NSUserDefaults.StandardUserDefaults;\n    defaults.RemovePersistentDomain(NSBundle.MainBundle.BundleIdentifier);\n    return defaults.Synchronize();\n}\n\nstring PasswordOfUser()\n{\n    var userDetails = NSUserDefaults.StandardUserDefaults;\n    return userDetails["password"];\n}	0
29548609	29547591	Inject a singleton with parameters	using System;\n\nnamespace UnitTestProject3\n{\n    public interface IFoo\n    {\n        int GetAllTheFoo();\n    }\n\n    public interface IInitialiser\n    {\n        void Initialise(int x);\n\n        int GetX();\n\n        bool IsReady { get; }\n    }\n\n    public class Foo : IFoo\n    {\n        private bool isInitalised;\n        private int x;\n        private IInitialiser i;\n        public Foo(IInitialiser i)\n        {\n            this.isInitalised = false;\n            this.i = i;\n        }\n\n        protected void Init()\n        {\n            if (this.isInitalised)\n            {\n                return;\n            }\n            else if (i.IsReady)\n            {\n                x = i.GetX();\n                this.isInitalised = true;\n                return;\n            }\n            else\n            {\n                throw new Exception("you have not set x");\n            }\n        }\n\n        public int GetAllTheFoo()\n        {\n            Init();\n            return x;\n        }\n    }\n\n}	0
4375941	4375670	Extracting Lat/Long from Bing Geocoding service	var xml = XDocument.Load(@"c:\temp\geo.xml"); // or from stream or wherever\n\nXNamespace ns = "http://schemas.microsoft.com/search/local/ws/rest/v1";\nvar points = (from p in xml.Descendants(ns + "Point")\n              select new\n                      {\n                        Lat = (double) p.Element(ns + "Latitude"),\n                        Long = (double) p.Element(ns + "Longitude")\n                      })\n               .ToList();	0
11286225	11286215	C# dictionary with a float value?	var littledictionary = new Dictionary<string,float>();\nlittledictionary.Add("price", (float)0.0);	0
6499336	6494400	Drag a file url from a winforms control to external application	if (is_in_selection)\n{\n    sel_rows = from DataGridViewRow r in gridFiles.SelectedRows select r;\n    var files = (from DataGridViewRow r in gridFiles.SelectedRows select all_files[r.Index]);\n    string[] files_paths = files.Select((f) => f.FullPathName).ToArray();\n    var data = new DataObject(DataFormats.FileDrop, files_paths);\n    gridFiles.DoDragDrop(data, DragDropEffects.Copy);\n}	0
5594100	5593577	Get the indexes of selected rows in GridView	protected void CheckBox1_CheckedChanged(object sender, System.EventArgs e)\n{\n    CheckBox checkbox = (CheckBox)sender;\n    GridViewRow row = (GridViewRow)checkbox.NamingContainer;\n    if (checkbox.Checked == true) {\n        row.BackColor = System.Drawing.Color.Red;\n        mygridview.Columns(0).Visible = false;\n    }\n}	0
3395848	3389033	How do I get the overload through reflection at runtime?	method.DeclaringType.GetMethods()\n    .Where(x => x.Name == "UserInsert" \n           && x.GetParameters().Count() > 1)\n    .Single()	0
11910733	11910448	Displaying a MessageBox on top of all forms, setting location and/or color	class MyForm : Form {\n    void method(){\n       MessageBox.Show(this, "blablablablabla");\n    }\n}	0
11146900	11146811	Asynchronous method with foreach	public static IEnumerable<JObject> GetUsers(IEnumerable<string> usersUids, Field fields)\n{\n    var results = new List<JObject>\n    Parallel.ForEach(usersUids, uid => {\n        var parameters = new NameValueCollection\n                             {\n                                 {"uids", uid},\n                                 {"fields", FieldsUtils.ConvertFieldsToString(fields)}\n                             };\n        var user = GetUser(parameters).Result;\n        lock(results)\n            results.Add(user);\n    });\n    return results;\n}	0
12388558	12387449	How to get the absolute position of an element?	var ttv = MainTextBlock.TransformToVisual(Window.Current.Content);\nPoint screenCoords = ttv.TransformPoint(new Point(0, 0));	0
11325290	11325250	splitting string into array with a specific number of elements, c#	List<string> trainterms = traindocs[tr].Trim().Split('\n').Take(1000).ToList();	0
20582252	20581928	How to fetch records of specific rows from data table?	WITH T AS\n(\n    SELECT TOP 40 NP.*, row_number() OVER (ORDER BY id) AS RN from NewPatient NP Order by xx\n)\nSELECT * from T where RN>=20	0
1992561	1992509	Best way to decode hex sequence of unicode characters to string	using System;\nusing System.Text;\n\nclass Program {\n  static void Main(string[] args) {\n    uint utf32 = uint.Parse("1D0EC", System.Globalization.NumberStyles.HexNumber);\n    string s = Encoding.UTF32.GetString(BitConverter.GetBytes(utf32));\n    foreach (char c in s.ToCharArray()) {\n      Console.WriteLine("{0:X}", (uint)c);\n    }\n    Console.ReadLine();\n  }\n}	0
3295596	3295561	Search across fields in Lucene	string[] fields = new string[2];\nfields[0] = "title";\nfields[1] = "instructions";\n\nLucene.Net.QueryParsers.MultiFieldQueryParser multiFieldParser = new MultiFieldQueryParser(fields, analyzer);\nQuery multiFieldQuery = multiFieldParser.Parse("20");\nHits multiHits = isearcher.Search(multiFieldQuery);	0
4076259	4075802	Creating a DPI-Aware Application	this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); // for design in 96 DPI	0
1698250	1698153	Calling a Stored Procedure with XML Datatype	StringWriter sw = new StringWriter(); \nXmlTextWriter xw = new XmlTextWriter(sw); \ndoc.WriteTo(xw); \nStringReader transactionXml = new StringReader(sw.ToString()); \nXmlTextReader xmlReader = new XmlTextReader(transactionXml); \nSqlXml sqlXml = new SqlXml(xmlReader);	0
1832956	1832924	How do you declare a C# variable into an HTML type variable?	input type="hidden" name="name_type" value='textbox1.Text'	0
7164410	7164329	How to write a an EF query involving a many to many relationship	var context = new DbContext();\nvar result = context.Securables\n                    .Where(s => s.Roles\n                                 .Any(r => r.Users\n                                            .Any(u => u.UserId = userId)))\n                    .Distinct();	0
24960515	24957804	Windows Store App 8.1 - share multiple DataPackages	Windows.ApplicationModel.DataTransfer.DataTransferManager.showShareUI();	0
1438600	1438571	Where can I find character constants in C#?	if (e.KeyChar == Keys.Back)\n{\n\n}	0
31547037	31105051	Type of object to cast to when parsing DataGrid.SelectedItems (bound to a MySql DataTable)	foreach (DataRowView drRow in DgrReadWrite.SelectedItems)\n            {\n                listOfRowsToDelete.Add(drRow.Row);\n                // put index numbers into a string for MySQL query\n                ids = ids + drRow["index"] + ",";\n            }	0
16745086	16745045	Display DriveInfo to textbox	public Form()\n{\n\n    DriveInfo[] allDrives = DriveInfo.GetDrives();\n    foreach (DriveInfo d in allDrives)\n    {\n        if (d.IsReady && d.DriveType == DriveType.Network)\n        {\n            textBox3.Text+= String.Format("{0} Drive {1} is ready and a network drive", Environment.NewLine, d.VolumeLabel);\n\n        }\n    }\n}	0
26906917	26906476	First combobox item missing after combobox filled with datatable	string query = "SELECT Id,Name,Text FROM ApsisSms ORDER BY Id DESC";\nOleDbDataAdapter da = new OleDbDataAdapter(query, conn);\nconn.Open();\nda.Fill(dtSmsMessages);\n\nif (dtSmsMessages.Rows != null && dtSmsMessages.Rows.Count > 0)\n{\ncomboSMSMessages.Items.Clear();\n\ncomboSMSMessages.Items.Add(new ComboboxItem() { Text = "(new)", Value = "-1" });\nfor (int i = 0; i < dtSmsMessages.Rows.Count; i++)\n{\n ComboboxItem item = new ComboboxItem()\n    {\n        Text = dtSmsMessages.Rows[i]["Name"].ToString(),\n        Value = dtSmsMessages.Rows[i]["Id"].ToString()\n    };\n    comboSMSMessages.Items.Add(item);\n }\n}\ncomboSMSMessages.SelectedIndex = -1;	0
14306390	14305950	How to Make a UserControls BackColor Transparent in C#?	var pos = this.PointToScreen(userControl11.Location);\nuserControl11.Parent = pictureBox1;\nuserControl11.Location = pictureBox1.PointToClient(pos);	0
9325411	9325264	How to pass Json object in WCF Rest?	[WebInvoke(UriTemplate = "Login", Method = "POST", ResponseFormat = WebMessageFormat.Json, RequestFormat = WebMessageFormat.Json)]\n public WRModel.Entities.Session Login(LoginDetails details)	0
30903467	30863216	Web API translating input into random int	class Program\n    {\n        static void Main(string[] args)\n        {\n            Console.WriteLine("Sending in: \n43443333222211111117");\n            var largeBrokenNumber = JsonConvert.DeserializeObject<Foo>("{\"Blah\": 43443333222211111117 }");\n            Console.WriteLine(largeBrokenNumber.Blah);\n\n            Console.WriteLine();\n\n            Console.WriteLine("Sending in: \n53443333222211111117");\n            var largeOddWorkingNumber = JsonConvert.DeserializeObject<Foo>("{\"Blah\": 53443333222211111117 }");\n            Console.WriteLine(largeOddWorkingNumber.Blah);\n        }\n    }\n\n    public class Foo\n    {\n        public string Blah { get; set; }\n    }	0
5291215	5290308	Take a Picture of Persenels with a Digital Camera Attached To Computer	public static WIA.Device SelectCamera() {\n        var dlg = new WIA.CommonDialog();\n        try {\n            return dlg.ShowSelectDevice(WIA.WiaDeviceType.CameraDeviceType, false, false);\n        }\n        catch (System.Runtime.InteropServices.COMException ex) {\n            if (ex.ErrorCode == -2145320939) return null;\n            throw;\n        }\n    }	0
5596076	5596006	How do I determine if the value of a string variable changed in C#?	// holds a copy of the previous value for comparison purposes\nprivate string oldString = string.Empty; \n\nprivate void button6_Click(object sender, EventArgs e)\n{\n    // Get the new string value\n    string newString = //some varying value I get from other parts of my program\n\n    // Compare the old string to the new one\n    if (oldString != newString)\n    {\n        // The string values are different, so update the ListBox\n        listBox1.Items.Clear();\n        listBox1.Items.Add(x + /*other things*/);   \n    }\n\n    // Save the new value back into the temporary variable\n    oldString = newString;\n}	0
7295739	7294765	Problem with calling a powershell function from c#	using (Runspace runspace = RunspaceFactory.CreateRunspace())\n        {\n            runspace.Open();\n            PowerShell ps = PowerShell.Create();\n            ps.Runspace = runspace;\n            ps.AddScript(script);\n            ps.Invoke();\n            ps.AddCommand("BatAvg").AddParameters(new Dictionary<string, string>() {\n                {"Name" , "John"}, {"Runs", "6996"}, {"Outs","70"}\n            });\n            foreach (PSObject result in ps.Invoke())\n            {\n                Console.WriteLine(result);\n            }\n        }	0
1014015	1014005	How to populate/instantiate a C# array with a single value?	public static void Populate<T>(this T[] arr, T value ) {\n  for ( int i = 0; i < arr.Length;i++ ) {\n    arr[i] = value;\n  }\n}	0
12133978	12133654	Matching multiple domains in an XPath expression	.//a[contains(@href,'site.com')\n   or\n     contains(@href,'othersitesite.com')\n   or\n     contains(@href, 'thirdsite.com')\n     ]	0
13823796	13803090	datagridview dynamic with image	private void TabelaDinamimcaSucess(bool sucesso, int index, string host, string data, string tempo,string status)\n{\n\n   string[] row = new string[] { index.ToString(), host, data, tempo,status };\n   dataGridView1.Rows.Add(row);\n\n    int number_of_rows = dataGridView1.RowCount -1;\n\n    Bitmap b = new Bitmap((sucesso == true ? Properties.Resources.greenBall : Properties.Resources.redBall));\n    Icon icon = Icon.FromHandle(b.GetHicon());\n\n    dataGridView1.Rows[number_of_rows].Cells["img"].Value = icon;\n\n    dataGridView1.Show();\n}	0
28742922	28742704	find whether a string contains any special characters and remove with string.empty c#	string StringToCheck = ";#abc@()[]_123-~`";\nstring newstring = new String(stringToCheck.Where(x => Char.IsLetterOrDigit(x)).ToArray());	0
1171773	1171751	C# newbie: reading repetitive XML to memory	XmlDocument myDoc = new XmlDocument()\nmyDoc.Load(fileName);\n\nforeach(XmlElement elem in myDoc.SelectNodes("Elements/Element"))\n{\n    XmlNode nodeName = elem.SelectSingleNode("Name/text()");\n    XmlNode nodeType = elem.SelectSingleNode("Type/text()");\n    XmlNode nodeColor = elem.SelectSingleNode("Color/text()");\n\n    string name = nodeName!=null ? nodeName.Value : String.Empty;\n    string type = nodeType!=null ? nodeType.Value : String.Empty;\n    string color = nodeColor!=null ? nodeColor.Value : String.Empty;\n\n    // Here you use the values for something...\n}	0
34095201	34095051	Can you set a variable to console.ReadLIne()?	//Set Variable\nFunc<string> read = Console.ReadLine;\n//Call vaariable\nread();	0
25293842	25293763	how do I change a dynamically created property from a Event function?	public partial class Form2 : Form\n{\n    private FlowLayoutPanel flp = new FlowLayoutPanel();\n    public Form2(List<IPAddress> addresses)\n    {\n        InitializeComponent();    \n\n        flp.AutoScroll = true;\n        flp.FlowDirection = FlowDirection.TopDown;\n        flp.Location = new System.Drawing.Point(12, 67);\n        flp.AutoSize = false;\n        flp.Height = 600;\n        flp.Width = 1110;\n        flp.WrapContents = false;\n    }\n}	0
32805741	32805706	How can i detect which number sum to my output sum in c#?	for (int i = 0; i < arr1.Length; i++)\nfor (int j = 0; j < arr1.Length; j++)\n{\n    if (i == j) continue;\n\n    Int64 sum = arr1[i] + arr1[j];\n    if (sum == 984724000)\n        Console.WriteLine(arr1[i].ToString() + "+" + arr1[j].ToString())\n}	0
23069518	23067964	How can I embed or navigate to a page contained in another namespace	Frame.Navigate(typeof(MyControl.MainPage))	0
25785815	25785503	Improve performance of code	string[] empDetails = { "1,abc,2,11k", "2,de,3,11k", "3,abc,2,18k", "4,abdc,2,12k" };\nstring[] empToRemove = { "1", "3" };\n\nvar remove = new HashSet<string>(empToRemove);\nforeach (var item in empDetails)\n{\n    string id = item.Substring(0, item.IndexOf(','));\n    if (!remove.Contains(id))\n        Console.WriteLine(item); // or your custom action with this item\n}	0
4375145	4375088	Debug a Windows Service	static void Main()\n{\n#if (!DEBUG)\n\n\n            ServiceBase[] ServicesToRun;\n            ServicesToRun = new ServiceBase[] { new Service1Component() };\n            ServiceBase.Run(ServicesToRun);\n\n\n#else\n            Service1Component s = new Service1Component();\n            s.StartProcess();\n#endif\n}	0
11465064	11464980	Regular Expression for Non decimal positive integer ranging between 0 to 999999	Regex.IsMatch("999999","^[0-9]{0,6}$");//return true	0
3307634	3307593	Get DateTime Value from TextBox in FormView	//If you really need to find the textbox\n    TextBox dateTextBox = \n            FormView1.FindControl("user_last_payment_date") as TextBox;\n\n    if(dateTextBox == null)\n    {\n        //could not locate text box\n        //throw exception?\n    }\n\n    DateTime date = DateTime.MinValue;\n\n    bool parseResult = DateTime.TryParse(dateTextBox.Text, out date);\n\n    if(parseResult)\n    {\n        //parse was successful, continue\n    }	0
9138288	9138069	How to get <p> element values in XML?	const string url = "http://feeds.feedburner.com/TechCrunch";\nvar doc = XDocument.Load(url);\nvar items = doc.Descendants("item");\nXNamespace nsContent = "http://purl.org/rss/1.0/modules/content/";\nforeach (var item in items)\n{\n    var encodedContent = (string)item.Element(nsContent + "encoded");\n    var decodedContent = System.Net.WebUtility.HtmlDecode(encodedContent);\n    var html = new HtmlDocument();\n    html.LoadHtml(decodedContent);\n    var ps = html.DocumentNode.Descendants("p");\n    foreach (var p in ps)\n    {\n        var textContent = p.InnerText;\n        // do something with textContent\n    }\n}	0
25228504	25228406	attach file to an email in c#	using (var zip = new ZipFile())\n{\n    zip.AddDirectory("DirectoryOnDisk", "rootInZipFile");\n    zip.Save("MyFile.zip");\n}	0
5624248	5624125	Using variables as selectors with Selenium 2 Webdriver by.cssselector	string surveyName = "Selenium test survey";\nDriver.FindElement(By.CssSelector(String.Format("tr[svd='{0}']", surveyName))	0
11289104	11272672	Data Contract Known Types and a set of interfaces inheriting each other	[KnownType("GetKnownType")]\npublic class Section\n{\n    static Type[] GetKnownType()\n    {\n        return new[]\n        {\n            Type.GetType("Project.Format.A.DataSectionFormatA, Project.Format.A")\n        };\n    }\n}	0
9139872	9139778	Get all instances of sub-string one at a time?	var strings = myString.Split('0');\nvar replaced = new StringBuilder(strings[0]);\n\nfor (var i = 1; i < strings.Length; ++i)\n{\n    replaced.Append("REPLACED " + i.ToString());\n    replaced.Append(strings[i]);\n}	0
29854224	29854131	How to use a common interface between SerialPort and NetworkStream in C#?	private bool _TryReadChunk(Stream connection, int n_exp, out byte[] received)\n{\n    ...\n}	0
31137027	31136723	How to delete Azure blob from asp.net web api?	var result= blockBlob.DeleteIfExists();	0
23950059	23949744	Insert a XML in a Dictionary using LINQ in C#	var datas = xDocument.Root.Elements()\n                .Select(\n                    e => e.Descendants().Count() > 0?\n                    new { \n                        key = e.Descendants().Single(x => x.Name.LocalName == "SubNode1").Value,\n                        value =  e.Descendants().Select(x => x.Value).ToList()\n                        }:\n                    new { \n                        key = e.Name.LocalName, \n                        value = new List<string>(){ e.Value } \n                        }\n                ).ToDictionary( k => k.key, v => v.value );	0
22927953	22927864	specifying font for a row in pdf table c#	if(r[3].ToString()=="0")	0
28799526	28798766	C#, WPF, Having trouble opening a new window	public CreateAccount()\n{\n   InitializeComponent();\n}	0
2390440	2390394	Checking element values in a Boolean array - C#	private void print_button_Click(object sender, EventArgs e) {\n  if (authorbox.Text == "") {\n    MessageBox.Show("Author field empty", "Required Entry");\n    return;\n  }\n\n  if (titlebox.Text == "") {\n    MessageBox.Show("Title field Empty", "Required Entry");\n    return;\n  }\n\n  printPreviewDialog1.Document = printDocument1;\n  printPreviewDialog1.ShowDialog();\n}	0
1291923	1291513	Accessing the root visual of a ContentPresenter hosting a DataTemplate	public UIElement GetRootVisual()\n    {\n        UIElement root = AdornedElement;\n        if (root != null)\n        {\n            UIElement parent = VisualTreeHelper.GetParent(root) as UIElement;\n            if (parent != null)\n            {\n                root = parent;\n            }\n        }\n\n        return root;\n    }	0
21429673	21428977	Call Excel Macro from Ribbon Button	Globals.ThisWorkbook.Application.Run("Your macroname")	0
33014962	33000754	IBM MQListener Not Automatically Remove Message From Queue	openOptions = MQC.MQOO_BROWSE  // open queue for browsing	0
27346584	27344976	Sending huge base64 image to PHP via POST	FcgidMaxRequestLen 260000	0
26790525	26790455	Loop through a folder containing images, resize images and place in new folder	var files = new DirectoryInfo(@"C:\Source\")\n            .GetFiles()\n            .Where(f => f.IsImage());\n\nforeach (var file in files)\n{\n      using (var image = Image.FromFile(file.FullName))\n      {\n            using (var newImage = ScaleImage(image, 150, 150))\n            {\n                try\n                {\n                    var newImageName = Path.Combine(@"C:\Dest\", Path.GetFileNameWithoutExtension(file.Name) + "_resized" + file.Extension);\n                    newImage.Save(newImageName, ImageFormat.Jpeg);\n                }\n                catch\n                {\n                    continue;\n                }\n            }\n        }\n    }\n}\n\n\npublic static class Extensions\n{\n    public static bool IsImage(this FileInfo file)\n    {\n        var allowedExtensions = new[] {".jpg", ".png", ".gif", ".jpeg"};\n        return allowedExtensions.Contains(file.Extension.ToLower());\n    }\n}	0
26296565	26296479	Get index of random matching value	// Do this once only\nvar rnd = new Random();\n\n// Do this each time you want a random element.\nvar key = myList.Min();\nvar indices = mylist\n             .Select((n,index) => new { n, index })\n             .Where(x => x.n == key)\n             .Select(x => x.index)\n             .ToList();\nint anyOldOne= indices[rnd.Next(indices.Count)];	0
374544	374496	Add extra column to fill out space in datagridview C#	DataTable dt = new DataTable("Table1");\n        dt.Columns.Add("A");\n        dt.Columns.Add("B");\n        dt.Columns.Add("C");\n        dt.Rows.Add(1, 2, 3);\n        this.dataGridView1.DataSource = dt;\n        this.dataGridView1.Columns[dataGridView1.Columns.Count - 1].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;	0
25723410	25723301	Clear specific tabpage text boxes	void ClearTextBoxes(Control parent)\n    {\n        foreach (Control child in parent.Controls)\n        {\n            TextBox textBox = child as TextBox;\n            if (textBox == null)\n                ClearTextBoxes(child);\n            else\n                textBox.Text = string.Empty;\n        }\n    }\n\n    private void resetCurrentPageToolStripMenuItem_Click(object sender, EventArgs e)\n    {\n        ClearTextBoxes(tabControl1.SelectedTab);\n    }	0
9624924	9624907	NullReferenceException was unhandled, when making SlimDX screen capture in C#	public Device device;	0
29194505	29194457	How to get properties from an object without initializing or constructing the object	[Plugin(Name = "My Plugin", SafeName = "MyPlugin" ...)]\npublic class InputMonitor	0
9805830	9801366	Hide background graphics on inserting a new slide to a presentation programmatically	With lPresentation.Slides[2]\n  .Property = Value\n  .OtherProperty = OtherValue\n  .Etc = "And so forth"\nEnd With	0
1317025	1316618	How to get full Url from a Html Helper Class that I made?	VirtualPathUtility.ToAbsolute(src);	0
2603974	2602210	Don't serealize a especific data member , but DESEREALIZE, any chance?	[DataContract]\npublic class Customer\n{\n    [IgnoreDataMember]\n    public Age Age { get; set; }\n\n    [DataMember]\n    public string Name { get; set; }\n}	0
13505939	13505848	Display text under overlay item	String text = ?example toast text!?;\nToast toast = Toast.makeText(getApplicationContext(), text, Toast.LENGTH_SHORT);\n\n/* Positioning your Toast */\nint offsetX = 0, offsetY = 0;\ntoast.setGravity(Gravity.TOP, offsetX, offsetY);\ntoast.show();	0
8397222	8397044	Manage two or more frames datagridview with one scrollbar in c#?	private void dataGridSource_Scroll(object sender, ScrollEventArgs e)\n    {\n        if(e.ScrollOrientation == ScrollOrientation.VerticalScroll)\n        {\n            int i = dgvLog.FirstDisplayedScrollingRowIndex ;\n            dataGridTarget.FirstDisplayedScrollingRowIndex  = i;\n        }\n    }	0
5326657	5326453	User Control Buttons to Close a Dialog Box	this.ParentForm.DialogResult = DialogResult.OK;	0
7238904	7238750	What can I expect from Fluent NHibernate?	var fund = new Fund{\n   ID = 1,\n   Name = "YourNewName",\n   Holdings = new List<Holding>{\n     new Holding{\n       ID = 1\n       Description = "NewHoldingDescription"\n     }\n   }\n}\n\n//and then perform a SaveOrUpdate() on the fund, it should update the entries in the database	0
21551206	21551134	I'm having one grid view in asp.net c# and I want to enable one label which can show details of particular row	protected void LinkButton1_Click(object sender, EventArgs e)\n{\n    Label lbl1 = (Label)(((LinkButton)sender).NamingContainer as DataListItem).FindControl("Label14");\n    Response.Redirect("ShowUser.aspx?uid=" + lbl1.Text);\n}	0
7980880	7980523	How to update a control in MDI parent form from child forms?	// Code from Form 1\npublic partial class Form1 : Form\n{\n    public Form1()\n    {\n        InitializeComponent();\n    }\n    private void button1_Click(object sender, EventArgs e)\n    {\n        Form2 objForm2 = new Form2();\n        objForm2.ChangeStatus += new ChangeStatusHandler(objForm2_ChangeStatus);\n        objForm2.Show();\n    }\n    public void objForm2_ChangeStatus(string strValue)\n    {\n        statusbar.Text = strValue;\n    }\n}\n\n// Code From Form 2\npublic delegate void ChangeStatusHandler(string strValue);\npublic partial class Form2 : Form\n{\n    public event ChangeStatusHandler ChangeStatus;\n\n    public Form2()\n    {\n        InitializeComponent();\n    }\n\n    private void button1_Click(object sender, EventArgs e)\n    {\n        if (PassValue != null)\n        {\n            PassValue(textBox1.Text);\n        }\n    }\n}	0
7120556	7090053	Read all ini file values with GetPrivateProfileString	[DllImport("kernel32.dll")]\nprivate static extern int GetPrivateProfileSection(string lpAppName, byte[] lpszReturnBuffer, int nSize, string lpFileName);\n\nprivate List<string> GetKeys(string iniFile, string category)\n{\n\n    byte[] buffer = new byte[2048];\n\n    GetPrivateProfileSection(category, buffer, 2048, iniFile);\n    String[] tmp = Encoding.ASCII.GetString(buffer).Trim('\0').Split('\0');\n\n    List<string> result = new List<string>();\n\n    foreach (String entry in tmp)\n    {\n        result.Add(entry.Substring(0, entry.IndexOf("=")));\n    }\n\n    return result;\n}	0
21136492	21135643	Validate a URL exists or not from DB	public bool IsContentUrlExists(string url)\n{\n      url = url.Trim().TrimEnd(new[]{'/'});\n      return Context.Contents.Any(content => content.Url == url || content.Url == url + "/");\n}	0
20801063	20790978	Creating hierarchical JSON result from multiple tables using linq expression	public IQueryable<vwBatchList> AggregateBatchList(int coid)\n{\n     var contex = new LBPEntities();\n     var batchList = contex.vwBatchLists.Where(x => x.CoId == coid).Select(x => new\n                  {\n                        CoId = x.CoId,\n                        ...\n                        BatchDetails = contex.vwBatchDetails.Where(d => d.BatchNumber == x.batchNumber)\n                  });\n\n     var result = Json(batchList);\n}	0
12832990	12832926	How to add string to IEnumerable - C#	var list = new List<string>();\nlist.Add(Path.Combine(Server.MapPath("~/Content/themes/base/songs"),\n                           file));\na.Song = list;	0
5826658	5826475	Inject an event as a dependency	public interface IIdlingSource\n{\n    event EventHandler Idle;\n}\n\npublic sealed class ApplicationIdlingSource : IIdlingSource\n{\n    public event EventHandler Idle\n    {\n        add { System.Windows.Forms.Application.Idle += value; }\n        remove { System.Windows.Forms.Application.Idle -= value; }\n    }\n}\n\npublic class MyClass\n{\n    public MyClass(IIdlingSource idlingSource)\n    {\n        idlingSource.Idle += OnIdle;\n    }\n\n    private void OnIdle(object sender, EventArgs e)\n    {\n        ...\n    }\n}\n\n// Usage\n\nnew MyClass(new ApplicationIdlingSource());	0
31153705	31151817	Cannot swap unique value on two rows with EF	BEGIN TRANSACTION;\nUPDATE MyTable Set Id = 200 where Id = 1;\nUPDATE MyTable Set Id = 1 where Id = 2;\nUPDATE MyTable Set Id = 2 where Id = 200;\nCOMMIT;	0
3364263	3364252	Display a & in a menuitem or menustrip	menuItem.Text = "Foo && Bar";	0
612222	612203	Creating a SQLCommand for use in a SQLDataAdapter	// Create the DeleteCommand.\ncommand = new SqlCommand(\n    "DELETE FROM Customers WHERE CustomerID = @CustomerID", connection);\n\n// Add the parameters for the DeleteCommand.\nparameter = command.Parameters.Add(\n      "@CustomerID", SqlDbType.NChar, 5, "CustomerID");\nparameter.SourceVersion = DataRowVersion.Original;\n\nadapter.DeleteCommand = command;	0
23478359	23469121	MIME type to extension Windows Universal app	Windows.Graphics.Imaging.BitmapDecoder.GetDecoderInformationEnumerator()	0
9786126	9786054	How can I make image in text box with no-repeat	input.textbox\n{\n   background-image: url('Popup(Images)/Solved.png');\n   background-repeat:no-repeat;\n}\n\n<asp:TextBox ID="TextBox1" runat="server" CssClass="textbox" BorderStyle="None"  />	0
21110992	21110535	How to insert only added value in TextBox on DB?	public bool Addcomment(string Post_ID, string User_ID, string Comment_Content, DateTime Comment_Add_Date, DateTime Comment_Last_Date, bool Comment_Flag)\n{\n\n    SqlCommand cmd = new SqlCommand("dbo.Insertintocomments");\n    cmd.CommandType = CommandType.StoredProcedure;\n    cmd.Parameters.AddWithValue("@Post_ID", Post_ID);\n    cmd.Parameters.AddWithValue("@User_ID", User_ID);\n    Comment_Content = Comment_Content.Contains(",") ? Comment_Content.Replace(",", null) : Comment_Content;\n    cmd.Parameters.AddWithValue("@Comment_Content", Comment_Content);\n    cmd.Parameters.AddWithValue("@Comment_Add_Date", Comment_Add_Date);\n    cmd.Parameters.AddWithValue("@Comment_Last_Date", Comment_Last_Date);\n\n    cmd.Parameters.AddWithValue("@Comment_Flag", Comment_Flag);\n\n    return DBHelper.Instance().Insert(cmd);\n}	0
12786349	12786304	Accessing property through string name	typeof(MyClass).GetProperty(PropertyName).SetValue(_myClass, 5);	0
12626487	12626445	Splitting a string that is a property of an object, creating new objects from the split strings. Is there an elegant way?	List<object2> newObjects = object1.commaSeparatedListOfIds.Split(',')\n                                   .Select(str =>\n                                        new object2\n                                        {  \n                                           id = int.Parse(str),\n                                           time = object1.time,\n                                           passes = object1.passes\n                                        })\n                                   .ToList();	0
5700798	5700741	Color cells in WPF DataGrid dynamically	public int RealProperty { .... }\n\n  public SystemColors.AppWorkspaceColor Colour { return manglefromInt(RealProperty); }	0
19080533	19080273	One to Many Casade Deletes	{\n//...\nmodelBuilder.Entity<Parent>()\n    .HasMany(e => e.ParentDetails)\n    .WithOptional(s => s.Parent)\n    .WillCascadeOnDelete(true);\n//...	0
24885774	24885077	Remove elements from string after list of characters- without using a foreach loop	fooString = fooString.Substring(0, fooString.IndexOfAny(BAD_CHARS));	0
5794775	5794744	Returning a JObject as Json from an endpoint	return Content(taxonomyJson.ToString(), "application/json");	0
6933543	6933059	wpf - how to use dataTemplate for treeViewItems	ItemTempate="{StaticResource CellTemplate}"	0
18954257	18954166	Insert text in specific cell in Excel c#	Excel.Application excelApplication = new Excel.Application();\nExcel.Workbook excelWorkBook = excelApplication.Workbooks.Add();\nExcel.Worksheet wkSheetData = excelWorkBook.ActiveSheet;\nexcelApplication.Cells[5, 2] = "TextField";	0
19535788	19535040	Receiving MSMQ messages as a list	private static void Main()\n{\n    var queue = new MessageQueue("myQueue");\n    queue.PeekCompleted += new PeekCompletedEventHandler(OnPeekCompleted);\n\n    // Start listening to queue\n    queue.BeginPeek();\n}\n\nprivate void OnPeekCompleted(object sender, PeekCompletedEventArgs e)\n{\n    var cmq = (MessageQueue)sender;\n    try\n    {\n        var msmqMessage = cmq.EndPeek(e.AsyncResult);\n\n        msmqMessage.Formatter = new XmlMessageFormatter(typeof(messagetypehere));\n\n        var message = msmqMessage.Body;\n\n        // Do logic for the message\n        {\n            // Send mail or what ever\n\n        }\n\n        cmq.Receive(); // Remove the message from the queue\n    }\n    catch (Exception ex) \n    {\n        // Log or other\n    }\n\n    // Refresh queue\n    cmq.Refresh();\n\n    // Start listening to queue\n    cmq.BeginPeek();\n}	0
13145625	13145477	query a view with a list of data	var data = (from p in db.vwdb.Where(p => p.ID == id)\n                 group p by p.status into g select g.Key).ToList();\n\n//Here you'll get the data you want from the database:\nViewData.Model = db.vwStatus.Where(vw => data.Contains(vw.Id));\n\nreturn View();	0
12521769	12454636	Convert Byte Array Tiff To Byte Array Jpeg	Byte[] tiffBytes;\nByte[] jpegBytes;\n\nusing (MemoryStream inStream = new MemoryStream(tiffBytes))\nusing (MemoryStream outStream = new MemoryStream())\n{\n    System.Drawing.Bitmap.FromStream(inStream).Save(outStream, System.Drawing.Imaging.ImageFormat.Jpeg);\n    jpegBytes = outStream.ToArray();\n}	0
3149959	3149804	Generic type parameter constraint based on other type parameter in the same definition	class Derived2<T, U>: Base2<T, U>\n        where T: IMyClass\n        where U: IMyDerived1, IBase1<T>\n    {\n    }	0
23776711	23774001	Reset last draw graphics on text change	Image backgroundImage = (Image)bkp.Clone();\n\n   using (Graphics gfx = Graphics.FromImage(backgroundImage))\n   using (Pen pen = new Pen(Color.Red))\n   {\n      gfx.DrawRectangle(pen,\n                        Convert.ToInt16(txtLeftMargin.Text),\n                        Convert.ToInt16(txtTopMargin.Text),\n                        Convert.ToInt16(txtHeight.Text),\n                        Convert.ToInt16(txtWidth.Text));\n   }\n\n   pictureBox1.Image = backgroundImage;	0
7112878	7102687	A connection attempt failed because the connected party did not properly respond after a period of time	MailMessage mail = new MailMessage();\nmail.To.Add(to);\nmail.From = new MailAddress(from);\nmail.Subject = subject;\nmail.Body = body;\nmail.IsBodyHtml = true;\nSmtpClient smtp = new SmtpClient("smtp.gmail.com",587);\nsmtp.EnableSsl = true;\nsmtp.UseDefaultCredentials = false;\nsmtp.Credentials = new System.Net.NetworkCredential(address, password);\nsmtp.Send(mail);	0
23490246	23490197	Select All object values to list from dictionary	multiOrders.Values.ToList()	0
31252730	31252688	iterating over a dictionary of Regex in C#	public static string Replacements(string text)\n{\n\n    string output = text;\n    foreach (KeyValuePair<string, string> item in dict1)\n    {\n        //here replace output again\n        output = Regex.Replace(output, item.Key, item.Value); \n\n    }\n\n\n    return output;\n}	0
13870892	13870843	Turning a SqlCommand with parameters into a DataTable	using (SqlDataReader dr = command.ExecuteReader())\n{\n    var tb = new DataTable();\n    tb.Load(dr);\n    return tb;\n}	0
5269524	5269098	How to pass an value of type enum to another enum variable?	enum DBType { Int, Double, Float, Bool, String  }\n\n  class DBProperties\n  {\n    private DBType dbType;\n    public DBType DBType { get { return dbType; } set { dbType = value; } }\n  }\n\n  public partial class Form1 : Form\n  {\n    public Form1()\n    {\n      InitializeComponent();\n    }\n\n    private void cbDataType_SelectedIndexChanged(object sender, EventArgs e)\n    {\n      DBType val = (DBType)cbDataType.SelectedIndex;\n      cbDataType.SelectedIndex = (int)val;\n      var dbProperties = new DBProperties();\n      dbProperties.DBType = val;\n    }\n  }	0
3126034	3125692	Efficient foreach child evaluation in parallel	var childToRun = Children.AsParallel().AsOrdered()\n    .Where(x => x.ShouldRun()).FirstOrDefault();\nchildToRun.Run();	0
12270659	12270417	How to lock a DataClass	public Order GetOrder(int id) {\n    // ctx could also be instantiated via an IoC/DI framework, etc\n    using(var ctx = CreateDataContext()) {\n        return ctx.Orders.SingleOrDefault(x => x.Id == id);\n    }\n}\npublic void AddOrder(Order order) {\n    if(order == null) throw new ArgumentNullException("order");\n    // ctx could also be instantiated via an IoC/DI framework, etc\n    using(var ctx = CreateDataContext()) {\n        ctx.Orders.InsertOnSubmit(order);\n        ctx.SubmitChanges();\n    }\n}	0
5906199	5893859	Convert BigInt value in SQL to datetime in c#	DateTime.FromFileTimeUtc()	0
20688875	20688838	Refreshing Controls in runtime	public void Read_in()\n{\n    BackgroundWorker backgroundWorker1 = new BackgroundWorker();\n    backgroundWorker1.DoWork += new DoWorkEventHandler(backgroundWorker1_DoWork);\n    backgroundWorker1.RunWorkerAsync();\n\n}\n\nprivate void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)\n{\n    using (StreamReader sr = new StreamReader("in.txt"))\n    {\n        while (!sr.EndOfStream)\n        {\n            Data d = new Data\n            {\n                a = sr.ReadLine()\n            };\n            if(this.InvokeRequired)\n            {\n                 this.Invoke((MethodInvoker)delegate\n                 {\n                     _list.Add(d);\n                     Controls.Add(d.pb);\n                 });\n\n            }\n            else\n            {\n                 _list.Add(d);\n                 Controls.Add(d.pb);\n\n            }\n        }\n    }\n}	0
5326246	5326188	Regular expression - extract 6 digits exactly	(?<!\d)\d{6}(?!\d)	0
28964049	28963973	C# Reflection - Add element to collection	object cln = propertyInfo.GetValue(target);	0
21691621	21691560	insert values from 2 textbox in one column	cmd.CommandText = "INSERT INTO email (Id,email) VALUES ( @Id, @email )";\n\nfor (int i = 0; i < 2; i++)\n{\n    cmd.Parameters.Clear();\n    cmd.Parameters.AddWithValue("@Id", int.Parse(txtId.Text));\n    cmd.Parameters.AddWithValue("@email", email[i]);\n    cmd.ExecuteNonQuery();\n}	0
24273628	24269972	Date Conversion issue from webservice	TimeSpan offSetSpan = new TimeSpan();\n          string dt = TimestampValue;\n          string offset = TimestampValue.Substring(trackevent.Timestamp.Length - 6,6);\n\n          if (offset != "+00:00" && offset != "-00:00")\n                                {\n                                    offSetSpan = TimeSpan.Parse(offset.Trim());\n                                }\nConsole.WriteLine("Offset Timestamp: {0}", Convert.ToDateTime(TimestampValue).ToUniversalTime() + offSetSpan);	0
11972017	11971569	Creating a List of items from a binding source	var termArray = (from row in definitionDataTable.AsEnumerable() \nwhere row.Field<int>("StoreID")==yourID select row.Field<string>("Term")).ToArray();	0
7349641	7348423	How to remove escape sequences from stream	string inputString = @"hello world]\ ";\n\nStringBuilder sb = new StringBuilder();\nstring[] parts = inputString.Split(new char[] { ' ', '\n', '\t', '\r', '\f', '\v','\\' }, StringSplitOptions.RemoveEmptyEntries);\nint size = parts.Length;\nfor (int i = 0; i < size; i++)\n    sb.AppendFormat("{0} ", parts[i]);	0
11076453	11066466	Entity Framework Console app connecting to the wrong database	db.Database.Connection.ConnectionString	0
20939097	20937661	Datagrid not updating after data change	public SolidColorBrush MyBrushProperty{get{return myBrushProperty;}}\nprivate void CalcMyBrush()\n{\n    var awaiter = YourAsyncCalculation.GetAwaiter();\n    awaiter.OnComplited(()=>\n    {\n     myBrushProperty= (SolidColorBrush)awaiter.GetResult();\n     OnPropertyChanged("MyBrushProperty"); \n    });\n}	0
10048501	10047700	Select 50 previous rows	;WITH RankedRecords AS\n(\n    SELECT\n        ROW_NUMBER() OVER(ORDER BY A_RECID DESC) Row\n        , A_RECID\n    FROM [database]..[table]\n    WHERE A_1STNAME LIKE '(variable)%')\n        AND CAST(LEFT(A_RECID, 8) AS DATE) < CAST(LEFT('(lastPost)', 8) AS DATE)\n)\nSELECT TOP 50\n    T.*\nFROM[database]..[table] T\nINNER JOIN RankedRecords\n    ON RankedRecords.A_RECID = T.A_RECID\n    AND RankedRecords BETWEEN (@LastPost - 51) AND (@LastPost - 1)\nORDER BY RankedRecords.Row	0
9106399	9106177	Removing commented lines from InnerText	public static void RemoveComments(HtmlNode node)\n{\n    foreach (var n in node.ChildNodes.ToArray())\n        RemoveComments(n);\n    if (node.NodeType == HtmlNodeType.Comment)\n        node.Remove();\n}	0
977953	950294	How can I get rid of jerkiness in WinForms scrolling animation?	IDirectDraw::GetScanLine()	0
30859123	30858812	How to make if statement that checks if multple listBoxes are empty or not?	if (listBoxEmails.Items.Count >= 0 && listBoxWebsites.Items.Count >= 0 && \n\n    listBoxComments.Items.Count >= 0)\n    {\n    //perform action\n\n    }	0
1527734	1527706	How do I format DateTime or TimeZone/TimeZoneInfo to display Three letters?	Europe/Paris	0
20205297	20204353	Return string from javascript to c#	geocoder.geocode	0
9063938	9060657	prism navigation: I can requestnavigate to only one particular view	var NatLossesViewobj = _container.Resolve<NatLossesView>() \nregionManager.AddToRegion("DocumentGroupRegion", NatLossesViewobj);	0
7195168	7195136	Open a Win Form but keep it deactivated while another Form opens	ShowDialog()	0
16873346	16866706	Access Nexmo C# API using OAuth	// make a request for a protected resource\nstring responseText = session.Request().Get().ForUrl("http://www.google.com/m8/feeds/contacts/default/base").ToString();	0
5917668	5917658	Reversing a md5 hash algorithm in C#	public static byte[] Compress( byte[] data )\n{\n    var output = new MemoryStream();\n    using ( var gzip = new GZipStream( output, CompressionMode.Compress, true ) )\n    {\n        gzip.Write( data, 0, data.Length );\n        gzip.Close();\n    }\n    return output.ToArray();\n}	0
2370706	2370689	How to validate Guid in .net	private static Regex isGuid = \n      new Regex(@"^(\{){0,1}[0-9a-fA-F]{8}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{12}(\}){0,1}$", RegexOptions.Compiled);\n\ninternal static bool IsGuid(string candidate, out Guid output)\n{\n    bool isValid = false;\n    output = Guid.Empty;\n\n    if(candidate != null)\n    {\n\n        if (isGuid.IsMatch(candidate))\n        {\n            output=new Guid(candidate);\n            isValid = true;\n        }\n    }\n\n    return isValid;\n}	0
7534300	7531581	SSIS: C# Script task: How to change a SQL connection string based on server environment that the dtsx is running on?	Dts.Variables["System::MachineName"].Value.ToString()	0
4830835	4830763	get current page from url	Path.GetFileName( Request.Url.AbsolutePath )	0
2280329	2280321	Is there a way in C# to replicate a '#ifndef _DEBUG' from C/C++?	#if DEBUG\n    Console.WriteLine("Debug version");\n#endif\n\n#if !DEBUG\n    Console.WriteLine("NOT Debug version");\n#endif	0
22826783	22826674	Split a String into array in Java and C#	String value = "StringA:StringB!StringC.StringD";\n        char[] charArray = value.toCharArray();\n        StringBuilder stringBuilder = new StringBuilder();\n\n        for (char out : charArray)\n        {\n            if (!Character.isLetterOrDigit(out))  // find special characters\n            {\n                stringBuilder.append(",").append(out).append(","); \n            }\n            else\n            {\n                stringBuilder.append(out);\n            }\n        }\n\n        String[] resultValue = stringBuilder.toString().split(",");\n        System.out.println(Arrays.toString(resultValue));	0
32150723	32150273	LINQ Inner Join - Return one object from anonymous which is combined from Both Tables	public IEnumerable<Product> GetProductList()\n{\n\n    var query = from p in db.Products\n                 join la in db.LanguageAttribute on p.ID equals la.ID\n                 where l.LanguageID == "en-US"\n                 select new { Product = p, Description = la.Description };\n    var result = query.ToList();\n\n    result.ForEach(i => i.Product.Description = i.Description);\n\n    List<Product> products = result.Select(i => i.Product).ToList();\n\n    return products;\n}	0
1000637	1000588	How do I focus a modal WPF Window when the main application window is clicked	var uploadWindow = new UploadWindow();\nuploadWindow.Owner = this;\nuploadWindow.ShowDialog();	0
23250842	23250224	Windows Forms wait 5 seconds before displaying a message	//Your window Constructor\npublic MyWindow()\n{\n    InitializeComponent();\n\n    this.Cursor = Cursors.WaitCursor; \n    this.Enabled = false;\n    WaitSomeTime();\n\n    //load stuff\n    .....\n}\n\npublic async void WaitSomeTime()\n{\n    await Task.Delay(5000);\n    this.Enabled = true;\n    this.Cursor = Cursors.Default; \n}	0
1576777	1576671	Setting datagridviewimagecolumn image layout	dataGridViewImageColumn.ImageLayout = DataGridViewImageCellLayout.Stretch;	0
906702	865052	Programatically generating assemblies from OWL files with ROWLEX	private NC3A.SI.Rowlex.AssemblyGenerator generator;\n\nprivate void RunAssemblyGeneration(XmlDocument ontologyFileInRdfXml)\n{\nthis.generator = new NC3A.SI.Rowlex.AssemblyGenerator();\nthis.generator.GenerateAsync(ontologyFileInRdfXml, "myAssemblyName", \n                                        null, this.OnGenerationFinished);\n}\n\nprivate void OnGenerationFinished(string errorMessage)\n{\nif (errorMessage == null)\n{\n// Success\n// Displaying warnings and saving result\nstring[] warnings = this.generator.Warnings;\nthis.generator.SaveResult(@"C:\myAssemblyName.dll");\n                // Important! One generator instance can be executed only once. \n    this.generator = null; \n    this.RejoiceOverSuccess();\n    }\nelse\n{\n    // Failure\n    this.MournOverFailure();\n    }\n\n    }	0
28879270	28878811	xpath expression to select href value from link	string _tmpUrl = documentUrl.DocumentNode.SelectNodes("//a[@class='cat']")[i].Attributes["href"].Value;	0
2433150	2430353	Is it possible to dynamically set a static string during *class* Initialisation?	public static string ConnectionString { get; private set; }\n\nstatic MyClass()\n{\n    ConnectionString = @"Data Source=" + myLibrary.common.GetExeDir() + @"\Database\db.sdf;";\n}	0
12741559	12483482	Monitor if a popup window is visible in a Coded UI Test for a win32 application	if (MyPopupWindow.Exists)\n    Mouse.Click(MyPopupWindow.dxDialogOkButton());	0
21857974	21856267	How to detect a special symbol in the TextBox?	ToolTip tt = new ToolTip();\nChar lastChar = ' ';\n\nvoid textBox1_MouseMove(object sender, MouseEventArgs e) {\n  char c = textBox1.GetCharFromPosition(e.Location);\n  if (c.Equals('*')) {\n    if (!c.Equals(lastChar)) {\n      lastChar = c;\n      tt.Show("This is something special", this.textBox1,\n              new Point(e.Location.X + 20, e.Location.Y + 20),\n              2000);\n    }\n  } else {\n    lastChar = ' ';\n    tt.Hide(this.textBox1);\n  }\n}	0
9128250	9127316	Need help regarding RSS Feed and wordpress	var reader = XmlReader.Create("http://bbaremancareers.wordpress.com/feed/");\n        var feed = SyndicationFeed.Load<SyndicationFeed>(reader);\n\n        Console.WriteLine("Latest posts from " + feed.Title.Text);\n\n        foreach (var item in feed.Items)\n        {\n            string strTitle = item.Title.Text;\n            string strContent = item.Summary.Text;\n            DateTime publishDate = item.PublishDate.DateTime;\n            string linkUrl = item.Links[0].Uri.ToString();\n        }	0
9404678	9404523	Set property value using property name	List<KeyValuePair<string, object>> _lObjects = GetObjectsList(); \nvar class1 = new Class1();\nvar class1Type = typeof(class1); \nforeach(KeyValuePair<string, object> _pair in _lObjects)\n  {   \n       //class have this static property name stored in _pair.Key     \n       class1Type.GetProperty(_pair.Key).SetValue(class1, _pair.Value); \n  }	0
18594427	18593004	Convert Json object to iEnumerable	FacebookClient fb = new FacebookClient(App.AccessToken);\n\n   dynamic postsTaskResult = await fb.GetTaskAsync("/mypage?fields=posts");\n\n    foreach (var post in postsTaskResult.posts.data)//checking for nulls here would be safer\n    {\n        //var post = item; //JsonObject will do fine. I have not changed it\n        var name = ((IDictionary<String, object>)post).ContainsKey("name") ? (string)post.name : ""; //ContainsKey check optional\n        //var name = (string)post.name; //this would do fine\n        FacebookPostsData.Posts.Add(\n            new Posts { \n                Name = name, \n                id = (string)post["id"], \n                Message = (string)post["message"], \n                PictureUri = new Uri(string.Format("{0}", (string)post["picture"])) });\n    }	0
17651128	17648939	How does a dictionary get passed byref to a Task	Dictionary<string, WSResponse> responseDictionary = ...;\n\n  Task newTask = Task.Factory.StartNew(() =>\n  {\n       WSResponse response = Query.GetListFor(localID);                    \n       responseDictionary.Add(localID, response);\n  });	0
31139755	31139571	I want substring from set of string after a pattern exist in c#	var strings=new[]{"m60_CLDdet2_LOSS2CLF_060520469434_R0RKE_52_GU","m60_CLDdet2_LOSS2CLF_060520469434_R10KE_52_TCRER","m60_CLDdet2_LOSS2CLF_060520469434_R0HKE_52_NT"};\n\nstring[] starts = { "R0RKE", "R10KE", "R0HKE" };\nvar result = strings\n  .Select(str => new { str, match = starts.FirstOrDefault(s => str.IndexOf("_" + s) >= 0)})\n  .Where(x => x.match != null)\n  .Select(x => x.str.Substring(x.str.IndexOf(x.match)));\n\nConsole.Write(String.Join(",", result)); // R0RKE_52_GU,R10KE_52_TCRER,R0HKE_52_NT	0
14991417	14987512	Remove strange characters from cookie (VB)	Label1.Text = Uri.UnescapeDataString(Request.Cookies("Cookie").Value)	0
1743091	1743059	Mail doesn't get send untill I terminate my application - System.Mail.Net	smtp.Send(mail);	0
28029110	28021542	Dynamic Combobox Form keeps on setting all comboboxes when trying to set a single one	cbAttributes.DataSource = new List<string>(confFileSettings);	0
12976406	12976278	Where to put txt file	SpecialFolder.LocalApplicationData	0
3542766	3542241	Linq to XML join	var query = from f in fRoot.Elements("Company")\n    from r in rRoot.Elements("Bills")\n    where ((string)f.Element("category").Value).Split(',').Contains((string)r.Element("category").Value )\n    orderby(string)f.Element("name").Value\n    select new new{...};	0
29709647	29708776	Joining multiple ICollections in C# to retrieve data from other classes	from o in context.Orders\nfrom p in o.Products\nselect new CartGridItem\n{\n    Product = p,\n    CategoryNames = p.Categories.Select(c => c.Name),\n}	0
26503037	26502722	Show entire table from mysql in C# (WPF)	StringBuilder vypis = ""; \nwhile (rdr.Read())\n{\n vypis.AppendLine(string.Format("{0} - {1} - {2} - {3}",\n       rdr.GetInt32(0),\n       rdr.GetString(1),\n       rdr.GetString(2),\n       rdr.GetString(3));    \n}\nvypisBlock.Text = vypis.ToString();	0
8166134	8165903	How to suppress List item based on the input value in C#?	List<CustomerInfo>  inList = new List<CustomerInfo> ();\nList<CustomerInfo>  outList = new List<CustomerInfo> ();\n\nstring[] properties = string.split(',');\nforeach(var info in inList)\n{\n    CustomerInfo filteredInfo = new CustomerInfo();\n    foreach(var property in properties)\n    {  \n       var pi = typeof(CustomerInfo).GetProperty(property);\n       pi.SetValue(filteredInfo, pi.GetValue(info, null), null);\n    }\n    outList.Add(filteredInfo);\n}\n\nreturn outList;	0
32741835	32741656	Choose ComboBox value and convert it into a int	int N = Int32.Parse(this.comboBox1.SelectedItem.ToString());	0
12107200	12106657	Check if opened window has been closed	private void ShowChildWindow()\n{\n    Window childWindow = new ChildWindow();\n    childWindow.Closed += ChildWindowClosed;\n    childWindow.Show();\n}\n\nprivate void ChildWindowClosed(object sender, EventArgs e)\n{\n    ((Window)sender).Closed -= ChildWindowClosed;\n    RepeaterRefresh();\n}	0
26121674	26121481	Linq join that accepts null values	var items = from v in work.GetRepo<VW_V>().Query\n\n            join k in work.GetRepo<K>().Query \n              on v.Loc_Id equals k.Id\n\n            join p in work.GetRepo<P>().Query \n              on v.Peer_Id equals p.Id\n            into pJoinData \n            from pJoinRecord in pJoinData.DefaultIfEmpty( )\n\n            join tt in work.GetRepo<TT>().Query \n              on v.Item_Id equals tt.Id\n\n            select (new MyModel\n            {\n                Id = v.Id,\n                Location = k != null ? k.Name : string.Empty,\n                ItemName = tt.Name,\n                Peer = pJoinRecord != null ? pJoinRecord.Name : string.Empty,\n            });	0
1771903	1771845	Iterating through a list of lists?	foreach(var i in BunchOfItems.SelectMany(k => k.Items)) {}	0
15755572	15755420	401 when attempting to Tweet with Linq to Twitter	new TwitterContext(auth)	0
15252872	15252768	storing matrix in a c# dictionary	Tuple<int,int>	0
16376757	16376681	Check if label is more than a specific value	public class Clock\n{  \n\n    private int _hour;\n\n    public void Increment()\n    {\n       if (_hour > 23)\n          _hour = 0;\n       else\n          _hour++;\n\n       // Raise event\n    }\n\n    public event EventHandler HourChanged;\n\n    public int Hour { get { return _hour; } }\n}	0
12515817	12515682	Improving a Linq statement to remove the need for a foreach loop	var item = _ctx.JournalSet\n         .Where(x => x.EntryType == entityType)\n         .OrderBy(x => x.UpdatedTime_UTC)\n         .GroupBy(x => x.EntryId)\n         .Where(y => y.Last().Operation != "deleted");	0
17250582	17250529	Deserializing complex json object with dictionary	public class MyClass\n{\n    public string staticKey1 { get; set; }\n    public string staticKey2 { get; set; }\n    public IEnumerable<IDictionary<string, string>> results { get; set; }\n}	0
6997845	6997690	Change zedgraph pane background color	myChart.GraphPane.Chart.Fill.Color = System.Drawing.Color.Black;	0
29925462	29924941	How do I find all the distinct keys of json records in c#?	private static void GetKeys(JObject obj, List<string> keys)\n    {\n        var result = obj.Descendants()\n            .Where(f => f is JProperty) //.Where(f => f is JProperty) \n            .Select(f => f as JProperty)// and .Select(f => f as JProperty) can be replaced with .OfType<JProperty>()\n            .Select(f=>f.Path)\n            .Where(f=> !keys.Contains(f));\n        keys.AddRange(result);\n    }\n\n    static void Main(string[] args)\n    {         \n        IEnumerable<string> txts = @"{'id':'123', 'name':'hello, world',     'department':[{'name':'dept1', 'deptID':'123'}]}\n{'id':'456324', 'department':[{'name':'dept2', 'deptID':'456'}]}".Split("\r\n".ToArray(),StringSplitOptions.RemoveEmptyEntries);\n        List<string> keys = new List<string>();\n        foreach (var item in txts)\n        {\n            var obj = JObject.Parse(item);\n            GetKeys(obj, keys);\n        }	0
21797942	21797874	How to check for json data exist?	if (apiData != null)\n  if (apiData.search_api.result[0] != null)\n  {\n      txt_Result1.Text = apiData.search_api.result[0].areaName[0].value.ToString();\n  }	0
15878389	15875390	Get text of a text box that was created at runtime	TextBox bt = new TextBox();\n        bt.Name = "population_textbox";\n        bt.Height = 20;\n        bt.SetValue(Grid.ColumnProperty, 1);\n        bt.SetValue(Grid.RowProperty, 0);\n        temp_grid.Children.Add(bt);\n        this.RegisterName(bt.Name, bt);\n\n\n        var tb = this.FindName("population_textbox") as TextBox;\n        Console.Write(tb.Text);	0
21341569	21321552	Callback from C# COM dll to Delphi app causes memory leak	ICOMCallbackContainer ICOMCallbackTestServer.CallbackContainer\n    {\n        get { return _callbackContainer; }\n        set { \n\n            if (_callbackContainer != null)\n            {\n                  Marshal.ReleaseComObject(_callbackContainer); // calls IUnknown.Release()\n                  _callbackContainer = null;\n            }\n\n            _callbackContainer = value;\n        }\n    }	0
4310948	4310791	Best way add a new column with sequential numbering in an existing data table	DataTable dtIncremented  = new DataTable(dt.TableName);\nDataColumn dc            = new DataColumn("Col1");\ndc.AutoIncrement         = true;\ndc.AutoIncrementSeed     = 1;\ndc.AutoIncrementStep     = 1;\ndc.DataType              = typeof(Int32);    \ndtIncremented.Columns.Add(dc);\n\ndtIncremented.BeginLoadData();\n\nDataTableReader dtReader = new DataTableReader(dt);\ndtIncremented.Load(dtReader);\n\ndtIncremented.EndLoadData();	0
2785082	2783528	How do actually castings work at the CLR level?	try\n{\n    object x = 123;\n    object y = (string)x;\n}\ncatch(InvalidCastException ex)\n{ ... }	0
19011927	19010082	Fluent NHibernate, right way to implement ISQLExceptionConverter	public class SqlServerExceptionConverter : ISQLExceptionConverter\n{\n    public Exception Convert(AdoExceptionContextInfo adoExceptionContextInfo)\n    {\n        var sqlException = adoExceptionContextInfo.SqlException as SqlException;\n        if (sqlException != null)\n        {\n            // 2601 is unique key, 2627 is unique index; same thing: \n            // http://blog.sqlauthority.com/2007/04/26/sql-server-difference-between-unique-index-vs-unique-constraint/\n            if (sqlException.Number == 2601 || sqlException.Number == 2627)\n            {\n                return new UniqueKeyException(sqlException.Message, sqlException);\n            }\n        }\n        return adoExceptionContextInfo.SqlException;\n    }\n}	0
32756173	32755907	check whether there is a focus on the elements	//Logical focus\n var focusedControl = FocusManager.GetFocusedElement(this);\n\n//KeyBoard focus\n var focusedControl =  Keyboard.FocusedElement;\n\n// dummy logic to close the window when all the three textboxes are not focused.\nList<TextBox> items=new List<TextBox>();\nitems.Add(TextBoxExtendedSearchName);\nitems.Add(TextBoxExtendedSearchNomenclature);\nitems.Add(TextBoxExtendedSearchSpecialist);\nif(!items.Any(o=>o==focusedControl))\n {\n    window.Close();\n }	0
4412668	4412384	Acessing object like by Index, but by name in C#	public class Father\n{\n    public int Id { get; set; }\n    public string Name { get; set; }\n    public Children Children { get; set; }\n\n    public Father()\n    {\n    }\n}\npublic class Children : List<Child>\n{\n    public Child this[string name]\n    {\n        get\n        {\n            return this.FirstOrDefault(tTemp => tTemp.Name == name);\n        }\n    }\n}\npublic class Child\n{\n    public int Id { get; set; }\n    public string Name { get; set; }\n\n    public Child()\n    {\n    }\n}	0
10753976	10753759	connect to website using a free proxy server programmatically	string targetUrl = "http://www.google.com";\nstring proxyUrlFormat = "http://zend2.com/bro.php?u={0}&b=12&f=norefer";\nstring actualUrl = string.Format(proxyUrlFormat, HttpUtility.UrlEncode(targetUrl));\n\n// Do something with the proxy-ed url\nHttpWebRequest req = (HttpWebRequest)WebRequest.Create(new Uri(actualUrl));\nHttpWebResponse resp = req.GetResponse();\n\nstring content = null;\nusing(StreamReader sr = new StreamReader(resp.GetResponseStream()))\n{\n    content = sr.ReadToEnd();\n}\n\nConsole.WriteLine(content);	0
30455085	30454747	How to set a column name in SQL query as parameter?	string sqlCommandStatement =  \n   string.Format("("UPDATE users SET {0}=@somedata, {1}=@somedata" ,column1, column2);	0
32406910	32405822	Is it a good idea to implement a C# event with a weak reference under the hood?	() => LaunchMissiles()	0
8816383	8816002	How can I recursively search properties in C# only if those properties inherit from some base class?	static IEnumerable<PropertyInfo> FindProperties(object objectTree, Type targetType)\n{\n    if (targetType.IsAssignableFrom(objectTree.GetType()))\n    {\n        var properties = objectTree.GetType().GetProperties();\n        foreach (var property in properties)\n        {\n            yield return property;\n\n            if (targetType.IsAssignableFrom(property.PropertyType))\n            {\n                object instance = property.GetValue(objectTree, null);\n                foreach (var subproperty in FindProperties(instance, targetType))\n                {\n                    yield return subproperty;\n                }\n            }\n        }\n    }\n}	0
16028214	16028133	Remove items from ListBox when DataSource is set	private void radioButton1_CheckedChanged(object sender, EventArgs e)\n{\n    var bdHashSet = new HashSet<string>(bd);\n\n    listBox1.Datasource = null;\n    listBox1.Datasource =  bdHashSet.Where(s => (s.StartsWith("414") || s.StartsWith("424"))).ToList();\n}	0
9531777	9531691	How do I make the value of an XElement be wrapped in ![CDATA[***]]?	xElement.Element(elementName).ReplaceNodes(new XCData(value));	0
7590491	7590446	Set File Permissions in C#	FileAttributes attributes = File.GetAttributes(path);\n\n        if ((attributes & FileAttributes.Hidden) == FileAttributes.Hidden)\n        {\n            // Show the file.\n            attributes = RemoveAttribute(attributes, FileAttributes.Hidden);\n            File.SetAttributes(path, attributes);\n            Console.WriteLine("The {0} file is no longer hidden.", path);\n        } \n        else \n        {\n            // Hide the file.\n            File.SetAttributes(path, File.GetAttributes(path) | FileAttributes.Hidden);\n            Console.WriteLine("The {0} file is now hidden.", path);\n        }	0
25024	25007	Conditional formatting -- percentage to color conversion	function setColor(p){\n    var red = p<50 ? 255 : Math.round(256 - (p-50)*5.12);\n    var green = p>50 ? 255 : Math.round((p)*5.12);\n    return "rgb(" + red + "," + green + ",0)";\n}	0
11208644	11208591	Correct use of Object Initializer	DbRecordData tmp = new DbRecordData(2);\ntmp.Add("VehMarkName", SqlDbType.NVarChar, vehMarkName);\ntmp.Add("refVehTypeId", SqlDbType.Int, refVehTypeId);\nDbRecordData dbRecord = tmp;	0
9199952	9199895	Remove UtcOffset from DateTime.Now	DateTime.UtcNow.ToString("o");\n// "2012-02-08T19:19:38.5767158Z"\n\nnew DateTime(DateTime.UtcNow.Ticks).ToString("o");\n// "2012-02-08T19:19:38.5767158"\n\nnew DateTime(DateTime.Now.Ticks).ToString("o");\n// "2012-02-08T14:19:38.5767158"	0
12390546	12378998	How to use QuickFix to read secdef.dat file	using System;\nusing System.IO;\nusing QuickFix;\nusing QuickFix.DataDictionary;\n\nnamespace TestQuickFix\n{\n    class Program\n    {\n        private const int MAX_LINES = 10;\n\n        static void Main(string[] args)\n        {\n            DataDictionary dd = new QuickFix.DataDictionary.DataDictionary("fix\\FIX50SP2.xml");   \n            StreamReader file = new StreamReader(@"C:\secdef.dat");\n            int count = 0; string line;\n            while (((line = file.ReadLine()) != null && count++ < MAX_LINES))\n            {\n                QuickFix.FIX50.SecurityDefinition secDef = new QuickFix.FIX50.SecurityDefinition();\n                secDef.FromString(line, false, dd, dd);\n                Console.WriteLine(secDef.SecurityDesc);\n            }\n            file.Close();\n        }\n    }\n}	0
6762029	6761891	EF Transactions c# MySQL connector	public void EditUser(user user, Roles role)\n{\n    using (TestEntities entities = new TestEntities())\n    {\n        entities.Connection.Open();\n        using (DbTransaction trans = entities.Connection.BeginTransaction())\n        {\n          InnerEditUser(entities, trans);\n          InnerThat(entities, trans);\n          InnerThis(entities,trans);\n          entities.SaveChanges();\n          trans.Commit();\n        }\n    }\n }	0
4590398	4590304	How to make Singleton a Lazy instantiated class?	public sealed class Singleton\n{\n    Singleton()\n    {\n    }\n\n    public static Singleton Instance\n    {\n        get\n        {\n            return Nested.instance;\n        }\n    }\n\n    class Nested\n    {\n        // Explicit static constructor to tell C# compiler\n        // not to mark type as beforefieldinit\n        static Nested()\n        {\n        }\n\n        internal static readonly Singleton instance = new Singleton();\n    }\n}	0
6359964	6359868	SharpZipLib - adding folders/directories to a zip archive	ZipFile.AddDirectory	0
6650046	6650029	Supressing Windows Alerts Programmatically	Zone.Identifier	0
9851	9805	Calculate DateTime Weeks into Rows	public int GetWeekRows(int year, int month)\n{\n    DateTime firstDayOfMonth = new DateTime(year, month, 1);\n    DateTime lastDayOfMonth = new DateTime(year, month, 1).AddMonths(1).AddDays(-1);\n    System.Globalization.Calendar calendar = System.Threading.Thread.CurrentThread.CurrentCulture.Calendar;\n    int lastWeek = calendar.GetWeekOfYear(lastDayOfMonth, System.Globalization.CalendarWeekRule.FirstFourDayWeek, DayOfWeek.Monday);\n    int firstWeek = calendar.GetWeekOfYear(firstDayOfMonth, System.Globalization.CalendarWeekRule.FirstFourDayWeek, DayOfWeek.Monday);\n    return lastWeek - firstWeek + 1;\n}	0
697624	697541	How do I use the MS DIA SDK from C#?	midl /I "%VSINSTALLDIR%\DIA SDK\include" dia2.idl /tlb dia2.tlb\ntlbimp dia2.tlb	0
4215278	4215230	Extract unsigned values from certain bits in C# ushort	int GetFromBits(ushort bits, int offset)\n{\n return (bits >> (offset - 1)) & 0xF;\n}	0
27819565	27819173	How to "Receive a Fax Now" using FAXCOMEXLIB?	public void ReceiveFaxNow()\n    {\n        try\n        {\n            var device = nws.faxSrv.GetDevices().GetEnumerator();\n            device.MoveNext();\n            FaxDevice dev = (FaxDevice)device.Current;\n\n            if (dev != null)\n            {\n                dev.AnswerCall();\n            }\n        }\n        catch (Exception e)\n        {\n\n        }\n    }	0
13480597	13480039	TableQuery<T> from Azure TableStorage that filters on PartitionKey	public List<T> GetEntities<T>(string partitionKey, T entity) where T : TableEntity, new ()	0
26812899	13097112	How to get syntax highlighting of controllers and actions on HtmlHelper extension method?	public void WithLink([AspMvcAction] string action, [AspMvcController] string controller)	0
55511	50251	Dynamic linq:Creating an extension method that produces JSON result	public static class JSonify\n{\n    public static string GetJsonTable<T>(\n    this IQueryable<T> query, int pageNumber, int pageSize, string IDColumnName, string[] columnNames)\n    {\n    string select = string.Format("new ({0} as ID, \"CELLSTART\" as CELLSTART, {1}, \"CELLEND\" as CELLEND)", IDColumnName, string.Join(",", columnNames));\n    var items = new\n    {\n    page = pageNumber,\n    total = query.Count(),\n    rows = query.Select(select).Skip((pageNumber - 1) * pageSize).Take(pageSize)\n    };\n    string json = JavaScriptConvert.SerializeObject(items);\n    json = json.Replace("\"CELLSTART\":\"CELLSTART\",", "\"cell\":[");\n    json = json.Replace(",\"CELLEND\":\"CELLEND\"", "]");\n    foreach (string column in columnNames)\n    {\n    json = json.Replace("\"" + column + "\":", "");\n    }\n    return json;\n    }\n}	0
15107231	15106630	Click Event for Dynamically Generate Linkbutton	for (int i = 0; i < 4; i++)\n{\n   LinkButton lbtn = new LinkButton();\n   lbtn.OnClientClick = "document.getElementById('" + txtuname.ClientID + "').value = '"+txtuname.Text + i+"'; return false;";\n   lbtn.Text = txtuname.Text + i;\n   phlinks.Controls.Add(lbtn);\n   phlinks.Controls.Add(new LiteralControl("   "));\n}	0
12602914	12602567	C# make panel visible for specific time after mouse move over other panel	System.Windows.Forms.Timer myTimer = new System.Windows.Forms.Timer();\n\n// form constructor\npublic myForm() \n{\n    myTimer.Interval = 1000;    // or whatever you need it to be\n    myTimer.Tick += new EventHandler(TimerEventProcessor);   \n}\n\nprivate void myMouseHover(object sender, EventArgs e) \n{\n     this.prevPanel.Visible = true;\n     this.nextPanel.Visible = true;\n     myTimer.Start();\n }\n\nprivate void TimerEventProcessor(Object myObject, EventArgs myEventArgs) {\n     myTimer.Stop();\n     this.prevPanel.Visible = false;\n     this.nextPanel.Visible = false;\n}	0
4690748	3257588	In C# asp.net is it possible to send back a valid web page half way through a method?	protected void Page_Load(object sender, EventArgs e)\n{    \n if ((string)Session["OK"] != "OK")  \n   {        \n       // the session has timed out - take them back to the start page    \n       ForceBackToStartPage();  \n       return; \n   }  \n\n...rest of processing\n\n}	0
14749412	14748970	C# change formatting for a single DateTime	PrintBothDate()	0
9298954	9298515	Keyboard on the screen in WinForms	/// <summary>\n    /// Test to show launching on screen board (osk.exe).\n    /// </summary>\n    /// <param name="sender"></param>\n    /// <param name="e"></param>\n    private void textBox1_Click(object sender, EventArgs e)\n    {\n        try\n        {\n            Process.Start(@"c:\Temp\OSK.exe");\n        }\n        catch (Exception error)\n        {\n            string err = error.ToString();\n        }\n    }	0
29242152	29238933	How to open windows phone market page of my app programmaticaly in Windows Phone 8.1?	Launcher.LaunchUriAsync(new Uri("ms-windows-store:navigate?appid=[your app ID]"));	0
19072165	19071652	how to prevent going back to previous page	protected override void OnNavigatedTo(NavigationEventArgs e)\n{\n    while (NavigationService.RemoveBackEntry() != null);\n}	0
11788824	11788410	Validation in MVVM using attributes on properties	[Required(ErrorMessage = "Title is required.")]	0
31279341	31275880	Group 64 picture boxes into picturebox array	private PictureBox[] pictureBoxArray = new PictureBox[64]; //Initialize array to group picture boxes into picture box array\n\nprivate void Main_Load(object sender, EventArgs e)\n    {\n        ConvertGuiPBtoGuiPbArray(ref pictureBoxArray);\n    }\n\npublic void ConvertGuiPBtoGuiPbArray(ref PictureBox[] pictureBoxArray)\n{\n        int i = 0;\n        string NameofPictureBox;\n        string PictureBoxNumber;\n\n        foreach (var item in groupBox_DataLayer.Controls)\n        {\n            if (item is PictureBox)\n            {\n                NameofPictureBox = ((PictureBox)item).Name;\n                PictureBoxNumber = Regex.Match(NameofPictureBox, @"\d+").Value; // \d+ is regex for integers only\n                i = Int32.Parse(PictureBoxNumber);  //Convert only number string to int\n                i = i - 1;  //bcs of index of array starts from 0-63, not 1-64\n                pictureBoxArray[i] = (PictureBox)item; //put PictureBox object in desired position\n            }\n\n        }\n}	0
21464418	21464162	Show content of tables in some textboxes	SqlConnection con = new SqlConnection("Data Source=127.0.0.1;Initial \nCatalog=jadid;Integrated Security=True"); \n\nSqlCommand com_sel = new SqlCommand(); \n\nDataSet ds = new DataSet();   \nSqlDataAdapter adap = new\n\nSqlDataAdapter(com_sel);  \n\ncom_sel.CommandText = "select * from t2 where id=1";  //\n\ncom_sel.CommandType = CommandType.StoredProcedure;\ncom_sel.Connection = con; \ncom_sel.Parameters.Add("@p1",textBox1.Text);\ncon.Open();\nds.Clear();\nadap.Fill(ds); \ncom_sel.ExecuteNonQuery();  \n\ndataGridView1.DataSource = ds.Tables[0];\n\nint i; //this way you display the data in the textbox \n//TextBox1 is your textbox name \n//lessthen:- less than sign not write\n\nfor(i=0;i lessthen ds.Tables[0].Rows.Count-1;i++) {\n\nTextBox1.Text=ds.Tables[0].Rows[i]["Column"].ToString(); \n}	0
20969474	20969094	Automapper map from inner property to destination class	Mapper.Reset();\n// from, to\nMapper.CreateMap<InnerValue, DestinationClass>();\nMapper.CreateMap<SourceClass, DestinationClass>()\n    .ConvertUsing(s => Mapper.Map<InnerValue, DestinationClass>(s.Inner));\n\nMapper.AssertConfigurationIsValid();\n\nvar source = new SourceClass() { Inner = new InnerValue() { InnerPropertyId = 123, StringValue = "somethinges" } };\n\nvar dest = Mapper.Map<SourceClass, DestinationClass>(source);	0
19342080	19340672	How to pass BitmapImage to ImageSource	public class Card\n{\n     // Try some other type, they all can be bind to Image.Source.\n     public BitmapImage image; \n}	0
16814424	16814012	C# string to SqlDateTime: how to set format for recognition?	string val = "23.12.1992 00:00:00";\n\n// Parse exactly from your input string to the native date format.\nDateTime dt = DateTime.ParseExact(val, "dd.M.yyyy hh:mm:ss", null);\n\n// Part to SqlDateTime then            \nSystem.Data.SqlTypes.SqlDateTime dtSql = System.Data.SqlTypes.SqlDateTime.Parse(dt.ToString("yyyy/MM/dd"));	0
12898667	12897001	Log4net: configuration xml file and text log file location at runtime	log4net.Config.XmlConfigurator.m_repositoryName2ConfigAndWatchHandler["log4net-default-repository"]	0
33627036	33626450	self join Lambda query in Entity Framework	dt.FishEventScheduleVaccination\n    .Join(dt.FishEventSchedule,\n          vaccination => vaccination.ScheduleId,\n          schedule => schedule.ScheduleId,\n          (vaccination, schedule) => new { vaccination, schedule })\n    .Where(w => w.schedule.Start > DateTime.Now)\n    .AsEnumerable()\n    .Select(q => { q.vaccination.FishEventSchedule = q.schedule; return q.vaccination; })\n    .ToList();	0
10465428	10465300	Best way to get links from strings that contain them	(mywebsite.com/(.+?)\d{9})	0
856716	856663	1 or more bytes truncation with GZip round trip	s.Close();\nreturn output.ToArray();	0
27216350	27215688	Unity: Make camera only follow the player in x-direction	void Update () {\n    transform.Translate(Vector3.right * Time.deltaTime * movementSpeed);\n}	0
9316409	9302861	How to navigate to cs file that derives from custom ApplicationPage (with xaml)	InitializeComponent();	0
11301619	11301494	Loop for every key?	foreach (Keys k in Keyboard.GetState(PlayerIndex.One).GetPressedKeys()) {   \n    switch (k) {\n        case Keys.F11:\n            if (rndKey == 11) { rightbutton(); } else { wrongbutton(); }\n            break;\n        case Keys.F12:\n            if (rndKey == 12) { rightbutton(); } else { wrongbutton(); }\n            break;\n        default:\n            wrongbutton();\n            break;\n    }\n}	0
28505837	28393714	Adding role to a user	webpages_UsersInRoles s = new webpages_UsersInRoles();\n  var userid = WebSecurity.GetUserId(model.UserName);\n  s.RoleId = roles;\n  s.UserId = userid;\n  db2.webpages_UsersInRoles.Add(s);\n  db2.SaveChanges();	0
28588625	28588546	How to write a generic extension method which wraps object in an enumerable?	internal static class ObjectExtensions\n{\n   public static IEnumerable<T> Yield<T>(this T item)\n   {\n        yield return item;\n   }\n}	0
2697280	2697253	Using Linq to group a list of objects into a new grouped list of list of objects	var groupedCustomerList = userList\n    .GroupBy(u => u.GroupID)\n    .Select(grp => grp.ToList())\n    .ToList();	0
19000412	19000352	How to remove " [ ] \ from string	obj.str = obj.str.Replace("[","").Replace("]","").Replace("\\","").Replace("\"", "");	0
13500773	13500659	Select by Lambda Expression And Check Null Value	co.Reviews.Count()	0
7279575	7279536	How can define multiple KEY in EntityFrameWorkClass C#	[Table("Table_UserImages")]\npublic class UserImage\n{\n    [Key, Column("UserID", Order=0)]\n    public Guid? UserID { get; set; }\n    [Key, Column("ImageID", Order=1)]\n    public int? ImageID { get; set; }  \n}	0
12791901	12791181	Cant cast custom control	public class RibbonTab : Component, IRibbonElement, IContainsRibbonComponents	0
11541573	11541023	Translating data points to pixel coordinates for drawing	p[i].X = (DrawingArea.Width/2F) * (1 + (points[i].X / _voltageRange)); \n   p[i].Y = (DrawingArea.Height/2F) * (1 - (points[i].Y * (float)Math.Pow(_currentRange, -1)));	0
28615752	28565777	Angularjs $http post doesnt binding with asp.net web api server model	public IHttpActionResult Post([FromBody] jObject model){..}	0
2656302	2656279	Converting SQL to LINQ to XML	using (DbDataReader rdr = cmd.ExecuteReader()) {\n\n\n    from c in rdr.Cast<DbDataRecord>() \n    select new XElement("event",\n        new XAttribute("start", c["start"]),\n        new XAttribute("end",c["eend"]),\n        new XAttribute("title",c["title"]),\n        new XAttribute("Color",c["Color"]),\n        new XAttribute("link",c["link"])));\n\n}	0
28784666	28783916	Combining two Lists of an Object into one	var ids = studentWithAge.Select(s => s.Id)\n    .Union(studentWithSexAndComplexion.Select(s => s.Id));\nvar query =\n    from id in ids\n    from sa in studentWithAge\n                    .Where(sa => sa.Id == id)\n                    .DefaultIfEmpty(new ObjectItem { Id = id })\n    from ssc in studentWithSexAndComplexion\n                    .Where(ssc => ssc.Id == id)\n                    .DefaultIfEmpty(new ObjectItem { Id = id })\n    select new ObjectItem\n    {\n        Id = id,\n        Name = sa.Name ?? ssc.Name,\n        Sex = ssc.Sex,\n        Age = sa.Age,\n        Complexion = ssc.Complexion,\n    };	0
3919816	3919804	How do I convert an int to two bytes in C#?	byte b0 = (byte)i,\n     b1 = (byte)(i>>8);	0
3225325	3225298	What is a way to Parse this File in C#, Where I have a CRLF Inside a Field	var lines = content.Split(...);\nstring header[] = lines[0].Split(...);\nint numberOfColumns = header.Length;\n\nvar parsedLines = new List<string[]>();\nfor (int i = 1; i < lines.Length; i++) {\n   var line = lines[i];\n\n   while ((fields = line.Split(...)).Length < numberOfColumns) {\n     // combine with next, and increment i\n     line += lines[++i];\n   }\n\n   parsedLines.Add(fields);\n}	0
8258116	8258010	Find and Find Next	if (frm1TB.Text.Length >= frm1TB.Text.SelectionStart + frm1TB.Text.SelectionLength)\n{\n    int foundAt = frm1TB.Text.IndexOf(\n        searchText.Text,\n        frm1TB.Text.SelectionStart + frm1TB.Text.SelectionLength);\n}	0
5958154	5767605	Looping through Regex Matches	class Program\n{\n    static void Main(string[] args)\n    {\n        string sourceString = @"<box><3>\n<table><1>\n<chair><8>";\n        Regex ItemRegex = new Regex(@"<(?<item>\w+?)><(?<count>\d+?)>", RegexOptions.Compiled);\n        foreach (Match ItemMatch in ItemRegex.Matches(sourceString))\n        {\n            Console.WriteLine(ItemMatch);\n        }\n\n        Console.ReadLine();\n    }\n}	0
31710153	31708738	Visual Studio 2013 C# Add all images from imagelist to listview	PictureBox pb = default(PictureBox);\n        int x = 0, y = 3000;\n        foreach (Image img in imglist1.Images)\n        {\n            pb = new System.Windows.Forms.PictureBox();\n            pb.Image = img;\n            pb.Width = 1450;\n            pb.Height = 1450;\n            //x += 1000;\n            y -= 1000;\n            pb.Location = new System.Drawing.Point(x,y);\n\n            //pb.Location.X = x;\n            //pb.Location.Y = y;\n            this.Controls.Add(pb);\n        }	0
5564453	5562908	Assignment of a struct value to this keyword	struct MyStruct\n{\n    int a = 1;\n    int b = 2;\n    int c = 3;\n\n    public void Mutate()\n    {\n        a = 10;\n        b = 20;\n        c = 30;\n    }\n\n    public void Reset()\n    {\n        a = 1;\n        b = 2;\n        c = 3;\n    }\n\n    public void Reset2()\n    {\n        this = new MyStruct();\n    }\n\n    // The two Reset methods are equivilent...\n}	0
33226244	33226111	C# how can I accept a steam steam offer?	//at the top of the file\nusing SteamTrade.TradeOffer;\n\n//the later on in the file\nOffersession newSteamSession = new OfferSession('yourApiKey', 'steamweb');\n\nstring convertedStringtradeId = String.Empty;\nvar isAccepted = newSteamSession.Accept(tradeOfferId, convertedStringtradeId);\n\nif(isAccepted) \n{\n    //do more logic here if the offer was good\n    //you can use the convertedStringtradeId if you need something\n\n\n}else\n{\n  //what happens when things go wrong\n}	0
9478042	9477531	outlook sent mails	public partial class ThisAddIn\n{\n\nprivate void ThisAddIn_Startup(object sender, System.EventArgs e)\n{\n    this.Application.ItemSend += new Microsoft.Office.Interop.Outlook.ApplicationEvents_11_ItemSendEventHandler(ThisApplication_ItemSend);\n}\n\nprivate void ThisApplication_ItemSend(object item, bool cancel)\n{\n    Outlook.MailItem newEmail = item as MailItem;\n    if (newEmail != null)\n    {\n        foreach (var attachment in newEmail.Attachments)\n        {\n            attachment.SaveAsFile(@"C:\TestFileSave\" + attachment.FileName);\n        }\n    }\n}\n\n}	0
13167648	13167369	Windows user impersonation in PHP?	fastcgi.impersonate = 1	0
23708893	23708740	C# grid view files doesnt open	// code to upload files\nHttpFileCollection fileCollection = Request.Files;\nif (fileCollection.Count != 0)\n{\n    string filename = string.Empty;\n    for (int i = 0; i < fileCollection.Count; i++)\n    {\n        HttpPostedFile file = fileCollection[i];\n        filename = Path.GetFileName(file.FileName);\n        if (file.ContentLength > 0)\n        {\n            string strFilePath = "~/Uploads/";\n            System.IO.DirectoryInfo DI = new System.IO.DirectoryInfo(MapPath(strFilePath));\n            if (!DI.Exists)\n            {\n                System.IO.Directory.CreateDirectory(MapPath(strFilePath));\n            }\n            strFilePath = strFilePath + filename;\n            System.IO.FileInfo FI = new System.IO.FileInfo(MapPath(strFilePath));\n            if (!FI.Exists)\n            {\n                file.SaveAs(Server.MapPath(strFilePath));\n            }\n\n            // save the filepath variable to your database\n        }\n    }\n}	0
21447457	21431540	Reading emails from gmail by subject	public static byte[] GetUserImage(string image_name)\n    {\n        Pop3Client c = new Pop3Client();\n\n        c.Connect("pop.gmail.com", 995, true);\n        c.Authenticate("your gmail", "password");\n        for (int i = c.GetMessageCount(); i >= 1; i--)\n        {\n            OpenPop.Mime.Message mess = c.GetMessage(i);\n            if (mess.Headers.Subject.Equals(image_name))\n            {\n               return mess.MessagePart.MessageParts[1].Body;//this to get attachment\n                                            **OR:**\n               return Encoding.ASCII.GetString(mess.MessagePart.Body);//this to get text\n            }\n\n        }\n        return null ;\n    }	0
33549255	33549217	Failing SQL insert	myCommand3.CommandText = "INSERT INTO Dbo.Values ([Portfolio Name],[Date],[Daily Value],[Daily Percent]) VALUES ('Ascentric',@SQLTime,2000,0.01)";	0
32287899	32287839	How to create a list<string> from simple xml file?	var list = XDocument.Load(filename)\n           .Descendants("Result")\n           .Select(x => (string)x)\n           .ToList();	0
9466703	9466609	DateTime Arithmetic Query Using EntityFramework	Linq-to-entities	0
17051747	17051422	Windows application that remembers user input	Properties.Settings.Default.SomeProp	0
12244102	12038905	Using DrawUserPrimitive and transforming that with some matrices	internal void HandleDraw(GameTime gameTime)\n{\n    Draw(gameTime);\n\n    if (Children.Count > 0)\n    {\n        // draw children\n        foreach (Control child in Children.Values.OfType<Control>())\n        {\n            if (child.Visible)\n            {\n                Engine.CurrentTransformation.Push(Matrix.Multiply(\n                    child.Transformation,\n                    Engine.CurrentTransformation.Peek()\n                ));\n\n                child.HandleDraw(gameTime);\n\n                Engine.CurrentTransformation.Pop();\n            }\n        }\n    }\n}	0
7636653	7636605	Extracting and copying files to local folder from a zip archive stored in a blob storage	using (ZipFile zip = ZipFile.Read(InputStream))\n  {\n    ZipEntry entry = zip["NameOfEntryInArchive.doc"];\n    entry.Extract();  // create filesystem file here. \n  }	0
10745001	10744981	Exclude numbers starting with a certain three digits in C#	int num;\ndo {\n   num = SSN.Next(100000000, 999999999);\n} while (num >= 666000000 && num < 667000000);	0
14878103	14878046	Is there a simpler way to preform projection on a ListItemCollection?	foreach (ListItem item in listbox.Items)\n{\n    item.Selected = condition(item);\n}	0
14958433	14956922	Multiple linq query of order by to single one	var searchByMapping = new Dictionary<SearchByEnum,Func<SomeDTO, object>>();\nsearchByMapping.Add(SearchByEnum.Prop1, x => x.Prop1);\nsearchByMapping.Add(SearchByEnum.Prop2, x => x.Prop2);\nsearchByMapping.Add(SearchByEnum.Prop3, x => x.Prop3);\n\ncoll = coll.OrderBy(searchByMapping[searchByEnumParam]).ToList();	0
100066	100045	Regular expressions in C# for file name validation	if (proposedFilename.IndexOfAny(System.IO.Path.GetInvalidFileNameChars()) != -1)\n{\n  MessageBox.Show("The filename is invalid");\n  return;\n}	0
12788844	12781894	How to map IDictionary<Enum, bool>?	// IDictionary<string, bool>\nHasMany(x => x.Dictionary1).AsMap<string>("keyColumn").Element("Enabled");\n\n// IDictionary<SomeEnum, bool>  (Enum will be mapped as int)\nHasMany(x => x.Dictionary2).AsMap("SomeEnum").Element("Enabled");  \n\n// IDictionary<Entity, string>\nHasMany(x => x.Dictionary3).AsEntityMap().Element("valueColumn");	0
12992665	12963389	Adding clients to groups	public class Status : Hub, IDisconnect, IConnected\n{\n    public Task Disconnect()\n    {\n        return Clients.leave(Context.ConnectionId, DateTime.Now.ToString());\n    }\n\n    public Task Connect()\n    {\n        return Clients.joined(Context.ConnectionId, DateTime.Now.ToString());\n    }\n\n    public Task Reconnect(IEnumerable<string> groups)\n    {\n        return Clients.rejoined(Context.ConnectionId, DateTime.Now.ToString());\n    }\n}	0
2384679	2384592	Is there a way to force all referenced assemblies to be loaded into the app domain?	var loadedAssemblies = AppDomain.CurrentDomain.GetAssemblies().ToList();\n        var loadedPaths = loadedAssemblies.Select(a => a.Location).ToArray();\n\n        var referencedPaths = Directory.GetFiles(AppDomain.CurrentDomain.BaseDirectory, "*.dll");\n        var toLoad = referencedPaths.Where(r => !loadedPaths.Contains(r, StringComparer.InvariantCultureIgnoreCase)).ToList();\n        toLoad.ForEach(path => loadedAssemblies.Add(AppDomain.CurrentDomain.Load(AssemblyName.GetAssemblyName(path))));	0
753104	751823	How to programmatically add and populate <xs:annotation> and <xs:documenation> tags in C#	const string uri = "http://www.w3.org/2001/XMLSchema";\nXmlDocument d = new XmlDocument();\nd.Load(path);\nXmlNamespaceManager ns = new XmlNamespaceManager(d.NameTable);\nns.AddNamespace("xs", uri);\n\nforeach (XmlElement ct in d.SelectNodes("//xs:complexType", ns))\n{\n    foreach (XmlElement e in ct.SelectNodes("xs:sequence/xs:element", ns))\n    {\n        XmlElement a = d.CreateElement("xs", "annotation", uri);\n        a.InnerText = String.Format(\n            "Complex type: {0}; Element name: {1}",\n            ct.GetAttribute("name"),\n            e.GetAttribute("name"));\n        e.AppendChild(a);\n    }\n}	0
26577125	26577061	Reading text from file and parsing	internal class Program\n{\n    private static void Main(string[] args)\n    {\n        string lines = File.ReadAllText(path: @"readme.txt");\n        string[] words = SplitWords(lines);\n        foreach (var  word in words)\n        {\n            Console.WriteLine(word);\n        }\n    }\n\n    private static string[] SplitWords(string s)\n    {\n        return Regex.Split(s, @"\W+");\n    }\n}	0
1228694	1228675	Scroll to bottom of C# TextBox	private void myForm_Shown(object sender, EventArgs e)\n{\n  txtLogEntries.SelectionStart = txtLogEntries.Text.Length;\n  txtLogEntries.ScrollToCaret();\n}	0
19113914	19113481	Dropdownlist Validation with Submit Button in APS.NET C#	foreach (GridViewRow row in this.gridView.Rows)\n {\n    DropDownList ddl = row.FindControl("ddlName") as DropDownList;\n    if(ddl != null)\n    {\n    //check here\n    }\n }	0
20848280	20847725	Get list of interface	var resourceGatherers = new List<IResourceGatherer>();\n\nvar gathererShips = Planet.Ships.OfType<IResourceGatherer>().ToList();\n\nvar gathererStructures = Structures.OfType<IResourceGatherer>().ToList();\n\nresourceGatherers.AddRange(gathererShips);\nresourceGatherers.AddRange(gathererStructures);	0
10484125	10483171	Multiple assignment operations in one lamdba expression	Expression.Block(first, second);	0
408424	408415	Why explicit interface implementation?	public clas SomeClass : IEnumerable<SomeOtherClass>\n{\n    public IEnumerator<SomeOtherClass> GetEnumerator ()\n    {\n        ...\n    }\n\n    IEnumerator IEnumerable.GetEnumerator ()\n    {\n        return GetEnumerator ();\n    }\n}	0
4438996	4438915	Fastest method of collection searching by DateTime	IEnumerable<item> GetItems(int startIndex, int endIndex, List<item> input)\n    {\n        for (int i=startIndex;i<endIndex;i++)\n           yield return input[i];\n    }	0
3952867	3952849	Sum of SQL table rows with LINQ?	decimal TotalPrice = SampleTable.Sum(q => q.number * q.price);	0
12738794	12738685	Windows 8 local storage	Windows.Storage.ApplicationData.Current.LocalSettings.Values["FirstName"] = "Joe"	0
24067013	24066917	Base Base Constructor C# initialization	class GrandParent ()\n{\n    public int A {get; protected set;}\n    public int B {get; protected set;}\n\n    public GrandParent (int a, int b);\n    {\n        A = a;\n        B = b;\n    }\n}\n\nclass Parent : GrandParent ()\n{\n    public Parent (int a, int b):base(a,b) {}\n}\nChild Class, were the problem occurs.\n\nclass Child : Parent ()\n{\n    public int C {get; protected set}\n\n    public Child (int a, int b, int c):base(a,b)\n    {\n        C = c;\n    }\n}	0
5329179	5329133	Get Key Name from Model State/ Model State Dictionary?	foreach (var key in modelStateDictionary.Keys) \n        {\n            ModelState modelState = modelStateDictionary[key];\n        }	0
6445758	6444926	How to HTML encode a csv export	Response.ContentEncoding = Encoding.UTF32;	0
2291969	2290576	How to use Dynamic Instantiation with ICriteria in Nhibernate?	.SetProjection(Projections.ProjectionList()\n    .Add(Projections.Property("item.id"), "id")\n    .Add(Projections.Property("item.name"), "name"))\n.SetResultTransformer(Transformers.AliasToBean<ItemRow>())\n.List<ItemRow>();	0
24739137	24738976	Is it possible to start same animation for different controls at same start time	private void animateImage(string target)\n{\n     Storyboard testStoryboard = new Storyboard();\n     ...\n\n     testStoryboard.SetValue(Storyboard.TargetNameProperty, target_name);\n     testStoryboard.Begin();\n}	0
30246618	30246497	Using statement for Base64UrlEncode	private static string Base64UrlEncode(string input) {\n    var inputBytes = System.Text.Encoding.UTF8.GetBytes(input);\n    // Special "url-safe" base64 encode.\n    return Convert.ToBase64String(inputBytes)\n      .Replace('+', '-')\n      .Replace('/', '_')\n      .Replace("=", "");\n  }	0
9075169	9072692	WP7 - Parsing XML data	NL = System.Environment.NewLine;\n\ndoc = XDocument.Parse(xml);\nStringBuilder output = new StringBuilder();\n\nvar rounds = doc.Descendants("value");\nforeach(XElement round in rounds)\n{\n  builder.Append(round.Attribute("value").Value + NL);\n  foreach(XElement country in round.Elements())\n  {\n    builder.Append(country.Attribute("home").Value);\n    builder.Append(" - ");\n    builder.Append(country.Attribute("away").Value);\n    builder.Append(" in ");\n    builder.Append(country.Attribute("venue").Value);\n    builder.Append(NL);\n  }\n}	0
10419133	10418160	Gridview textbox multi line only for one single case	void GridView1_RowDataBound(Object sender, GridViewRowEventArgs e)\n{\nforeach (GridViewRow gRow in GridView1.Rows)\n{\nTextBox myfieldtxt = gRow.FindControl("yourTxtBxID") as TextBox;\nLabel myLable = gRow.FindControl("yourLableID") as Label;\n\nif(myLable.Text.Equals("XYZ"))\n{\n  myfieldtxt.TextMode = TextBoxMode.MultiLine;\n}\nelse\n{\n myfieldtxt.TextMode = TextBoxMode.Single;\n}\n}\n}	0
13474244	13473626	Find a number pattern in multiple lines of random numbers	NumberFromLine & NumberFromList == NumberFromList	0
20696737	20582262	Transfer Winform Data to web browser(Chrome, Mozila FireFox, Safari etc)	using (var wc = new WebClient())\n            {\n                var page = wc.DownloadString(arguments);\n                HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();\n                doc.LoadHtml(page);\n                HtmlAgilityPack.HtmlNodeCollection nodes = doc.DocumentNode.SelectNodes("//input");\n               if (nodes != null)\n                {\n                    foreach (HtmlAgilityPack.HtmlNode data in nodes)\n                    {\n                       //Do whatever you want........\n                     }\n                 }\n              }	0
16821076	16820966	Serialize JSON from List<T> and Show Values	List<IndexData> list = new List<IndexData>()\n{\n    new IndexData(){ColumnName="column1",Data="data1"},\n    new IndexData(){ColumnName="column2",Data="data2"},\n};\n\n//Using Json.Net\nvar json1 = JsonConvert.SerializeObject(\n                new {IndexData=list.ToDictionary(x => x.ColumnName, x => x.Data)});\n//Using JavaScriptSerializer\nvar json2 = new JavaScriptSerializer().Serialize(\n                new { IndexData = list.ToDictionary(x => x.ColumnName, x => x.Data) });	0
17582252	17558022	How would you check multiple RichTextboxes containing multiple lines for unique and or duplicate lines	List<string> SortingList = new List<string>();\n\n    using (StreamReader r = new   StreamReader("DistinctItemsNoBlankLines.txt"))\n                        {\n                        string line;\n                        while ((line = r.ReadLine()) != null)\n                            {\n                                SortingList.Add(line);\n                            }\n\n                        }\n\n\n\n   List<string>DistinctSortingList = SortingList.Distinct().ToList();\n\n        foreach (string str in DistinctSortingList)\n        {\n\n        int index = 0;\n            while ( index < DistinctSortingList.Count() -1)\n            {\n            if (DistinctSortingList[index] == DistinctSortingList[index + 1])\n                DistinctSortingList.RemoveAt(index);\n            else\n                index++;\n            }\n        }\n         txtDistinctItems.Lines = DistinctSortingList.ToArray();	0
7363884	7363821	Marshalling an array of structs to a pointer in C#	[DllImport("data.dll")]\ninternal static unsafe extern int MyExternalFunction(DATA[] pData);	0
16971171	16971023	How to make a UserControl grow with container (Form)	FsLookupPanel.Dock = MakeResPanel.Dock = DockStyle.Fill;\nthis.flowLayoutPanel1.Controls.Add(FsLookupPanel);\nthis.flowLayoutPanel1.Controls.Add(MakeResPanel);	0
27205407	27195449	Mathos Parser - using a letter as an operator	else if (Char.IsLetter(ch))\n            {\n                //if (i != 0 && (Char.IsDigit(expr[i - 1]) || Char.IsDigit(expr[i - 1]) || expr[i - 1] == ')'))\n                //{\n                //    tokens.Add("*");\n                //}\n\n                vector = vector + ch;\n\n                while ((i + 1) < expr.Length && Char.IsLetter(expr[i + 1])) // here is it is possible to choose whether you want variables that only contain letters with or without digits.\n                {\n                    i++;\n                    vector = vector + expr[i];\n                }\n\n                tokens.Add(vector);\n                vector = "";\n            }	0
20684180	20673835	Chart control data series	curveChart.Series.Clear();\ncurveChart.Series.Add("Series1");\ncurveChart.Series["Series1"].XValueType = ChartValueType.DateTime;\ncurveChart.Series["Series1"].Points.AddXY(DateTime.Now, 12.00m);\ncurveChart.Series["Series1"].Points.AddXY(DateTime.Now.AddDays(1), 13m);\ncurveChart.Series["Series1"].Points.AddXY(DateTime.Now.AddDays(2), 8m);\ncurveChart.Series["Series1"].ChartType = System.Windows.Forms.DataVisualization.Charting.SeriesChartType.Line;\ncurveChart.Series["Series1"].BorderWidth = 3;\ncurveChart.ChartAreas["0"].AxisX.Interval = 1;\n\ncurveChart.Series.Add("Series2");\ncurveChart.Series["Series2"].XValueType = ChartValueType.DateTime;\ncurveChart.Series["Series2"].Points.AddXY(DateTime.Now, 5.00m);\ncurveChart.Series["Series2"].Points.AddXY(DateTime.Now.AddDays(1), 7m);          \ncurveChart.Series["Series2"].ChartType = System.Windows.Forms.DataVisualization.Charting.SeriesChartType.Line;\ncurveChart.Series["Series2"].BorderWidth = 3;\ncurveChart.ChartAreas["0"].AxisX.Interval = 1;	0
8388668	8388634	Is it possible to serialize objects made from different class in the same xml file?	public class Kennel\n{\n    public Header Header { get; set; }\n    public List<Dog> Dogs { get; set; }\n}	0
11081295	11081109	Logically sorting integers data	var zs = ys.Select(y => Tuple.Create(y, xs.Subsets().Where(s => s.Sum() == y)));	0
27407094	27406136	How can I remove duplicate, invalid, child nodes from an XML document using Linq to XML?	XElement root = XElement.Load(file); // .Parse(string)\nList<string> names = root.Descendants().Distinct(x => x.Name.LocalName).ToList();\nnames.ForEach(name => root.Descendants(name).Skip(1).Remove());\nroot.Save(file); // or root.ToString()	0
21184229	19657512	How to achieve the same image printing quality as windows default printing?	private void pd_PrintPage(object sender, PrintPageEventArgs ev)\n{\n    // Draw a picture.\n    ev.Graphics.DrawImage(Image.FromFile(Global.APPDATA_PATH+ @"tmp\print.png"), ev.Graphics.VisibleClipBounds);\n\n    // Indicate that this is the last page to print.\n    ev.HasMorePages = false;\n}	0
1296993	1296969	Implementing Photoshop filters in C#	BitmapData bmd=bm.LockBits(new Rectangle(0, 0, 10, 10), System.Drawing.Imaging.ImageLockMode.ReadOnly, bm.PixelFormat);\n      int PixelSize=4;\n      for(int y=0; y<bmd.Height; y++)\n      {\n        byte* row=(byte *)bmd.Scan0+(y*bmd.Stride);\n        for(int x=0; x<bmd.Width; x++)\n        {\n          row[x*PixelSize]=255;\n        }\n      } // it is copied from the last provided link.	0
13325296	13325056	searching for a string in a full path c#	class program    \n{\n\n        static void Main(string[] args)\n        {\n            List<string> search = searchSong("SomeThing");\n            foreach (string song in search)\n            {\n                Console.Writeline(song);\n            }\n        }\n\n        public List<string> searchSong(string value)\n        {\n            List<string> songs = new List<string>();\n            String[] mp3 = null;\n            mp3 = Directory.GetFiles(@"D:\Songs", "*.mp3", SearchOption.AllDirectories).ToArray();\n            foreach (String item in mp3)\n            {\n                if (item.Contains(value))\n                {\n                    songs.Add(item);\n                }\n            }\n            return songs;\n        }\n\n    }	0
31692139	31692009	C# short-circuit evaluation without return value	private void EventHandler(object sender, EventArgs e)\n{\n   if (foo(1) || foo(3) || foo(2)) { /* do nothing */ }\n}	0
20564199	20560408	How to use the Nokia Imaging SDK's BlendFilter on WP8?	using (var backgroundSource = new StreamImageSource(stream))\nusing (var filterEffect = new FilterEffect(backgroundSource))\n{\n    using (BlendFilter blendFilter = new BlendFilter()) \n    {\n        var size = new Windows.Foundation.Size(400, 400);\n        var color = Windows.UI.Color.FromArgb(250, 128, 255, 200);\n\n        blendFilter.ForegroundSource = new ColorImageSource(size, color);\n        blendFilter.BlendFunction = BlendFunction.Add;\n\n        filterEffect.Filters = new[] { blendFilter };\n\n        var result = await new JpegRenderer(filterEffect).RenderAsync();\n    }\n}	0
14415738	14415697	How to install a third party application	System.Diagnostics.Process	0
7875351	7875259	How do I get the AM/PM value from a DateTime?	dateTime.ToString("tt", CultureInfo.InvariantCulture);	0
20824958	20824758	How to do the color for a particular row in a gridview?	// on load or when refersh data\n\nif (SelectingID != null)\n{\n    for (int i = 0; i < dgvInvoiceList.Rows.Count; i++)\n    {\n        BillingGeneral.InvoicesDataSet.InvoiceListRow dr = (BillingGeneral.InvoicesDataSet.InvoiceListRow)((DataRowView)dgvInvoiceList.Rows[i].DataBoundItem).Row;\n        if (dr.ID == SelectingID.Value)\n        {\n            dgvInvoiceList.ClearSelection();\n            dgvInvoiceList.Rows[i].Selected = true;\n            SelectingID = null;\n            break;\n        }\n    }\n}	0
16456816	14444036	Reference stylesheet/spcript from User Control	stylePlaceholder = ((PlaceHolder)((ContentPlaceHolder)Page.Master.Master.FindControl("HeadSection")).FindControl("phd_ControlsStyles"));\n\nstylePlaceholder.Controls.Add(new LiteralControl(css + " href=\"http://" + cdn + "/Utils/Bundle/" + getCss() + ".css?v=" + settings["subVersion"] + "\" />"));	0
22936864	22936699	XMl Search and filter in windows phone	string xml = @"<?xml version='1.0' encoding='UTF-8'?>\n<root>\n  <player>\n    <playerId>1234</playerId>\n    <playerName>ABCD</playerName>\n\n   <line>\n      <studentId>5612</studentId>\n      <studentName>WXYZ</studentName>\n   </line>\n\n  </player>\n</root>";\n\nvar doc = XDocument.Parse(xml);\n\nstring studentName = (string)doc.Descendants("player")\n               .Where(p => (string)p.Element("playerName") == "ABCD")\n               .Descendants("studentName").First();	0
17101678	17101570	How to Draw Lines with delay?	public partial class DrawingForm : Form\n{\n    Timer m_oTimer = new Timer ();\n\n    public DrawingForm ()\n    {\n        InitializeComponent ();\n\n        m_oTimer.Tick += new EventHandler ( m_oTimer_Tick );\n        m_oTimer.Interval = 2000;\n        m_oTimer.Enabled = false;\n    }\n\n    // Enable the timer and call m_oTimer.Start () when\n    // you're ready to draw your lines.\n\n    void m_oTimer_Tick ( object sender, EventArgs e )\n    {\n        // Draw the next line here; disable\n        // the timer when done with drawing.\n    }\n}	0
19583302	19582898	Sort a datatable but keep rows containing 0 always at bottom	DataRow[] drnew = dt.Select("Price <> 0");\nDataRow[] drzero = dt.Select("Price = 0");\nDataTable dtfinal = new DataTable();\nif (drnew != null && drnew.Count() > 0)\n{\n    DataView dv = drnew.CopyToDataTable().DefaultView;\n    dv.Sort = "Price Desc";\n    dtfinal = dv.Table;\n}\nif (drzero != null && drzero.Count() > 0)\n{\n    dtfinal.Merge(drzero.CopyToDataTable());\n}	0
27198561	27197852	wpf Datagrid Cell Formatting	if (e.PropertyType == typeof(System.DateTime))\n{\n    Style styleCenter = new Style(typeof(DataGridCell));\n\n    styleCenter.Setters.Add(new Setter(HorizontalAlignmentProperty, HorizontalAlignment.Center));\n    styleCenter.Setters.Add(new Setter(FontWeightProperty, FontWeights.Bold));\n    styleCenter.Setters.Add(new Setter(ForegroundProperty, Brushes.Red));\n\n    (e.Column as DataGridTextColumn).Binding.StringFormat = "dd/MM/yyyy";\n    (e.Column as DataGridTextColumn).CellStyle = styleCenter;\n}	0
8217240	8217205	Get access to the Sender control - C#	void pb_point_Click(object sender, EventArgs e)\n{\n    var pictureBox = (PictureBox)sender;\n    MessageBox.Show(pictureBox.Location.ToString());\n}	0
2789	2780	Converting ARBG to RGB with alpha blending	alpha=argb.alpha()r = (alpha/255)*argb.r() + (1 - alpha/255)*blend.r()g = (alpha/255)*argb.g() + (1 - alpha/255)*blend.g()b = (alpha/255)*argb.b() + (1 - alpha/255)*blend.b()	0
10490163	10490092	Get all values between delimiters in large string	List<string> matches = Regex.Matches(STRING, @"(?<=/PI/).*(?=/500/)")\n                            .Cast<Match>()\n                            .Select(m => m.Value)\n                            .ToList();	0
13329302	13027194	How to get the char input for a certain key, in the current culture or language?	[DllImport("user32.dll")]\n    public static extern int ToUnicode(uint virtualKeyCode, ScanCodeShort scanCode,\n        byte[] keyboardState,\n        [Out, MarshalAs(UnmanagedType.LPWStr, SizeConst = 64)]\nStringBuilder receivingBuffer,\n        int bufferSize, uint flags);\n\n    public static string GetCharsFromKeys(ScanCodeShort keys)\n    {\n        var buf = new StringBuilder(256);\n        var keyboardState = new byte[256];\n        GetKeyState(VirtualKeyStates.VK_F3);\n        GetKeyboardState(keyboardState);\n        keyboardState[(int)System.Windows.Forms.Keys.ControlKey] = 0x00;\n        int x = ToUnicode(MapVirtualKey(keys, 1), keys, keyboardState, buf, 256, 0);\n        return buf.ToString();\n    }\n\n\n    [DllImport("user32.dll")]\n    static extern short GetKeyState(VirtualKeyStates nVirtKey);\n\n    [DllImport("user32.dll")]\n    [return: MarshalAs(UnmanagedType.Bool)]\n    static extern bool GetKeyboardState(byte[] lpKeyState);	0
21777517	21762007	Inserting a record into SQL Server Compact database using TableAdapter	private MyDataSetTableAdapters.MeasurementTableAdapter measurementTableAdapter =\n         new MyDataSetTableAdapters.MeasurementTableAdapter();\n\n         measurementTableAdapter.Insert((n+1), DeviceID, DateTime.Now, Values[n]);	0
21650239	21649494	Copy a node from one xml to another	XElement rss = XElement.Parse("string xml feed");\nXNamespace ns = "http://...";\nXElement feed = rss.Descendants(ns + "condition").Last();\n\nXElement file = XElement.Load("file");\nXElement local = file.Descendants(ns + "condition").LastOrDefault();\n\nif (feed.Attribute("date").Value != local.Attribute("date").Value)\n    local.AddAfterSelf(feed);\n\nfile.Save("file");	0
9994602	9973926	An application consuming almost 100% CPU on A SYSTEM	System.Windows.Forms.Timer	0
21558551	21558239	Trouble with file properties	namespace ConsoleApplication1\n{\n    class Program\n    {\n        static void Main(string[] args)\n\n        {\n            var dir = new DirectoryInfo(@"C:\Windows");\n\n            foreach (var file in dir.GetFiles())\n            {\n                Console.WriteLine("Name: " + file.Name + "\r\nSize: " + file.Length + "\r\nType: " + file.GetType());\n            }\n            Console.ReadKey();\n\n        }\n    }\n}	0
4753776	4753685	C# Insert missing records, from a list with linq?	List<Guid> usersWithoutInfo = new List<Guid>(){......};\n\nvar usersToInsert = usersWithoutInfo.Where(userGuid => !usertableInDB.Contains(userGuid)).ToList();	0
18098223	18097533	How to get javascript/html Code as it is from a textbox	Server.HtmlDecode(TextBox_Editor.Text)	0
10841245	10841168	How to define by using C# code a space between controls?	label1.Position=new Point(picbox1.Right, picbox1.Top);\nlabel2.Position=new Point(picbox1.Left, picbox1.Bottom);	0
18206529	18206209	Rounding to 2 decimal places, without using banker's rounding	public static decimal RoundHalfUp(this decimal d, int decimals)\n{\nif (decimals < 0)\n{\n    throw new ArgumentException("The decimals must be non-negative", \n        "decimals");\n}\n\ndecimal multiplier = (decimal)Math.Pow(10, decimals);\ndecimal number = d * multiplier;\n\nif (decimal.Truncate(number) < number)\n{\n    number += 0.5m;\n}\nreturn decimal.Round(number) / multiplier;\n}	0
20069668	20069409	Add line numbers to stack trace of ASP.NET web site that is deployed in release mode	Advanced...	0
11198884	11198845	Multi key dictionary where only 1 key is needed to retrieve object	Dictionary<string, object> dict = new Dictionary<string, object>();\ndict.Add("key1", obj);\ndict.Add("key2", obj);\n\n// dict["key1"] == dict["key2"]	0
7106971	7080981	How use Observable.ToAsync with IEnumerable	var users = Run(path); //NOTE: This doesn't execute your run method yet, Run will only execute when you start enumerating the users values\nusers.ToObservable(System.Concurrency.Scheduler.ThreadPool) //The enumerator will be scheduled on separate thread\n.ObserveOn(frm) //Observe on UI thread of win form\n.Subscribe(s => {}) //This will run in UI thread for each user object	0
6434824	6434469	Getting sibling using xPath	while(theNodes2.MoveNext())	0
17340121	17304812	Gridview always add new row when click button?	for (int i = dtCurrentTable.Rows.Count; i < visitors; i++)\n            {\n                //extract the TextBox values\n                TextBox box1 = (TextBox)Gridview1.Rows[rowindex].Cells[1].FindControl("txtDate");\n                TextBox box2 = (TextBox)Gridview1.Rows[rowindex].Cells[2].FindControl("TextBox2");\n                TextBox box3 = (TextBox)Gridview1.Rows[rowindex].Cells[3].FindControl("TextBox3");\n\n                drCurrentRow = dtCurrentTable.NewRow();\n                drCurrentRow["RowNumber"] = i + 1;\n                drCurrentRow["Column1"] = box1.Text;\n                drCurrentRow["Column2"] = box2.Text;\n                drCurrentRow["Column3"] = box3.Text;\n                dtCurrentTable.Rows.Add(drCurrentRow);\n                drCurrentRow = null;\n                rowindex++;\n            }	0
16596105	16596002	Get time process takes to complete in seconds?	Stopwatch watch = new Stopwatch();\nwatch.Start();\n//Do things\nwatch.Stop();\nText = watch.Elapsed.Seconds.ToString();	0
23140289	23139643	Aggregate List Based on Child Properties	var groupings = list.SelectMany(x => x.AdditionalPropertyList).GroupBy(x => x.PartNumber).Select(g => new { PartNumber=g.Key, Quantity=g.Sum(x => x.Quantity) } );\n\n foreach (var g in groupings)\n    Console.WriteLine("PartNumer: {0} Total: {1}", g.PartNumber, g.Quantity);	0
21059538	21053780	Getting multiple DbContexts to use Migrations with the same database	IdentityDbContext<ApplicationUser>	0
311583	311576	Parsing a Date Range in C# - ASP.NET	var dates = TextBoxDateRange.Text.Split(new char[] { '-' }, StringSplitOptions.RemoveEmptyEntries);\n\nvar startDate = DateTime.Parse(dates[0], CultureInfo.CurrentCulture);\nvar endDate = DateTime.Parse(dates[1], CultureInfo.CurrentCulture);	0
29299759	29299297	Measure text height wrapped in a specified width	var size = TextRenderer.MeasureText(text, font, new Size(width, height), TextFormatFlags.WordBreak);	0
16847549	16847548	XmlNode indexer result if there is no such element	const string xmlData = @"<?xml version=""1.0"" encoding=""utf-16""?>\n<testRoot xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" xmlns:xsd=""http://www.w3.org/2001/XMLSchema"">\n    <ExampleData isData=""true"" testString=""Hello World!"">\n        content\n    </ExampleData>\n</testRoot>";\nXmlDocument doc = new XmlDocument();\ndoc.LoadXml(xmlData);\nvar item = doc["foo"];\nAssert.IsNull(item);	0
2313221	2313196	If I return a value inside a using block in a method, does the using dispose of the object before the return?	class Program\n    {\n        static void Main(string[] args)\n        {\n            TestMethod();\n            Console.ReadLine();\n        }\n\n        static string TestMethod()\n        {\n            using (new Me())\n            {\n                return "Yes";\n            }\n        }\n    }\n\n    class Me : IDisposable\n    {\n        #region IDisposable Members\n\n        public void Dispose()\n        {\n            Console.WriteLine("Disposed");\n        }\n\n        #endregion\n    }	0
32799279	32799077	Combine Words and Generate Variations From Multiple Textbox	for (int entryKeyword1 = 0; entryKeyword1 < keyword1.Count; entryKeyword1++)\n{\n    for (int entryKeyword2 = 0; entryKeyword2 < keyword2.Count; entryKeyword2++)\n    {\n        for (int entryKeyword3 = 0; entryKeyword3 < keyword3.Count; entryKeyword3++)\n        {\n            combinedKeywords.Add(String.Concat(keyword1[entryKeyword1], " ", keyword2[entryKeyword2], " ", keyword3[entryKeyword3]));\n        }\n    }\n}	0
23397071	23397002	Getting correct value in Debug mode, wrong in Release mode with Serial Programing	string indata = sp.ReadTo("\r\n");	0
23143616	23143502	GroupBy then do aggregation on results for each group	var grouped = people.GroupBy(x => x.name)\n                                .Select(x => new\n                                    {\n                                        Name = x.Key,\n                                        Age = x.Sum(v => v.age),\n                                        Result = g.Aggregate(new Int32(), (current, next) => next.age + next.age)\n                                    });	0
33678229	33677859	How to use variables of child in parents static method?	class Parent{\n    public static string myString = "I don't want this string";\n\n    public static void MyMethod(){\n        Console.Write(myString);\n    }\n}\n\nclass Child : Parent{\n    new public static string  myString = "I want THIS string";\n    public new static void MyMethod(){\n        var old=Parent.myString;\n        Parent.myString=myString;\n        Parent.MyMethod();\n        Parent.myString=old;\n    }\n}\n\nclass Program\n{\n    static void Main()\n    {\n        Child.MyMethod(); // I want to output "I want THIS string";\n    }\n}	0
16254210	16238390	How will I load/cache the holidays from my database? It will be added to my DateTimeExtensions that already excludes weekends	public static bool IsHoliday(this DateTime date)\n{\nConnectionStringSettings myConnectionString = ConfigurationManager.ConnectionStrings["System.Properties.Settings.ConnectionString"];\nSqlConnection mySqlConnection = new SqlConnection(myConnectionString.ConnectionString);\nmySqlConnection.Open();\nSqlCommand mySqlCommand = new SqlCommand("SELECT Date FROM Holiday", mySqlConnection);\nSqlDataReader sqlreader = mySqlCommand.ExecuteReader();\n\nList<DateTime> holidays = new List<DateTime>();\n\nwhile (sqlreader.Read())\n{\nholidays.Add(sqlreader.GetDateTime(0));\n}\nholidays.ToArray();\nmySqlConnection.Close();\nreturn holidays.Contains(date.Date);\n}	0
23119340	23118881	Append a text file starting from a certain location in the source text file	string originalContents = File.ReadAllText("original.txt");\nstring insertContents = File.ReadAllText("append.txt");\nint index = originalContents .IndexOf("match");\nif (index == -1) return;\nFileStream stream = new FileStream("original.txt", FileMode.Open);\nstream.Position = index;\nbyte[] insertBytes = Encoding.ASCII.GetBytes(insertContents);\nstream.Write(insertBytes);\nbyte[] endBytes = Encoding.ASCII.GetBytes(originalContents.Substring(index));\nstream.Write(endBytes);	0
3826407	3826384	Finding minimum values of (properties of ) collections in C#	using System.Linq;\n\nvar collection = new EngineMeasurementCollection();\nint maxSpeed = collection.Max(em => em.Speed);	0
3645500	3645494	How can anonymous types be created using LINQ with lambda syntax?	var query =\n    books\n        .Where(book => book.Length > 10)\n        .OrderBy(book => book.Length)\n        .Select(book => new { Book = book.ToUpper() });	0
9036445	8994786	How do I remove an Excel Chart Legend Entry with C#?	// .\n// . code to add series\n// .\n// remove the legend entry for the newly added series\nchart.Legend.LegendEntries(chart.Legend.LegendEntries().Count).Delete();	0
6753784	6753572	Help with c# lambda expression	public static TResult TryGetOrDefault<TSource, TResult>(this TSource obj, Func<TSource, TResult> expression)\n{\n    if (obj == null)\n        return default(TResult);\n\n    try\n    {\n        return expression(obj);\n    }\n    catch(NullReferenceException)\n    {\n        return default(TResult);\n    }\n}	0
19387808	19387760	Find average salary of a department using LINQ	var massagedEmployees = employees.GroupBy(e => e.Department)\n                                .Select(g => new { Department = g.Key, Avg = g.Average(e => e.Salary) } );	0
15701190	15701183	How to access form elements from another class	public class spaceship\n{ \n    Image myimage = Image.FromFile("image/Untitled6.png");\n    Form1 myform = new Form1();\n\n    spaceship()\n    {\n        myform.pictureBox1.Image = myimage;             \n    }\n}	0
23927724	23926448	How do I update a time value back to NULL on a column with data type time(7)	if(txtMeetingTime.Text.Length > 0)\n{\n    DateTime meetingTime;\n    DateTime.TryParseExact(txtMeetTime.Text, new string[] { "H:mm" },\n          System.Globalization.CultureInfo.InvariantCulture,\n          System.Globalization.DateTimeStyles.None,\n          out meetingTime);\n    cmd.Parameters.AddWithValue("@updateTime", meetingTime);\n}\nelse\n{\n    cmd.Parameters.Add("@updateTime",SqlDbType.DateTime).Value = DBNull.Value;\n}	0
19444131	19444053	C# - Foreach Url in Listbox, complete tasks	listBox1.Items.Cast<string>().ToList().ForEach((s) => GoToWebSite(s));	0
18195598	18195325	Set Combo Box in Datagridview Column	DropDownList ddl = (DropDownList)e.Row.FindControl("ddlName");\nddl.SelectedValue = "HELP";	0
11578465	11578424	split function settings	string.Split	0
2508314	2508120	fast way for finding GUIDs	public interface IJobDoer\n{\n    void DoJob();\n    Guid Guid{get;}\n}\n\npublic class FirstJobType : IJobDoer\n{\n    void DoJob()\n    {\n     /// whatever...\n    }\n    Guid Guid { get{return "insert-guid-here";}}\n}	0
4070045	4063023	StructureMap - How to register and resolve an open generic type	Scan(x =>\n{\n    x.WithDefaultConventions();\n    x.AssemblyContainingType(typeof(TeamEmployeeRepository));\n    x.AddAllTypesOf(typeof(Repository<>));\n    x.ConnectImplementationsToTypesClosing(typeof(IRepository<>));\n});	0
8187351	8187210	How to get a reference to the underlying data type of a Data Template in WPF	private void HandleClick(object sender, EventArgs e)\n{\n  ....	0
9564039	9563105	Localization with editable messages at runtime	MyXmlReader = System.Xml.XmlReader.Create(MyResourceFileName)\nMyResourceDictionary = System.Windows.Markup.XamlReader.Load(MyXmlReader)	0
29208624	29208266	ASP.net Getting Max Date of database Date column How to avoid Null in Date Column C# My code Attached	var LastUpdate = ds.Tables[0].AsEnumerable().Where(r => r.Field<DateTime?>(col.ColumnName) != null).Max(r => r.Field<DateTime>(col.ColumnName));	0
6959902	6959872	Loading a DataTable with the items in a DataSet	DataTable dt = dataSetInstance.Tables[0];	0
6278304	6201678	How to convert dates without getting 'String was not recognized as a valid DateTime.'-error?	Convert.ToDateTime(row.Cells[6].Text)	0
11633138	11617906	links in mvc2 cease to properly follow virtual path when loaded asynchronously in a partial view	.post()	0
7732093	7732028	how to get specific file names using c#	string [] fileEntries = Directory.GetFiles(targetDirectory, "*-*.zip");	0
6141798	6141762	manipulate elements in a list - c#	List<string> originalList = ...\nList<string> newList = originalList.Select(s => s.Split('\\')[0]).ToList()	0
28608929	28607665	Creating a list that dynamically expands when a request is made C#	var objectsToShow = allObjectsCollection.Skip(10).Take(10);	0
23040062	22954349	How i can display MailMessage in WebBrowser,RichTextBox or free component to C#	var dataStream = messageList[i].AlternateViews[0].ContentStream;\nbyte[] byteBuffer = new byte[dataStream.Length];\nstring altbody =  System.Text.Encoding.UTF8.GetString(byteBuffer, 0, dataStream.Read(byteBuffer, 0, byteBuffer.Length));\nwebbrowser.DocumentText = altbody;	0
21993367	21978608	How to implement Session Per Conversation pattern with WebAPI/ NHibernate	// GET api/companies\npublic IQueryable<Company> GetCompanies()\n{\n    return _session.Query<Company>();\n}	0
5748273	5740254	How do I load an image from a URL in Silverlight without having the image control be in the visual tree	public void Fetch(Uri uri)\n{\n    WebClient webClient = new WebClient();\n    webClient.OpenReadCompleted += this.ReadCompleted;\n    webClient.OpenReadAsync(uri);\n}\n\nprivate void ReadCompleted(object sender, OpenReadCompletedEventArgs e)\n{\n    WebClient webClient = (WebClient)sender;\n    webClient.OpenReadCompleted -= this.ReadCompleted;\n    Stream stream = e.Result;\n    BitmapImage bmp = new BitmapImage();\n    bmp.SetSource(stream);\n    WriteableBitmap wbmp = new WriteableBitmap(bmp);\n}	0
11196879	11190115	Footer page number from Word document	Public Sub GetPageNumber()\n    On Error GoTo MyErrorHandler\n\n    Dim currentDocument As Document\n    Set currentDocument = ActiveDocument\n\n    Debug.Print Selection.Sections(1).Footers(wdHeaderFooterPrimary).Range.Text 'Or...\n    Debug.Print Selection.Sections(1).Footers(wdHeaderFooterPrimary).Range.Fields(1).Result\n\n    Exit Sub\n\nMyErrorHandler:\n    MsgBox "GetPageNumber" & vbCrLf & vbCrLf & "Err = " & Err.Number & vbCrLf & "Description: " & Err.Description\nEnd Sub	0
5962500	5961981	I want to retrieve an Image from database and crop it as per the user needs	connection.Open();\n    SqlCommand command = new SqlCommand("select Photo from iffcar", connection);\n    byte[] image = (byte[])command.ExecuteScalar();\n    stream.Write(image, 0, image.Length);\n    Bitmap bitmap = new Bitmap(stream);\n\n    int croppedWidth = ??, croppedHeight = ??, cropOffsetX = ??, cropOffsetY = ??;\n    var croppedBitmap = new Bitmap(croppedWidth, croppedHeight);\n    var graphics = Graphics.FromImage(croppedBitmap);\n    graphics.DrawImage(bitmap, -cropOffsetX, -cropOffsetY, bitmap.Width, bitmap .Height);\n    Response.ContentType = "image/gif";\n    croppedBitmap.Save(Response.OutputStream, ImageFormat.Jpeg);	0
3458125	3434447	How to hide the empty Column	if(String.IsNullOrEmpty(mydatagrid.Rows[0][0].ToString()) && mydatagrid.Rows.Count==1) //Check a field that would normally have a value\n{\n     mydatagrid.Rows.RemoveAt(0);\n}	0
13991760	13989680	How to handle TreeView nodes with semicolons ;	testCaseTreeView.PathSeparator = "/";	0
22596935	22594074	Unity 4.3 - understanding positions and screen resolution, how to properly set position of object?	// Update is called once per frame\nvoid Update () {\n    float camHalfHeight = Camera.main.orthographicSize;\n    float camHalfWidth = Camera.main.aspect * camHalfHeight; \n\n    Bounds bounds = GetComponent<SpriteRenderer>().bounds;\n\n    // Set a new vector to the top left of the scene \n    Vector3 topLeftPosition = new Vector3(-camHalfWidth, camHalfHeight, 0) + Camera.main.transform.position; \n\n    // Offset it by the size of the object \n    topLeftPosition += new Vector3(bounds.size.x / 2,-bounds.size.y / 2, 0);\n\n    transform.position = topLeftPosition;        \n}	0
12587480	12587336	please let me know how to load the List<dataset> of first dataset values to List<Person>	List<Person> pers = lstPer[0].Tables[0].AsEnumerable().\n                    Select(r=> new Person() { \n                        FirstName = r.Field<string>("fieldname1"),\n                        MiddleName = r.Field<string>("fieldname2")\n                    })\n                    .ToList();	0
24125421	24110598	c# Datetime bound textbox removes starting 0s	var culture = CultureInfo.CurrentCulture.Clone() as CultureInfo;\nculture.DateTimeFormat.ShortDatePattern = "MM/dd/yyyy";\nSystem.Threading.Thread.CurrentThread.CurrentCulture = culture;	0
17927685	17683548	How do I attach a second process when the debugger starts?	internal class DebugEventMonitor {\n\n    // DTE Events are strange in that if you don't hold a class-level reference\n    // The event handles get silently garbage collected. Cool!\n    private DTEEvents dteEvents;\n\n    public DebugEventMonitor() {\n        // Capture the DTEEvents object, then monitor when the 'Mode' Changes.\n        dteEvents = DTE.Events.DTEEvents;                     \n        this.dteEvents.ModeChanged += dteEvents_ModeChanged;\n    }\n\n    void dteEvents_ModeChanged(vsIDEMode LastMode) {\n        // Attach to the process when the mode changes (but before the debugger starts).\n        if (IntegrationPackage.VS_DTE.DTE.Mode == vsIDEMode.vsIDEModeDebug) {\n            AttachToServiceEngineCommand.Attach();\n        }\n    }\n\n}	0
32525991	32525674	How to bind dynamic property?	[DataContract]\n    public class Data\n    {\n        [DataMember]\n        public List<Items> photos { get; set; }\n    }\n\n    [DataContract]\n    public class Items\n    {\n        [DataMember(Name = "3")]\n        public string Three { get; set; }\n        [DataMember(Name="0")]\n        public string Zero { get; set; }\n        [DataMember(Name = "2")]\n        public string Two { get; set; }\n    }\n\n    public static void TestJson()\n    {\n        var json = "{\"photos\":[{\"0\":\"some data\",\"2\":\"other data\",\"3\":\"another data\"}]}";\n\n        var serializer = new DataContractJsonSerializer(typeof(Data));\n        Data data = serializer.ReadObject(new MemoryStream(Encoding.UTF8.GetBytes(json))) as Data;\n    }	0
17886904	17886871	SQL error: must declare a scalar variable	declare @RowID int;\nINSERT [db].[xyyz] (x,y,z) values (@x,@y,@z)\nSET @RowId = SCOPE_IDENTITY();\ncommand.Parameters.AddWithValue("@x", x);\ncommand.Parameters.AddWithValue("@y", y);\ncommand.Parameters.AddWithValue("@z", z);	0
2455828	2455703	Splash Screen Example	private void Form1_Load(object sender, System.EventArgs e)\n{\n    // Display the splash screen\n    var splashScreen = new SplashForm();\n    splashScreen.Show()\n\n    // On the splash screen now go and show loading messages\n    splashScreen.lblStatus.Text = "Loading Clients...";\n    splashScreen.lblStatus.Refresh();\n\n    // Do the specific loading here for the status set above\n    var clientList = _repository.LoadClients();\n\n    // Continue doing this above until you're done\n\n    // Close the splash screen\n    splashScreen.Close()\n}	0
5919363	5886775	How to get the if the Page is Liked in my Facebook Application page	FacebookWebClient fbApi = new FacebookWebClient(FacebookWebContext.Current.AccessToken);\n\ndynamic peramaters = new ExpandoObject();\nperamaters.method = "pages.isFan";\nperamaters.page_id = ConfigurationManager.AppSettings["PageId"]; \n\ndynamic likes = fbApi.Get(peramaters);\n\nif (!(bool)likes) // do stuff	0
214106	214086	How can you get the names of method parameters?	public static string GetParamName(System.Reflection.MethodInfo method, int index)\n{\n    string retVal = string.Empty;\n\n    if (method != null && method.GetParameters().Length > index)\n        retVal = method.GetParameters()[index].Name;\n\n\n    return retVal;\n}	0
5548984	5548936	Making A New Paramatirized Thread	private void OpenNewThread(bool open)\n{\n    Thread thread = new Thread(new ThreadStart(\n        () => CloseOpenAnimation(open)));\n    thread.Start();\n}	0
26697345	26676556	FACEBOOK - c# UserID/feed GET post comments Picture URL	[user_id]/feed?fields=[comma separated fields],comments{attachment,[comma separated fields]}	0
23899810	23899555	How can I convert a workweek double into a DateTime in C#	void Main()\n{\n    string k = "22.4";\n    Console.WriteLine(ConvertWeekDay(k, 2014).ToString());\n    k = "53.1";\n    Console.WriteLine(ConvertWeekDay(k, 2014).ToString());\n    k = "1.1";\n    Console.WriteLine(ConvertWeekDay(k, 2015).ToString());\n}\n\npublic DateTime ConvertWeekDay(string weekday, int year)\n{\n    int w; int d;\n    string[] wd = weekday.Split(new char[] {'.'});\n    w = int.Parse(wd[0]); d = int.Parse(wd[1]);\n    DateTime dt = new DateTime(year,1,1);\n    while(dt.DayOfWeek != DayOfWeek.Monday)\n        dt = dt.AddDays(-1);\n\n    dt = dt.AddDays(7 * (w - 1) + d - 1);\n    return dt;\n}	0
4500242	4500130	Data not getting saved properly in excel file from stream writer	Excel.Range rg = (Excel.Range)worksheetobject.Cells[1,1];\nrg.EntireColumn.NumberFormat = "dd-MM-yyyy";	0
4352230	4352209	Conversion from UTF8 to ASCII	var input = "La introducci?n masiva de las nuevas tecnolog?as de la informaci?n";\nvar utf8bytes = Encoding.UTF8.GetBytes(input);\nvar win1252Bytes = Encoding.Convert(\n                Encoding.UTF8, Encoding.GetEncoding("windows-1252"), utf8bytes);\nFile.WriteAllBytes(@"foo.txt", win1252Bytes);	0
331761	330115	Retrieving product information from an unmanaged executing application in C#/.NET	HMODULE hEXE = GetModuleHandle(NULL);	0
28749093	28739477	accessing a remote registry with local credentials (of the remote machine) on the domain	...\nusing Microsoft.Win32;\nusing System.Net;\n...\n\nstring hostName = 192.168.1.1;\n\nusing (new NetworkConnection(@"\\" + hostName + @"\admin$", new NetworkCredential(@"ad\administrator", "TopSecret")))\n{\n    using (RegistryKey remoteHklm = RegistryKey.OpenRemoteBaseKey(RegistryHive.LocalMachine, hostName))\n    {\n        using (RegistryKey serviceKey = remoteHklm.OpenSubKey("System\\CurrentControlSet\\Services", true))\n        {\n            if (serviceKey != null)\n            {\n                foreach (string key in serviceKey.GetSubKeyNames())\n                {\n                    Console.WriteLine(key);\n                }\n            }\n        }\n\n    }\n}	0
1127200	1122231	Open another application's System Menu	public static void ShowContextMenu(IntPtr hAppWnd, Window taskBar, System.Windows.Point pt)\n{\nWindowInteropHelper helper = new WindowInteropHelper(taskBar);\nIntPtr callingTaskBarWindow = helper.Handle;\nIntPtr wMenu = GetSystemMenu(hAppWnd, false);\n// Display the menu\nuint command = TrackPopupMenuEx(wMenu,\nTPM.LEFTBUTTON | TPM.RETURNCMD, (int) pt.X, (int) pt.Y, callingTaskBarWindow, IntPtr.Zero);\nif (command == 0)\nreturn;\n\nPostMessage(hAppWnd, WM.SYSCOMMAND, new IntPtr(command), IntPtr.Zero);\n}	0
1371414	1371408	How to validate a Regular Expression?	public static bool IsRegexPatternValid(String pattern)\n{\n    try\n    {\n        new Regex(pattern);\n        return true;\n    }\n    catch { }\n    return false;\n}	0
10371086	10370931	Using app domains in C#	static void UsereflectionWithAppDomain()\n{\n    AppDomain mydomain = AppDomain.CreateDomain("MyDomain");\n    MethodInfo mi = default(MethodInfo);\n\n    // Once the files are generated, this call is\n    // actually no longer necessary.\n\n    byte[] rawAssembly = loadFile(@"d:\RelectionDLL.dll");\n\n    // rawSymbolStore - debug point are optional.\n    byte[] rawSymbolStore = loadFile(@"d:\RelectionDLL.pdb");\n    Assembly assembly = mydomain.Load(rawAssembly, rawSymbolStore);\n\n    Type reflectionClassType = assembly.GetType("ReflectionDLL.MyStaicClass");\n\n    mi = reflectionClassType.GetMethod("PrintI");\n    mi.Invoke(null, null);\n\n    AppDomain.Unload(mydomain);\n}\n\n\n// Loads the content of a file to a byte array. \nstatic byte[] loadFile(string filename)\n{\n    FileStream fs = new FileStream(filename, FileMode.Open);\n    byte[] buffer = new byte[(int)fs.Length];\n    fs.Read(buffer, 0, buffer.Length);\n    fs.Close();\n\n    return buffer;\n}	0
21508276	21504434	How to Represent Conjugation Tables in C#	List<ConjugationForm> conjugationTable {get; set;}	0
7813993	7813968	C# array get last item from split in one line	string lastItemOfSplit = aString.Split(new char[] {@"\"[0], "/"[0]}).Last();	0
22362422	22362118	C# Form application - Retrieve notification icon file app.config	System.Drawing.Icon ico = (System.Drawing.Icon)Properties.Resources.ResourceManager.GetObject(ConfigurationManager.AppSettings["icopath"].ToString());	0
3541598	3541507	Hide ID column in ListView control	public partial class Form1 : Form {\n    public Form1() {\n        InitializeComponent();\n        listView1.Columns[1].Width = 0;\n        listView1.ColumnWidthChanging += listView1_ColumnWidthChanging;\n    }\n\n    private void listView1_ColumnWidthChanging(object sender, ColumnWidthChangingEventArgs e) {\n        if (e.ColumnIndex == 1) {\n            e.NewWidth = 0;\n            e.Cancel = true;\n        }\n    }\n}	0
20176868	20176819	How to find one value from an IQueryable in C# ASP.NET MVC 4 using Linq	var portfolio = _db.Users\n                   .Where(u => u.UserName == userName)\n                   .Select(u =>u.Portfolio)\n                   .FirstOrDefault();\nif(portfolio == null)\n        {\n            return HttpNotFound();\n        }//end of if\n        return View(portfolio);	0
29771609	29771468	Iframe click make div show hide	function assignHandler() {\n  var ifr = document.getElementById("iframe1");\n  var iframeDocument = ifr.contentDocument || ifr.contentWindow.document;\n  var links=iframeDocument.getElementsByTagName("a");\n  for (var i=0;i<links.length;i++) {\n    links[i].onclick=function() {\n      var div = parent.document.getElementById("divTest");\n      if (div) div.style.display=this.href.indexOf("Locker")!=-1?"block":"none";\n      return false; // remove when link is needed\n    }\n  }  \n}	0
7469864	7469828	LINQ query to split an ordered list into sublists of contiguous points by some criteria	myList.ChunkBy( o => o.FlagSet )	0
24898493	24898447	Adding more items to a group by statement	var rowsPerProvider = (from row in dt.Select()\n    group row by new\n    {\n        emp1 = row["f_name"].ToString().Trim(),\n        emp2 = row["m_name"].ToString().Trim(),\n        emp3 = row["l_name"].ToString().Trim(),\n    }\n    into g\n    select g).ToDictionary(\n        g => g.Key,\n        g => g.ToArray());	0
15343898	15270764	get ssl certificate in .net	using System.Security;\n    using System.Security.Cryptography;\n    using System.Security.Cryptography.X509Certificates;\n\n    //Do webrequest to get info on secure site\n    HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://mail.google.com");\n    HttpWebResponse response = (HttpWebResponse)request.GetResponse();\n    response.Close();\n\n    //retrieve the ssl cert and assign it to an X509Certificate object\n    X509Certificate cert = request.ServicePoint.Certificate;\n\n    //convert the X509Certificate to an X509Certificate2 object by passing it into the constructor\n    X509Certificate2 cert2 = new X509Certificate2(cert);\n\n    string cn = cert2.GetIssuerName();\n    string cedate = cert2.GetExpirationDateString();\n    string cpub = cert2.GetPublicKeyString();\n\n    //display the cert dialog box\n    X509Certificate2UI.DisplayCertificate(cert2);	0
34107565	34107476	Get type of generic parameter from class which is inherited from generic interface	// your type\nvar type = typeof(Impl);\n// find specific interface on your type\nvar interfaceType = type.GetInterfaces()\n    .Where(x=>x.GetGenericTypeDefinition() == typeof(IInterface<>))\n    .First();\n// get generic arguments of your interface\nvar genericArguments = interfaceType.GetGenericArguments();\n// take the first argument\nvar firstGenericArgument = genericArguments.First();\n// print the result (System.Int32) in your case\nConsole.WriteLine(firstGenericArgument);	0
10421852	10421466	How to make my i7 processor reach 100% usage with this code (fastest way to parse xml)	Parallel.For	0
247417	247313	Can I Format A String Like A Number in .NET?	string number = "1234567890";\nstring formattedNumber = string.Format("{0}-{1}-{2}", number.Substring(0,3), number.Substring(3,3), number.Substring(6));	0
23676045	20564286	Entity Framework 6 multiple table to one foreign key relationship code first	public virtual parentbase {get;set;}.	0
167178	167129	C# - IEnumerable to delimited string	var delimitedString = selectedValues.Aggregate((x,y) => x + ", " + y);	0
21412874	21412821	Can't insert date because of conversion	ItemName   ImageIndex  DateEntery   Index0   ItemBarcode\n@ItemName  GETDATE()   @ImageIndex  @Index0  @ItemBarcode\n           ^           ^	0
21259955	21238624	Save and Load pictures windows 8 app	ms-appdata:///local/dfds.jpg	0
34386724	34385984	Roslyn to ignore subtrees	base.Visit	0
33718770	33706864	Japanese characters with MigraDoc/PDFsharp	document.Styles[StyleNames.Normal].Font.Name = "Arial Unicode MS";	0
3530581	3530534	How can I pass additional parameters to predicate functions?	public Comparison<T> MakeComparison<T>(object extraParameter)\n{\n    return\n        delegate(T x, T y) \n        {\n            // do comparison with x, y and extraParameter\n        }\n}	0
6611910	6611324	Send mail using GMail SMTP	inner exception	0
21570918	21570354	Ajax ModalPopUp Window according to certain conditions	protected void ButtonSave_Click(object sender, EventArgs e)\n    {\n     if (MyCondition == true)\n        {           \n           modalPopUpConfirmation.Show();\n        }\n     else\n        {            \n            Label1.Text = "The condition was false, so no modal popup!";\n        }\n    }	0
5350618	5350590	Best way to separate two base64 strings	[0-9a-zA-Z/=+]	0
14461307	14461236	Failed to bind the combobox in datagrid	ItemsSource="{Binding Path=Order.PartsList}"	0
22411125	22266833	Windows Phone crop view	PixelHeight\nPixelWidth	0
18870734	18870604	Storing values of multiple dynamic textboxes to array	string[] values = txtbox.Select(x => x.Text).ToArray();	0
6320349	6320250	Get a RETURN from a Invoke method	public static string readListBoxSelected(ListBox listbox)\n    {\n        if (listbox.InvokeRequired)\n        {\n            return (string)listbox.Invoke(\n              new Func<String>(() => readListBoxSelected(listbox))\n            );\n        }\n        else\n        {\nif(istbox.SelectedValue != null)\n\n            return  listbox.SelectedValue.ToString();\nelse\nreturn String.Empty\n        }\n        }	0
8213716	8213499	Required Field Validators	public class FooModel{\n\n        [Required]\n        [DataType(DataType.Date)]\n        [DisplayFormat(DataFormatString = "{0:MM/dd/yyyy}"]\n        public DateTime RequestedStartDate{\n             get; set;\n        }\n\n        [Required]\n        public decimal RequestedPayRate{\n             get; set;\n        }\n }	0
19001858	19001423	Getting path of a to the parent folder of the Solution file C#	string startupPath = Path.Combine(Directory.GetParent(System.IO.Directory.GetCurrentDirectory()).Parent.Parent.Parent.FullName,"abc.txt");\n\n   // Read the file as one string. \n   string text = System.IO.File.ReadAllText(startupPath);	0
13593590	12660077	Display a StorageFile in Windows 8 Metro C#	public async Task<Image> GetImageAsync(StorageFile storageFile)\n{\n        BitmapImage bitmapImage = new BitmapImage();\n        FileRandomAccessStream stream = (FileRandomAccessStream)await storageFile.OpenAsync(FileAccessMode.Read);\n        bitmapImage.SetSource(stream);\n        Image image = new Image();\n        image.Source = bitmapImage;\n        return image;\n}	0
20646091	20640538	What is the simplest way to execute a parallel, for loop as a low-priority, CPU operation?	Process currentProcess = Process.GetCurrentProcess();\nProcessPriorityClass oldPriority = currentProcess.PriorityClass;\n\ntry\n{\n    currentProcess.PriorityClass = ProcessPriorityClass.BelowNormal;\n\n    int i = 0;\n    ThreadSafeRNG r = new ThreadSafeRNG();\n    ParallelOptions.MaxDegreeOfParallelism = 4; //Assume I have 8 cores.\n    Parallel.For(0, Int32.MaxValue, (j, loopState) => \n    {\n        int k = r.Next();\n        if (k > i) k = i;\n    }\n}\nfinally\n{\n    //Bring the priority back up to the original level.\n    currentProcess.PriorityClass = oldPriority;\n}	0
17331286	17330570	Putting dynamic string parameter in drop down menu server controls	SqlDataSource1.SelectParameters["PointPerson"].DefaultValue = "User";	0
21321253	21321215	How do i get StartPosition location?	label5.text = this.Location.X + "," + this.Location.Y;	0
4832329	4828662	Linq-to-SQL complex custom object from SP	from x in dataContext.StoredProc("", "", "")\nselect new Rota {\n    DisplayOrder = x.DisplayOrder,\n    StartingTime = x.StartingTime,\n    FinishTime = x.FinishTime,\n    Employee = new Employee {\n        EmployeeId = x.EmployeeId,\n        Name = x.EmployeeName\n    }\n}	0
23781044	23779854	Keep ASP.NET Calender Open On Month Click	protected void ClanderDOI_VisibleMonthChanged(object sender, MonthChangedEventArgs e)\n{\n    ClanderDOI.Visible = true;\n}	0
682078	681770	How to programmatically get SVN revision description and author in c#?	using(SvnClient client = new SvnClient())\n{\n    Collection<SvnLogEventArgs> list;\n\n    // When not using cached credentials\n    // c.Authentication.DefaultCredentials = new NetworkCredential("user", "pass")l\n\n    SvnLogArgs la = new SvnLogArgs { Start = 128, End = 132 };\n    client.GetLog(new Uri("http://my/repository"), la, out list);\n\n    foreach(SvnLogEventArgs a in list)\n    {\n       Console.WriteLine(string.Format("=== r{0} : {1} ====", a.Revision, a.Author));\n       Console.WriteLine(a.LogMessage)\n    }\n}	0
30822983	30822958	How to automatically update the database on application start up?	internal class Configuration : DbMigrationsConfiguration<YourContext>\n{\n    public Configuration()\n    {\n        this.AutomaticMigrationsEnabled = true;\n        this.AutomaticMigrationDataLossAllowed = false;\n    }	0
21378174	21378040	Return array of 'this' in C#	public abstract class MyBaseClass<T> : where T : MyBaseClass<T>\n{\n    public abstract T[] Search(string search);\n}\n\npublic class DerivedClass : MyBaseClass<DerivedClass>\n{\n    public override DerivedClass[] Search(string search)\n    {\n        return new DerivedClass[0];\n    }\n}	0
15797035	15796761	Change DateFormatString to show 11:59:59 as opposed to 12:00:00	auctionEnd = auctionEnd.AddSeconds(-1);	0
6818577	6818481	Usercontrol with different aspx, but same implementation	// base class with common functionality\npublic class MyUserControlBase : UserControl {\n    // derived class will initialize this property\n    public TextBox TextBox1 {get;set;}\n    // derived class will initialize this property\n    public Button Button1 {get;set;}\n\n    /* some code of usercontrol */\n}\n\n/* ... elsewhere ... */\n// final class with *.aspx file\npublic class MyUserControlA : MyUserControlBase {\n    protected override OnInit(EventArgs e) {\n        // "this.txtUrl" is generated from *.aspx file\n        this.TextBox1 = this.txtUrl;\n        // "this.btnSubmit" is generated from *.aspx file\n        this.Button1 = this.btnSubmit;\n    }\n}\n\n/* ... elsewhere ... */\n// final class with *.aspx file\npublic class MyUserControlB : MyUserControlBase {\n    protected override OnInit(EventArgs e) {\n        // "this.txtTitle" is generated from *.aspx file\n        this.TextBox1 = this.txtTitle;\n        // "this.btnOk" is generated from *.aspx file\n        this.Button1 = this.btnOk;\n    }\n}	0
24236257	24236004	How to read a CSV file from FTP using C#	FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();\n//use the response like below\nStream responseStream = response.GetResponseStream();\nStreamReader reader = new StreamReader(responseStream);\nstring[] allLines = reader.ReadToEnd().Split(Environment.NewLine.ToCharArray(), StringSplitOptions.RemoveEmptyEntries);	0
3637243	3637227	Linq Where value is in Array	var someData = from p in returns   \n               from d in p.ReturnDet   \n               where p.Year > 2009  \n               where periods.Contains(d.Period);	0
8819771	8819716	How to access value of usercontrol in asp.net	TimePeriod ib = (TimePeriod)LoadControl("TimePeriod.ascx");\nstring timeTo = ib.TimeTo;\nstring timeFrom = ib.TimeFrom;	0
22112750	22095209	How can I refresh the application by clicking on the button?	private void button1_Click(object sender, EventArgs e)\n{\n    this.Controls.Clear();\n    InitializeComponent();\n    //the code you wrote in the button click or if the code is in another button write:\n    // button.PerformClick();\n}	0
21263934	21263810	Is my logic correct? I'm trying to do a simple search from a database	string strPatient = "SELECT * FROM PATIENT WHERE patientID= (" +  strRFID+")" ;	0
8105384	8105370	How to find similar words in two strings in c#	foreach (string t1 in term1.split(' '){\n\nforeach (string t2 in term2.split(' '){\n\nif (Stemmer.Stem(t1).equals(Stemmer.Stem(t2)){\n\n//do whatever here\n\n}\n\n}    \n\n    }	0
34402984	34402523	How to create an iterator based on another collection	var externalUsers = users.Select(user => externalUserIds.Contains(user.UniqueKey));	0
20730514	20730469	C# checkboxlist with enum	Mangment enumValue = (Mangment)Enum.Parse(typeof(Mangment), itemChecked.ToString(), true)	0
17356502	17336367	How to Add Footers to Documents in Odd Pages and Even Pages	1> 0 implies false and -1 true so use .PageSetup.OddAndEvenPagesHeaderFooter = -1\n\n2> use WdHeaderFooterIndex.wdHeaderFooterEvenPages to access footer on even page\n\n3> use WdHeaderFooterIndex.wdHeaderFooterFirstPage to access footer on odd page	0
27354482	27354198	How can I check so that if any elements relate to the if the foreach would set it instead of later going to the else?	FallSpeed = 3;\n  isTouchingGround = false;\n\n  if(GrassList.Any(\n      grass => grass.Rect.X - 32 <= Rect.X &&\n               grass.Rect.X + 32 >= Rect.X && \n               grass.Rect.Y - 65 <= Rect.Y))\n  {\n     FallSpeed = 0;\n     isTouchingGround = true;\n  }	0
9695474	9695073	How to Find toolstripButton inside toolstrip in a UserControl	var toolstrip1 = this.userControlCommonTask1.Controls.Find("toolstrip1", true);\n        var toolstrip1Items = toolstrip1[0] as ToolStrip; <-- set to toolstrip control\n\n        var btnRead = toolstrip1Items.Items.Find("btnRead", true); <--get BtnRead on toolstrip Item.Find\n        btnRead[0].Enabled = false; <--disable/Enable btn	0
18077469	18077125	Conditional Split String with multiple delimiters	string astring=@"#This is a Section*This is the first category*This is the second Category# This is another Section";\n\nstring[] sections = Regex.Matches(astring, @"#([^\*#]*)").Cast<Match>()\n    .Select(m => m.Groups[1].Value).ToArray();\nstring[] categories = Regex.Matches(astring, @"\*([^\*#]*)").Cast<Match>()\n    .Select(m => m.Groups[1].Value).ToArray();	0
20602936	20602921	How to select Distinct names from a xml database using LINQ?	var queryAllCustomers = (from cust in loadedCustomData.Descendants("record")\n                            select (string)cust.Element("City")).Distinct();	0
21678650	21678585	C# FileBrowserDialog and a write-protected Folder	try\n{\n   config.Save(@userConfigurePath);\n}\ncatch(Exception ex)\n{\n   MessageBox.Show("Sorry there was en error with writing file. Try different location");\n}	0
15933605	15932521	Kendo grid binding with code-first model	return Json(context.SomeDBSet.Select( e => new { e.X, ....  e.Id}).ToDataSourceResult(request));	0
6126428	6126344	Refresh DataGrid in WPF	Datagrid.Items.Refresh()	0
22873981	22873949	C# split a textfile in two different listbox where initial lines of textfile appears in listbox1 and others appears in listbox2	int lineNum = 1;\n\nforeach (string line in System.IO.File.ReadAllLines(myFilePath))\n{\n    if (lineNum <= 100)\n    {\n        listBox1.Items.Add(line);\n    }\n    else\n    {\n        listBox2.Items.Add(line);\n    }\n\n    lineNum++;\n}	0
17304771	17304396	Inserting results from one table to another with consecutive dates for each inserted row	INSERT INTO Invitations (PatientId, PlanId, [Time])\nSELECT TOP 10 \n  Patients.Id, \n  @PlanId, \n  DATEADD(MINUTE,(ROW_NUMBER() OVER (ORDER BY Patients.Id) -1) * 5 ,@InitialTime ) AS [Time]\nFROM Patients	0
15643092	15643068	A lot of fields with the same attribute	[SameAttribute]	0
2732078	2732063	Disposables, Using & Try/Catch Blocks	try\n{\n   FileStream fs = null;\n   try\n   {\n       fs = File.Open("Foo.txt", FileMode.Open);\n       // Do stuff\n   }\n   finally\n   {\n       if (fs != null)\n       {\n           fs.Dispose();\n       }\n   }\n}\ncatch(Exception)\n{\n   /// Handle Stuff\n}	0
9884712	9884642	Merging records from multiple rows in table sql server	create table #temp\n(\n  resNo int,\n  subres int,\n  enddate datetime,\n  primary key (resNo, subres)\n)\n\n-- Store the values you need for enddate in a temp table\ninsert into #temp\nselect resNo, \n       subres,\n       max(enddate) as enddate\nfrom t_resourcetable\ngroup by resNo, subres\n\n-- Delete duplicates keeping the row with min startdate\ndelete T\nfrom (\n        select row_number() over(partition by resNo, subres order by startdate) as rn\n        from t_resourcetable\n     ) as T\nwhere rn > 1\n\n-- Set enddate where needed\nupdate T set enddate = tmp.enddate\nfrom t_resourcetable as T\n  inner join #temp as tmp\n    on T.resNo = tmp.resNo and\n       t.subres = tmp.subres\nwhere T.enddate <> tmp.enddate\n\ndrop table #temp	0
33033554	33029448	C# Convert HtmlString into HTMLDocument	HTMLDocument doc = new HTMLDocument();\n  IHTMLDocument2 doc2 = (IHTMLDocument2)doc;    \n\n  doc2.write(fileText);	0
24642289	24412200	Send Json Array from Android Device to Mobile Azure Services backend javascript not working	JsonArray jArray = new JsonArray();\n\nContact c1 = new Contact();\nc1.ContactNO = "123455";\nc1.Name = "Test";\n\nGson gson = new Gson();\njArray.add(gson.toJsonTree(c1));\nContact c2 = new Contact();\nc2.ContactNO = "23455";\nc2.Name = "test2";\njArray.add(gson.toJsonTree(c2));\n\nmClient.invokeApi("uploadContacts", jArray, new ApiJsonOperationCallback() {\n        @Override\n        public void onCompleted(JsonElement jsonElement, Exception e, ServiceFilterResponse serviceFilterResponse) {	0
13986165	13986077	Connection string to Database Application	Server=myServerAddress;Database=myDataBase;User Id=myUsername;Password=myPassword;	0
15312896	15312285	Saving a Date in Excel from Datepicker	for (int i = 0; i < dataGridView1.Rows.Count - 1; i++)\n{\n    for (int k = 0; k < dataGridView1.Columns.Count; k++)\n    {\n        worksheet.Cells[i + 2, k + 1] = dataGridView1.Rows[i].Cells[k].Value.ToString();\n        worksheet.Cells[i + 2, k + 1].NumberFormat = "dd/mm/yyyy"\n    }\n}\n\nworkbook.Save();	0
14855094	14854787	Knockout Validation on a dynamic form	ko.observable().extend({ required : {message : 'Should not be empty', \n    onlyIf: [viewModel.Observable bound to checkbox]}});	0
25435152	25435025	Exclude two times gaps from IF statment	if (now >= dend || now <= start  || (now >= end  && now < dstart))\n   {\n      //skip\n   }\nelse\n   {\n      //Do something\n   }	0
20176045	20175941	How to put a minimum requirement number for it to write the word	if (textBox2.Text == "1")\n{\n    textBox2.Text += " Animal";\n}\nif (textBox3.Text == "1"\n{\n    textBox3.text += " Person";\n}\nif (!textBox2.Text.EndsWith(" Animals") && !textBox2.Text.EndsWith(" Animal"))\n    textBox2.Text += " Animals";\nif (this.textBox2.Text != "")\n{\n    listBox1.Items.Add(this.textBox2.Text);\n}\nif (!textBox3.Text.EndsWith(" People") && !textBox3.Text.EndsWith(" Person"))\n    textBox3.Text += " People";\nif (this.textBox3.Text != "")\n{\n    listBox1.Items.Add(this.textBox3.Text);\n}	0
16149964	16149153	Getting Values of other Series through tooltip	foreach (var o in ListObjOfThatClass)\n{\n    var p1 = new DataPoint();\n    p1.SetValueXY(o.Id, o.Count1);\n    p1.ToolTip = string.Format("{0}", o.Count2);\n    Chart1.Series[0].Points.Add(p1);\n\n    var p2 = new DataPoint();\n    p2.SetValueXY(o.Id, o.Count2);\n    Chart1.Series[1].Points.Add(p2);\n}	0
30184552	30184204	Trying to populate textbox and listview from txt file	string[] items = reader.ReadLine().Split('\t');\nforeach (var item in items)\n{\n    var listViewItem = new ListViewItem(item);\n    transactionList.Items.Add(listViewItem);    \n}	0
11467875	11467688	How to define hyperlink click event on the fly?	protected void RadGrid1_ItemDataBound(object sender, GridItemEventArgs e)\n{\n    if (e.Item is GridDataItem)\n    {\n        LinkButton link = (LinkButton)gridDataItem["ContentTitle"].Controls[0];\n        link.Click += dummyBtn_Click;\n    }\n}\n\nprotected void dummyBtn_Click(object sender, EventArgs e)\n{\n    Response.Write("dummyBtn_Click");\n}	0
23953924	23952233	C# - DateTime.Parse from string not working	DateTime startDate = DateTime.ParseExact(strDate, "G", CultureInfo.InvariantCulture);	0
10645387	10645367	String not recognized as valid datetime	DateTime.ParseExact(dtm.Text.Trim(), "dd/M/yyyy", System.Globalization.CultureInfo.InvariantCulture)	0
465353	465318	How to implement events through interface in C#?	public interface IFoo\n{\n    event EventHandler Boo;\n}\n\nclass Foo : IFoo\n{\n    public event EventHandler Boo;\n    public void RaiseBoo()\n    {\n        if (Boo != null)\n            Boo(this, EventArgs.Empty);\n    }\n}\n\n...\n\nprivate void TestClass_Boo(object sender, EventArgs e)\n{\n    throw new NotImplementedException();\n}\n\n    ...\n\n   object o = new Foo();\n   ((IFoo)o).Boo += TestClass_Boo;\n   ((Foo)o).RaiseBoo();	0
8681373	8554448	convert 8 bit color bmp image to 8 bit grayscale bmp	Private Function GetGrayScalePalette() As ColorPalette  \n    Dim bmp As Bitmap = New Bitmap(1, 1, Imaging.PixelFormat.Format8bppIndexed)  \n\n    Dim monoPalette As ColorPalette = bmp.Palette  \n\n    Dim entries() As Color = monoPalette.Entries  \n\n    Dim i As Integer \n    For i = 0 To 256 - 1 Step i + 1  \n        entries(i) = Color.FromArgb(i, i, i)  \n    Next \n\n    Return monoPalette  \nEnd Function	0
18443848	18438924	How to submit changes in LinqPad	void Main()\n{\n    var p1 = Person.Single(x => x.Id == 1);\n    p1.Name = "Test";\n    SaveChanges();\n}	0
10052281	10052108	How to get selected radio button text in datalist ?	protected void DataList1_OnItemCommand(object sender, DataListCommandEventArgs e)\n{\n if (String.Equals(e.CommandName, "Validate"))\n {\n  DataListItem dataItem = (DataListItem )e.Item;\n  RadioButton rbtn1 = (RadioButton)dataItem.FindControl("RadioButton1");\n  RadioButton rbtn2 = (RadioButton)dataItem.FindControl("RadioButton2");\n  RadioButton rbtn3 = (RadioButton)dataItem.FindControl("RadioButton3");\n  RadioButton rbtn4 = (RadioButton)dataItem.FindControl("RadioButton4");\n\n  // Code to check which radio button was checked.\n  if(rbtn1 != null && rbtn1.Checked)\n  {\n\n  }\n  else if(rbtn2 != null && rbtn2.Checked)\n  {\n\n  } //Perform these for the remaining two check boxes\n }\n}	0
27248209	27248085	SensorCore with CameraCaptureTask	protected override async void OnNavigatingFrom(NavigatingCancelEventArgs e) \n{\n    await _stepCounter.DeactivateAsync(); \n}	0
34135906	34135748	Entity Framework - Update/add value to existing value	context.repository.Update(e => e.id == id, e2 => new entity { quantity = e2.quantity + moreQuantity });	0
20036355	19696450	New Record from Current Rec	private void BindingSource1_AddingNew(object sender, AddingNewEventArgs e)\n        {\n  if(need_insert_from_Current)\n                {\n                BindingSource bs =(BindingSource)sender;\n                DataRowView cur = (DataRowView)bs.Current;\n                DataView dv=(DataView)bs.List;\n                DataRowView drv=dv.AddNew();\n                // Collect data from current rec (except from the 1st value (Id is Identity !)\n                for (int i = 1; i <= dv.Table.Columns.Count-1; i++)\n                {\n                    drv.Row[i] = cur.Row[i];\n                }\n                bs.Position = bs.Count - 1;\n                e.NewObject = drv;\n                need_insert = true;\n                need_insert_from_Current=false;\n                }\n        }	0
3553056	3552906	editing a line in a text file without using pointers?	var lines = File.ReadAllLines(filePath);\nforeach (change to make)\n{\n    for (int i = 0; i < lines.Length; i++)\n    {\n        // read values from line\n        if (need_to_modify)\n        {\n            // whatever change logic you want here.\n            lines[i] = lines[i].Replace(...);\n        }\n    }\n}\nFile.WriteAllLines(filePath, lines);	0
18983103	18893051	how to set cursor position in cell of grouping grid of syncfusion?	private void grd_TableControlCurrentCellChanged(object sender, GridTableControlEventArgs e)\n{\n   GridDropDownGridListControlCellRenderer cr = \n      gcc.Renderer as GridDropDownGridListControlCellRenderer;\n          if (cr != null)\n          {\n              cr.TextBox.SelectionStart = cr.TextBox.TextLength;\n              cr.TextBox.SelectionLength = 0;\n          }\n}	0
9420496	9420454	c# Quick way to undef all parameters	public class SomeClass\n{\n   public double jTime;\n   ...\n}\n\n...\n\nSomeClass sc = new SomeClass();\nsc.jTime = 1;\nsc = new SomeClass();	0
1734158	1734142	populating listbox	var records = from line in File.ReadAllLines(@"D:\file.txt")\n              let parts = line.Split(';')\n              select new \n              {\n                  Company = parts[0],\n                  Identification = parts[2]\n              };\nlistBox1.DataSource = records;\nlistBox1.DisplayMember = "Company";\nlistBox1.ValueMember = "Identification";	0
3347431	3347376	Text file to store data	StreamWriter sw = null;\nFileInfo fi = new FileInfo(Path.Combine(Application.StartupPath, "filename.txt"));\n\nif(fi.Exists)\n    sw = new StreamWriter(fi.Open(FileMode.Open));	0
24846062	24846010	c# Show image database for each usercontrol	private BitmapImage byteToImage(byte[] array)\n    {\n        BitmapImage img = null;\n\n        if (array != null && array.Length > 0)\n        {\n            using (MemoryStream stream = new MemoryStream(array))\n            {\n                stream.Position = 0;\n                img.BeginInit();\n                img.CreateOptions = BitmapCreateOptions.PreservePixelFormat;\n                img.CacheOption = BitmapCacheOption.OnLoad;\n                img.UriSource = null;\n                img.StreamSource = stream;\n                img.EndInit();\n            }\n            img.Freeze();\n        }\n\n        return img;\n    }	0
3953729	3953651	How can I reduce boilerplate in my properties using attributes?	private void SetField<T>(\n    ref T field, T value,\n    string key, EventHandler handler)\n{\n    if(EqualityComparer<T>.Default\n        .Equals(field, value)) return;\n    field = value;\n    if(handler!=null) handler(this, EventArgs.Empty);\n    if(key!=null) Update(key,value);\n}\npublic int Foo {\n    get { return foo; }\n    set { SetField(ref foo, value, FooKey, FooChanged); }\n}	0
27099717	27099642	'object reference not set to an instance of an object' , while setting backColor to the node of tree in c#?	node.Style = new Style(); // You can replace here with whatever type of object is style.\nnode.Style.BackColor = Color.Red;	0
20281400	20281361	How to replace placeholders using string.Format() with variable args	this.Text = this.Text.FormatWith(this.TextArguments.ToArray<string>())	0
3312334	3312068	Popup Window will not Close	var PopupWnd = null; function\nShowPopup(){\n     PopupWnd = window.open('Popup.aspx','PopupWindow','');\n} \nfunction HidePopup(){\n    if(PopupWnd != null){\n        if(!PopupWnd.closed){\n            PopupWnd.close();\n        }\n    }\n }	0
22212569	22211473	Exporting Excel Charts as Images	Dim co As ChartObject, sht As Worksheet, x As Long\nx = 1\nSet sht = ThisWorkbook.Sheets("Sheet1")\nFor Each co In sht.ChartObjects\n    Application.Goto co.TopLeftCell, True\n    co.Chart.Export "C:\_stuff\test\chart" & x & ".jpg", "JPG", False\n    x = x + 1\nNext co	0
31890369	31890207	How to fetch files from a directory based on condition	FileInfo[] fi;\nDirectoryInfo di= new DirectoryInfo(@"C:\src_folder");\n\nDateTime beginning = DateTime.UtcNow.AddDays(-30);\nfi = di.GetFiles("*.jpeg")\n       .Where(file => file.CreationTimeUtc < beginning)\n       .ToArray();	0
7690673	7690457	How to convert this to an image to store in SQL	byte[] encData_byte = new byte[data.Length];\nencData_byte = System.Text.Encoding.UTF8.GetBytes(data);    \nstring encodedData = Convert.ToBase64String(encData_byte);\nreturn encodedData;	0
13453486	13453054	ChildWindow Close button event handler executes multiple times if it fast clicked many times	((Button)sender).IsEnabled=false;	0
10504080	10503978	On Idle Hide Mouse System-Wide, Show on Movement, from a C# Application	private Timer t;\nvoid OnLoad(object sender, EventArgs e)\n{\n    t = new Timer();\n    t.Interval = 5000;\n    t.Tick += new EventHandler(t_Tick);\n}\n\nprivate bool _hidden = false;\n\nvoid t_Tick(object sender, EventArgs e)\n{\n    if(!_hidden)\n    {\n         Cursor.Hide();\n         t.Interval = 500;\n    }\n    else\n    {\n         if(--some parameter---)\n              Cursor.Show();\n    }\n}	0
26937303	26935284	Sitecore asp.net Edit Custom User Profile Properties	User.FromName(username, true)	0
25119585	25118789	How to cache data from repository call	private readonly CacheManager cacheManager = new CacheManager(); \n          // or injected via ctor\n\npublic IEnumerable<Task> GetTasks()\n{\n    return this.cacheManager.Get("Tasks", ctx => this.taskRepository.GetAll());\n}\n\npublic void AddTask(Task task)\n{\n    this.taskRepository.Create(task);\n    /// other code\n\n    // we need to tell the cache that it should get fresh collectiion\n    this.cacheManager.Signal("Tasks"); \n}	0
22454443	22454335	Invoking Generic Method with the parameter of IEnumerable<T>	DataTable datatable = Tools.LinqToDataTable(list.ToList());	0
384896	384871	Building an assembler	nothing\n[label] [instruction] [comment]\n[label] [directive] [comment]	0
26571818	26571105	MongoDB - how to deserialize collection to List<Dictionary<string, object>>	var result = JsonConvert.DeserializeObject<Dictionary<string, object>>(json);	0
1881569	1881475	Hide a row in a datagridview (WinForms/C#)	((DataTable)dataGridView1.DataSource).DefaultView.RowFilter = "foo = bar";	0
4812748	4812390	Cant reference from any objects?	public class Test\n{\n    public void Foo()\n    {\n        Testing MyTesting = new Testing();\n        Testing_Class MyTestingClass = new Testing_Class();\n        MyTesting.A(); \n    }\n}	0
27375418	27373796	How to validate duplicate Entries in EF4 while Editing	var CityCheck = context.Cities.Where(u => u.CityName == city.CityName && u.ContId == city.ContId).FirstOrDefault();        \nif(CityCheck != null)\n    {\n         var CityCurrent = context.Cities.Where(t=> t.CityId == city.CityId && t.CityName == city.CityName).FirstOrDefault();\n         if (CityCurrent != null)\n         {\n             return RedirectToAction("Index");\n         }\n         else\n         {\n             ModelState.AddModelError("CityName", "City name already exists.");\n         }\n     }\n     else\n         {\n             context.Entry(city).State = EntityState.Modified;\n         }\n     if(ModelState.IsValid)\n         {  \n             context.Entry(city).State = EntityState.Modified;\n             return RedirectToAction("Index");\n         }\n    ViewBag.PossibleCountries = context.Countries.Where(f => f.IsActive == true && f.IsDeleted == false).ToList();\n\n    return View(city);\n\n    }	0
17686910	17365572	Why am I getting NullReferenceException when anonymous method uses a variable declared elsewhere?	public static string imagesDirectory = string.Empty;	0
13517740	13517700	How to convert Monthly calendar in c# to persain calendar	System.Globalization.PersianCalendar p = new System.Globalization.PersianCalendar();\nDateTime date = DateTime.Today;\nint year = p.GetYear(date);\nint month = p.GetMonth(date);\nint day = p.GetDayOfMonth(date);\nDateTime d1 = new DateTime(year, month, day);	0
10668247	10668194	Is there a C# equivalent of PHP's array_key_exists?	using System.Collections.Generic;\n...\nDictionary<int, int> dict = new Dictionary<int, int>();\ndict.Add(5, 4);\ndict.Add(7, 8);\nif (dict.ContainsKey(5))\n{\n    // [5, int] exists\n    int outval = dict[5];\n    // outval now contains 4\n}	0
15404639	15404603	Show data from Database in Datagridview	BindingSource binding = new BindingSource(); //req. by win forms\n DataTable dt = new DataTable();\n dt.Load(sql_command.ExecuteReader());	0
22354432	22353985	How to show progress indicator in System Tray for few seconds without using await [Windows Phone 8]	SystemTray.ProgressIndicator = new ProgressIndicator();\nSystemTray.ProgressIndicator.IsVisible = true;\nSystemTray.ProgressIndicator.Text = "Data is up-to-date";\n\nDispatcherTimer timer = new DispatcherTimer();\ntimer.Interval = TimeSpan.FromMilliseconds(2000);\n\ntimer.Tick += (sender, args) =>\n{\n    SystemTray.ProgressIndicator.IsVisible = false;\n    timer.Stop();\n};\n\ntimer.Start();	0
4167620	4164115	How to get focus to the treeview node with txt extension on closing or hiding subform	public Form1()\n{\n    InitializeComponent();\n    FindNode(treeView1.Nodes, ".txt");\n    this.ActiveControl = treeView1;\n}  \n\nbool found = false;\npublic void FindNode(TreeNodeCollection nodeCollection, string TextToFind)\n{\n   foreach (TreeNode node in nodeCollection)\n   {\n       if (found)\n          continue;\n       if (node.Text.Contains(TextToFind))\n       {\n          treeView1.SelectedNode = node;\n          TreeNode parentNode = node.Parent;\n          while (parentNode != null)\n          {\n              parentNode.Expand();\n              parentNode = parentNode.Parent;\n          }\n          found = true;\n          break;\n       }\n       FindNode(node.Nodes, TextToFind);\n    }\n}	0
16658451	16619523	IFrame Request with SessionID and Response of Secure Session Token	ShortGuid sessionID = ShortGuid.NewGuid ();\nSession.Add (sessionID.ToString (), "asdasdasdasd");\nstring encodedURL = Convert.ToBase64String (Encoding.Unicode.GetBytes (HttpContext.Current.Request.Url.PathAndQuery));  \n\nWebClient client = new WebClient ();\nNameValueCollection data = new NameValueCollection ();\n\ndata.Add ("UserName", "asdasd");\ndata.Add ("Password", "asdasd");\ndata.Add ("CustNumber", "asdasdasd");\ndata.Add ("Amount", "21231313");\ndata.Add ("SessionId", sessionID.ToString ());\ndata.Add ("UserDeclinedURL", encodedURL);\ndata.Add ("UserApprovedURL", encodedURL);\ndata.Add ("ServerURL", encodedURL);\n\n\nstring response = System.Text.Encoding.UTF8.GetString (client.UploadValues ("URL", data));	0
15021652	15002338	Find all files that differ from shelveset?	var shelvesetOld = vcs.QueryShelvesets("shelveset_old", null).FirstOrDefault();\nvar shelvesetOldChanges = vcs.QueryShelvedChanges(shelvesetOld)[0].PendingChanges;\n\nvar shelvesetNew = vcs.QueryShelvesets("shelveset_new", null).FirstOrDefault();\nvar shelvesetNewChanges = vcs.QueryShelvedChanges(shelvesetNew)[0].PendingChanges;\n\nvar differences = new List<PendingChange>();\nforeach (var oldChange in shelvesetOldChanges) {\n    var shelvesetNewChange = shelvesetNewChanges.FirstOrDefault(shelvesetChangeSearch => shelvesetChangeSearch.ServerItem.Equals(oldChange.ServerItem));\n    if (shelvesetNewChange == null) {\n        differences.Add(oldChange);\n        continue;\n    }\n\n    if (!shelvesetNewChange.UploadHashValue.SequenceEqual(oldChange.UploadHashValue)) {\n        differences.Add(oldChange);\n    }\n}	0
1842234	1841956	How can I make a WPF ToolTip appear faster with ToolTipService.Duration?	ToolTipService.SetInitialShowDelay(tb, 10);	0
3547365	3547294	ASP.NET MVC string formatting c# - by 100 characters make 4 rows each 25 characters	s = Regex.Replace(s, "(.{25})", "$1<br/>");	0
6244989	6244946	How to Delete a Specific Line in a Text File?	using (var reader = File.OpenText(orgFileName))\nusing (var writer = File.CreateText(tmpFileName))\n{\n    while (true)\n    {\n       string line = reader.ReadLine();\n       if (line == null)\n         break; // done\n\n       // logic to analyze / track content\n\n       if ( Is_special_line)\n       {\n          // do something, or maybe nothing (skip)\n       }\n       else\n       {\n          writer.WriteLine(line);\n       }\n    }\n}\n\nFile.Delete(orgFilename);\nFile.Rename(tmpFilename, orgFilename);	0
18272825	18270508	how to properly nest config-sections config-elements?	...\n[ConfigurationCollection(typeof(LoggerRegistration), AddItemName = "LoggerRegistration")]\npublic class LoggerRegistrations : ConfigurationElementCollection\n{\n...\n.\n...\n[ConfigurationCollection(typeof(LogMapperElement), AddItemName = "LogMapper")]\npublic class LogMappers : ConfigurationElementCollection\n...	0
4070729	4069533	How do I make a virtual node using MPF?	public override object GetIconHandle(bool open)\n    {\n        return ProjectMgr.ImageHandler.GetIconHandle(open ? (int)ProjectNode.ImageName.OpenFolder : (int)ProjectNode.ImageName.Folder);\n    }	0
29251335	29170814	Mocking a generic protected method	var getSomething = typeof(BaseClass)\n       // get GetSomething<T> using reflection\n       .GetMethod("GetSomething", BindingFlags.NonPublic | BindingFlags.Static) \n       // make it into GetSomething<Response>\n       .MakeGenericMethod(typeof(Response)); \n\n// and arrange\nMock.NonPublic.Arrange<bool>(method,\n        ArgExpr.IsAny<HttpWebRequest>(),\n        ArgExpr.Out(successfullLoginResponse))\n   .Returns(true);	0
21643397	21643281	listbox navigation to a new page and displaying data in details in the navigated page in windows phone 7 application	Newss news = listBox1.SelectedItem as Newss;\nNavigationService.Navigate(new Uri("/NewsDetails.xaml?News_Title=" + news.News_Title + "&News_Description=" + news.News_Description + "&image_path=" + news.image_path, UriKind.Relative));	0
15484227	15465871	How do I make a GIF repeat in loop when generating with BitmapEncoder	BitmapPropertySet properties = await encoder.BitmapProperties.GetPropertiesAsync("/appext/Data");\nproperties = new BitmapPropertySet()\n{\n    {\n        "/appext/Application",\n        new BitmapTypedValue(Iso8859.Default.GetBytes("NETSCAPE2.0"), Windows.Foundation.PropertyType.UInt8Array)\n    },\n    { \n        "/appext/Data",\n        new BitmapTypedValue(new byte[] { 3, 1, 0, 0, 0 }, Windows.Foundation.PropertyType.UInt8Array)\n    },\n};\n\nawait encoder.BitmapProperties.SetPropertiesAsync(properties);	0
9770784	9770522	How to handle Message Boxes while using webbrowser in C#?	public class Foo\n{\n    [DllImport("user32.dll", SetLastError = true)]\n    static extern IntPtr FindWindowEx(IntPtr hwndParent, IntPtr hwndChildAfter, string lpszClass, string lpszWindow);\n\n    [DllImport("user32.dll", EntryPoint = "FindWindow", SetLastError = true)]\n    private static extern IntPtr FindWindow(string lpClassName, string lpWindowName);\n\n    [DllImport("user32.dll", CharSet = CharSet.Auto)]\n    static extern IntPtr SendMessage(IntPtr hWnd, UInt32 Msg, IntPtr wParam, IntPtr lParam);\n\n\n    private void ClickOKButton()\n    {\n        IntPtr hwnd = FindWindow("#32770", "Message from webpage");\n        hwnd = FindWindowEx(hwnd, IntPtr.Zero, "Button", "OK");\n        uint message = 0xf5;\n        SendMessage(hwnd, message, IntPtr.Zero, IntPtr.Zero);\n    }\n}	0
6603722	6602890	How can I make this SelectMany use a Join?	customer.CustomerOrders	0
15975287	15975230	C# List of arrays to array of arrays	test = coordinates.ToArray();	0
24056317	24056302	Get the first and second objects from a list using LINQ	var topTwo = People.Where(a => a.Age > 18).Take(2).ToArray();\n\nPerson p1, p2;\nif (topTwo.Any())\n{\n   p1 = topTwo[0];\n   if (topTwo.Count > 1)\n       p2 = topTwo[1];\n}	0
8918608	8914938	DataGridView BindingDataSource with a Foreign Key	var selectedItem = datagridviewinstance.SelectedRows[x].DataBoundItem as YourTypeHere\nvar data = (from a in SOMETHING where fk == selectedItem.ForeignKeyProperty select a);\ntextbox1.Text = data.text;	0
29094317	29093694	Remove Double quote from json Data	var dataSet2 = [
\n  {"label": "Label 1", "data": "[[1,10],[2,20],[3,10],[4,25],[5,15],[6,20],[7,40]]", "color": "#3498db"}, 
\n  {"label": "Label 2", "data": "[[1,15],[2,30],[3,25],[4,55],[5,30],[6,45],[7,50]]", "color": "#e74c3c"}
\n];
\n
\n// parse and replace .data properties
\ndataSet2.forEach(function(item) {
\n  item.data = JSON.parse(item.data);
\n});
\n
\n
\nconsole.log(dataSet2);	0
9900782	9892201	Change Location and Name of Log file at runtime, based on GUID passed in QueryString	int id = 123123;\nDictionary<int, LogWriter> loggers = new Dictionary<int, LogWriter>();\n\nConfigurationSourceBuilder builder = new ConfigurationSourceBuilder();\n\nbuilder.ConfigureLogging()\n        .WithOptions\n            .DoNotRevertImpersonation()\n        .SpecialSources.LoggingErrorsAndWarningsCategory.SendTo.FlatFile("Flat File Listener").ToFile(@"trace.log")\n        .LogToCategoryNamed("General")\n            .WithOptions.SetAsDefaultCategory()\n            .SendTo.FlatFile("AppSpecificFlatFile" + id)\n            .ToFile("logging" + id + ".log")       \n            ;\n\nDictionaryConfigurationSource configSource = new DictionaryConfigurationSource();\nbuilder.UpdateConfigurationWithReplace(configSource);\ncoreExtension = new EnterpriseLibraryCoreExtension(configSource);\n\nIUnityContainer container = new UnityContainer();\ncontainer.AddExtension(coreExtension);\n\nvar logger = container.Resolve<LogWriter>();\n\nloggers[id] = logger;	0
24623673	24620656	How does use XamlReader to load from a Xaml file from within the assembly?	string defaultNamespace = "MyNamespace";\nstring folderName = "XAML";\nstring fileName = "Sample.xaml";\n\nstring path = String.Format("{0}.{1}.{2}", defaultNamespace, folderName, fileName);\n\nusing (Stream stream = System.Reflection.Assembly.GetExecutingAssembly().GetManifestResourceStream(path))        \n{\n    object root = XamlReader.Load(stream);\n}	0
25137322	25137248	Comparing dictionaries and creating new dictionary with values in C#	var merged = dicA.Join(dicB, pair => pair.Key, pair => pair.Key,\n                       (a, b) => new { Key = a.Value, Value = b.Value })\n                 .ToDictionary(pair => pair.Key, pair => pair.Value);	0
8579473	8579419	Select items in one object where a property is in a list<string>	var c = (from c in courseObject where\n    selectedListItems.Contains(c.Status) select c);	0
3838386	3838168	C#: How to manipulate List<String> using LINQ or LAMBDA expression	var transposed = Enumerable.Range(0, MyList.First().Length)\n                           .Select(rowIndex => new string(MyList.Select(str => str[rowIndex]).ToArray()))\n                           .ToList();	0
26762708	26762157	Linq to XML: Remove duplicate from an item	var contents = XDocument.Parse(xml);\n\n// Select only elements that have the language attribute\nvar result = from item in contents.Descendants()\n             where item.Attribute("language") != null\n             select item;\n\n// Returns only those elements that have at least another element\n// with the same value.\nvar resultDuplicates = result\n    .GroupBy(s => s.Value)\n    .SelectMany(grp => grp.Skip(1));\n\n// If duplicates found, replace them in the original xml.\nif (resultDuplicates.Count() > 0)\n{\n    foreach(var entry in resultDuplicates)\n        xml = xml.Replace(entry.ToString(), string.Empty);\n}	0
772249	772154	how to write if null surround-with code snippet	Sub NullCheck()\n    Dim selected As String\n    Dim var As String\n    Dim res As String\n    Dim sel As TextSelection\n\n\n    sel = DTE.ActiveDocument.Selection\n    selected = sel.Text        \n    var = selected.Substring(0, selected.IndexOf("=") - 1).Trim()\n    res = String.Format("if ({0} == null) {1} ", var, selected)\n\n    sel.Delete()\n    sel.Insert(res, vsInsertFlags.vsInsertFlagsContainNewText)\n    sel.SmartFormat()\n\nEnd Sub	0
18149401	17996701	Binary deserialization without object definition	public class SomeDataFormat // 16 field\n{\n    public string Name { get; set; }\n    public string Country { get; set; } \n    public string UserEmail{ get; set; }\n    public bool IsCaptchaDisplayed{ get; set; }\n    public bool IsForgotPasswordCaptchaDisplayed{ get; set; }\n    public bool IsSaveChecked{ get; set; }\n    public string SessionId{ get; set; } \n    public string SelectedLanguage{ get; set; } \n    public string SelectedUiCulture{ get; set; } \n    public string SecurityImageRefId{ get; set; } \n    public string LogOnId{ get; set; } \n    public bool BetaLogOn{ get; set; } \n    public string Amount{ get; set; }\n    public string CurrencyTo{ get; set; }\n    public string Delivery{ get; set; } \n    public bool displaySSN{ get; set; }\n}	0
3216515	3216496	C# How to determine if a number is a multiple of another?	public bool IsDivisble(int x, int n)\n{\n   return (x % n) == 0;\n}	0
26926006	26924658	How can I check for the checkboxes that I've dynamically created in C#	EnableViewState=false	0
3016992	3016739	ASMX: Setting User/Password at run-time	var nc = new NetworkCredential( "Name","Password","Domain Name");	0
22060745	22052506	Grey zone of DST	DateTime dt = new DateTime(2014,3,30,2,30,0);\n    TimeZoneInfo tziSV = TimeZoneInfo.FindSystemTimeZoneById("W. Europe Standard Time");\n\n    if (tziSV.IsInvalidTime(dt))\n    {\n       dt = dt.Add(tziSV.GetUtcOffset(dt));\n    }\n    DateTime dtSV = TimeZoneInfo.ConvertTimeToUtc(dt,tziSV);	0
15880408	15880256	C# DataSet validation from XML schema	// First, read in the XML schema\n    DataSet MyDataSet = new DataSet();\n    MyDataSet.ReadXmlSchema(@"C:\YourSchema.xsd");\n\n\n    // Now, read in the XML file (it is validated \n    // against the schema when it is read in).\n    MyDataSet.ReadXml(@"C:\YourFile.xml");	0
29417299	29417056	Type with a generic where the type passed as a generic also has a generic causes an ArgumentException	internal virtual RouteBase GetRoute(DbContextTypeProvider databaseContextTypeProvider, Type model)\n{\n    Type catchallRoute = typeof(CatchallRoute<,>).MakeGenericType(new Type[] {\n        databaseContextTypeProvider.DbContextType,\n        model\n    });\n\n    Type routeTypeWrapper = typeof(RouteTypeWrapper<>).MakeGenericType(new Type[] {\n        catchallRoute\n    });\n\n    RouteTypeProvider routeTypeProvider = (RouteTypeProvider)Activator.CreateInstance(routeTypeWrapper);\n\n    return GetRoute(databaseContextTypeProvider, model, routeTypeProvider);\n}	0
22290192	22286558	In place algorithm for string transformation	var input = "a1b2c3d4e5f6g7h8i9j1k2l3m4";\nint ixLetter = 0;\nint ixDigit = input.Length - 1;\nint oxLetter = 0;\nint oxDigit = input.Length - 1;\n\nchar[] output = new char[input.Length];\nwhile (ixDigit >= 0)\n{\n    if (char.IsDigit(input[ixDigit]))\n    {\n        output[oxDigit] = input[ixDigit];\n        --oxDigit;\n    }\n    if (!char.IsDigit(input[ixLetter]))\n    {\n        output[oxLetter] = input[ixLetter];\n        ++oxLetter;\n    }\n    --ixDigit;\n    ++ixLetter;\n}\n\nstring result = new string(output);	0
11146774	11146602	Creating countdown to date C#	DateTime endTime = new DateTime(2013,01,01,0,0,0);\nprivate void button1_Click(object sender, EventArgs e)\n{ \n    Timer t = new Timer();\n    t.Interval = 500;\n    t.Tick +=new EventHandler(t_Tick);\n    TimeSpan ts = endTime.Subtract(DateTime.Now);\n    label1.Text = ts.ToString("d' Days 'h' Hours 'm' Minutes 's' Seconds'");\n    t.Start();\n}\n\nvoid  t_Tick(object sender, EventArgs e)\n{\n    TimeSpan ts = endTime.Subtract(DateTime.Now);\n    label1.Text = ts.ToString("d' Days 'h' Hours 'm' Minutes 's' Seconds'");\n}	0
10529593	10529493	Creating a object from Datarow	if (dr[CONSTANT_ATT1] != null) then attrib1 = dr[CONSTANT_ATT1].ToString();\nif (dr[CONSTANT_ATT2] != null) then attrib2 = dr[CONSTANT_ATT2].ToString();\nif (dr[CONSTANT_ATT3] != null) then attrib3 = dr[CONSTANT_ATT3].ToString();	0
4789991	4783541	Using Facebook's DeAuth Callback with the C# SDK	string signedRequestValue = Request.Form["signed_request"];\nvar app = new FacebookApp();\nvar sig = app.ParseSignedRequest(signedRequestValue);\nlong userid = sig.UserId;	0
20548480	20544092	Copying/over-writing one source to another in TFS?	var sourcePath = workspace.GetServerItemForLocalItem(fileName);\n        var targetPath = workspace.GetServerItemForLocalItem(fileNameQA);\n\n        var getStatus = workspace.Merge(sourcePath, targetPath, null, null);\n        if (getStatus.NumUpdated > 0)\n        {\n            //OK\n        }	0
10213914	10213651	Write a CSV file	class UserAndValues\n{\n    public int UserID { get; set; }\n    public string FirstName { get; set; }\n    public string LastName { get; set; }\n    [FieldConverter(typeof(MyListConverter))] \n    public ICollection<UserFavourites> Favourites {get;set;}\n}\n\npublic class MyListConverter: ConverterBase \n{ \n\n    public override object StringToField(string from) \n    { \n      throw new NotImplemented("bad luck");\n    } \n\n    public override string FieldToString(object fieldValue) \n    { \n       var list = fieldValue as ICollection<UserFavourites>;\n\n        return string.Join(",", \n            list.Select(f => f.ToString()));   // customize\n    }\n\n}	0
13426485	13426463	Convert array to string? c#	string.Join(",", Client);	0
5316984	5316814	Using data from query	using (SqlConnection con = new SqlConnection(conStr)) {\n    con.Open();\n    using (SqlCommand cmd = new SqlCommand(stm, con)) {\n        using (SqlDataReader reader = cmd.ExecuteReader()) {\n            while (reader.Read()) {\n                geodata address = new geodata();\n                // assign properties to address object\n                address.Agency = reader["agency"].ToString();\n                // call your method\n            }\n        }\n    }\n}	0
2693011	2692981	C#: How to construct a variable from another variables	((TextBox)FindControl("textbox_" + endingOfVariable)).Text = newValue;	0
8529102	8529014	How to get userID for username in ASMX webservice	//Returns the UserID and converts to a string\nstring UserID;\nif ((myObject != null) && (myObject.ProviderUserKey != null)) {\n    UserId = myObject.ProviderUserKey.ToString();\n} else {\n    UserId = String.Empty;\n}	0
24737419	24737369	How to match multiple items with Regex	string input = "akjsd{OrderNumber} aksjd {PatientName} aksjak sdj askdj {PatientSurname} askdjh askdj {PatientNumber} aksjd aksjd aksjd kajsd kasjd";\nMatchCollection matches = Regex.Matches(input, "{(.*?)}");\n\nforeach(Match match in matches)\n{\n    Console.WriteLine(match.Value);\n}	0
9751259	9751215	Percentage in StringFormat	Console.WriteLine(string.Format("{0}%", 0.8526));	0
31932987	31932896	Get Text Between Two Strings (HTML) in C#	fullName = fullName.Trim ();\nfullAddress = fullAddress.Trim ();\ncity = city.Trim ();	0
31941464	31940799	Get IdentityUser FullName of the current User in ASP.Net Webforms Web api	//make sure you added this line in the using section\nusing Microsoft.AspNet.Identity.Owin\n\nstring fullname = HttpContext.Current.GetOwinContext()\n    .GetUserManager<ApplicationUserManager>()\n    .FindById(HttpContext.Current.User.Identity.GetUserId()).FullName;	0
25669486	25668659	How to hide the Soft Keyboard when Enter key is pressed on WindowsPhone / Windows 8.1?	if(e.Key == VirtualKey.Enter)\n{\n    textBox.IsEnabled = false;\n    textBox.IsEnabled = true;\n}	0
7884225	7884158	Logging into a website using HttpWebRequest/Response in C#?	var client = new WebClient();\nclient.BaseAddress = @"https://www.site.com/any/base/url/";\nvar loginData = new NameValueCollection();\nloginData.Add("login", "YourLogin");\nloginData.Add("password", "YourPassword");\nclient.UploadValues("login.php", "POST", loginData);	0
15846379	15673665	How do I extract a SubDirectory using C# DotNetZip?	using (ZipFile zip1 = ZipFile.Read(fileName))\n{\n    zipFile = ZipFile.Read(@""+fileName);\n    var result = zipFile.Any(entry => entry.FileName.Contains("MySubFolder"));\n\n    if (result == false)\n    {\n        // something here that will extract JUST MySubFolder and content\n        string TestX = Path.GetDirectoryName(e.FileName) ;\n        string MyNewPath = outputDirectory+@"\"+TestX ;\n        e.Extract(MyNewPath);\n    } else {\n        foreach (var e in selection)\n   {             \n        var selection = (from e in zip1.Entries where (e.FileName).Contains("MySubfolder")\n        .select e)               \n        e.Extract(outputDirectory);        \n   }\n}	0
14840021	14839901	can storing data in a database sometimes lead to corrupted data?	try..catch	0
5898530	5897812	exception in set method	public void Set(TaskPrice entity)\n{\n    ObjectStateEntry entry=null;\n    if (this.Context.ObjectStateManager.TryGetObjectStateEntry(entity, out entry) == false)\n    {\n        this.ObjectSet.Attach(entity);\n    }\n    bool isExists = GetQuery().Any(x => x.TaskId == entity.TaskId);\n    if (isExists)\n    {\n\n        this.Context.ObjectStateManager.ChangeObjectState(entity, EntityState.Modified);\n    }\n    else\n    {\n        this.ObjectSet.AddObject(entity);\n    }\n}	0
20384284	20263554	Rotating 3D scatter plot data in WPF not working as expected	public static Point3D RotateAboutY(Point3D pt1, double aY)\n    {\n        double angleY = 3.1415926 * aY / 180;\n\n        double x2 = (pt1.Z * Math.Sin(angleY)) + (pt1.X * Math.Cos(angleY));\n        double y2 = pt1.Y;\n        double z2 = (pt1.Z * Math.Cos(angleY)) - (pt1.X * Math.Sin(angleY));\n\n        return new Point3D(x2, y2, z2);\n    }	0
29930423	29928943	How to Use DateTime Web Form Field to Pass DateTime Parameter into Database using Stored Procedure?	txtEffDate.Text	0
9370379	9317694	how to add delete confirmation prompt for command field in detail view?	protected void DViewComputer_DataBound1(object sender, EventArgs e)\n{\n    int noRow = DViewComputer.Rows.Count - 1;//get the no of record\n\n    if (noRow >0)\n    {\n        Button button = (Button)(DViewComputer.Rows[noRow].Cells[0].Controls[2]);\n\n        // Add delete confirmation\n        ((System.Web.UI.WebControls.Button)(button)).OnClientClick = "if (!confirm('Are you sure " +\n                               "you want to delete this record?')) return;";\n\n    }\n}	0
21495865	21219373	Sending Ctrl-Alt-Break from C#	HtmlElement rdpClient = myWebBrowser.Document.GetElementById("MsRdpClient");\nrdpClient.SetAttribute("Fullscreen", "true");	0
24782306	24782139	Why i can not open a custom web.config file in my web ASP app?	// Set the root path of the Web application that contains the\n// Web.config file that you want to access.\nstring configPath = "/MyAppRoot";\n\n// Get the configuration object to access the related Web.config file.\nConfiguration config = WebConfigurationManager.OpenWebConfiguration(configPath);	0
3425026	3424171	Add character counter to MemoExEdit control	private void memContactWith_Properties_Popup(object sender, EventArgs e)\n{\n   MemoExPopupForm popupForm = (sender as DevExpress.Utils.Win.IPopupControl).PopupWindow as MemoExPopupForm;\n   MemoEdit me = popupForm.Controls[2] as MemoEdit;\n   me.EditValueChanging += new DevExpress.XtraEditors.Controls.ChangingEventHandler(me_EditValueChanging);            \n}\n\nvoid me_EditValueChanging(object sender, DevExpress.XtraEditors.Controls.ChangingEventArgs e)\n{\n   var memo = (sender as MemoEdit);\n   var maxChars = memo.Properties.MaxLength;\n   lblContactWithCharCount.Text = memo.Text.Length + "/" + maxChars;\n}	0
4923772	4919965	ref for variables not parameters in functions	Person a = whatever;\nref Person b = ref a;	0
32378912	32364420	Proper Usage of Update and FixedUpdate Movements With Animations	void Update() {\n\n    // IF we are allowed to move.\n    if(_PMS.canMove){\n        // Get a -1, 0 or 1.\n        moveHorizontal = Input.GetAxisRaw ("Horizontal");\n        moveVertical = Input.GetAxisRaw ("Vertical");\n    }\n}\n\nvoid FixedUpdate(){\n    // IF we are allowed to move.\n    if(_PMS.canMove){\n        // Get Vector2 direction.\n        movement = new Vector2(moveHorizontal * _PMS.invertXDirection, moveVertical * _PMS.invertYDirection);\n        // Apply direction with speed.\n        movement *= speed;\n        // IF the user has an animation set.\n        if(anim != null){\n            // Play animations.\n            Helper_Manager.PlayerAnimation(moveHorizontal, moveVertical, anim, _PMS); // always call this, assuming you play an idle animation if moveHorizontal and moveVertical are 0\n        }\n\n        // Apply the force for movement.\n        rb.AddForce(movement);\n    }\n}	0
22747625	22747305	get all xaml files from compiled dll	var assembly = Assembly.LoadFile("pathToYourAssembly");\nvar stream = assembly.GetManifestResourceStream(assembly.GetName().Name + ".g.resources");\nvar resourceReader = new ResourceReader(stream);\n\nforeach (DictionaryEntry resource in resourceReader)\n    Console.WriteLine(resource.Key);	0
33306027	33304888	How do I find 10 elements by longitude and latitude in 1 km radius using LINQ?	// Returns the great circle distance between two flats, as meters\npublic static double DistanceBetweenFlats(Flat flat1, Flat flat2)\n{\n    const int EarthRadius = 6371;\n    double latitude = ToRadian(flat2.Latitude - flat1.Latitude);\n    double longitude = ToRadian(flat2.Longitude - flat1.Longitude);\n    double tmp = (Math.Sin(latitude / 2) * Math.Sin(latitude / 2)) +\n        (Math.Cos(ToRadian(flat1.Latitude)) * Math.Cos(ToRadian(flat2.Latitude)) *\n        Math.Sin(longitude / 2) * Math.Sin(longitude / 2));\n    double c = 2 * Math.Asin(Math.Min(1, Math.Sqrt(tmp)));\n    double d = EarthRadius * c;\n    return d * 1000;\n}\n\n...\n\nvar centerFlat = ...;\nvar getAllInRadius = flats.Where(z => DistanceBetweenFlats(centerFlat, z) <= 1000);	0
27825455	27825281	Getting EvaluateException was unhandled - Cannot Find column [CustConActive]	adpt.Fill(ds);	0
8756477	8756436	How to SUM each column value of a data table	table.Columns.Add("Total", typeof(int), "[.NET] + java + SAP");	0
13593096	13593006	Find the highest number in array , using while or for?	private void button2_Click(object sender, EventArgs e)\n {\n    int maxIndex = 0;\n\n    for(int i = 0; i < 50; i++)\n    {\n        if (money[i] > money[maxIndex])            \n            maxIndex = i;            \n    }\n\n    MessageBox.Show(name[maxIndex] + " has biggest value " + money[maxIndex]);\n }	0
2516879	2516783	How can two threads access a common array of buffers with minimal blocking ? (c#)	IProducerConsumerCollection<T>	0
17549609	17530942	Visual Studio password recovery without email	e.Cancel = True;\n    PasswordRecovery1.SuccessText = e.Message.Body;	0
1602174	1602022	GridView.PageSize set to default 10 on 1st page load	Master.GridViewSize	0
6806886	6806765	get your application to speak with custom voice	System.Speech	0
22690991	22687901	Custom color for ICellStyle FillForegroundColor than provided named colors	byte[] rgb = new byte[3] { 192, 0, 0 };\n XSSFCellStyle HeaderCellStyle1 = (XSSFCellStyle)xssfworkbook.CreateCellStyle();\n HeaderCellStyle1.SetFillForegroundColor(new XSSFColor(rgb));	0
4629391	4629254	LINQ2SQL: Join multiple tables	var result = (from projects in _db.Projects\n                      join folders in _db.Folders\n                      on projects.ProjectId equals folders.ProjectId\n                      join tasks in _db.Tasks\n                      on folders.FolderId equals tasks.FolderId\n                      where projects.Id.ToString() == id\n                      && projects.UserId == user\n                      select projects).ToList();	0
21866749	21866656	Working with byte array and strings	string str = BitConverter.ToString(arrayStr).Replace("-", "");	0
10893637	10893412	How to disable a cell of a GridView row?	protected void GridView1_DataBound(object sender, GridViewRowEventArgs e)\n    {\n        if (e.Row.RowType == DataControlRowType.DataRow)\n        {\n            if (e.Row.Cells[5].Text=="Locked")\n            {\n                (e.Row.FindControl("idofButton1") as Button).Visible=false;\n            }\n        }\n    }	0
6759567	6759514	Lazy initialization for objects that initializing by reflection	Lazy<T>	0
21487191	21423960	Go to a specified line in a text file and store it into SQL server	var line = File.ReadAllLines("filepath")\n               .Where(line => !line.StartsWith("#"))\n               .First();	0
9426937	9425415	How do I declare a embedded struct in C# like a embedded record in delphi?	[StructLayout(LayoutKind.Sequential, Pack=1)]\nstruct Kernel\n{\n    int State;\n}\n\n[StructLayout(LayoutKind.Sequential, Pack=1)]\nstruct Shell\n{\n    [MarshalAs(UnmanagedType.ByValArray, SizeConst=20)]\n    Kernel[] Kernels;\n}	0
30947607	30947032	How to supply dynamic data set to a single view using ViewModels	return View("ViewToRender", viewModel);	0
6841819	6310618	ListView Checkbox Behavior	private bool allowCheck = false;\nprivate bool preventOverflow = true;\n\nprivate void lstvwRaiseLimitStore_MouseClick(object sender, MouseEventArgs e)\n    {\n        preventOverflow = false;\n        ListViewItem item = lstvwRaiseLimitStore.HitTest(e.X, e.Y).Item;\n        if (item.Checked)\n        {\n            allowCheck = true;\n            item.Checked = false;\n        }\n        else\n        {\n            allowCheck = true;\n            item.Checked = true;\n        }\n    }\n\nprivate void lstvwRaiseLimitStore_ItemChecked(object sender, ItemCheckedEventArgs e)\n    {\n        if (!preventOverflow)\n        {\n            if (!allowCheck)\n            {\n                preventOverflow = true;\n                e.Item.Checked = !e.Item.Checked;\n            }\n            else\n                allowCheck = false;\n        }\n    }	0
10254781	10254570	Change default ASP MVC Request Header to add your own values	Operation is not supported by this platform	0
11538979	11538896	How to ping a website / ip that is deployed in iis	// prepare the web page we will be asking for\n                HttpWebRequest request = (HttpWebRequest)\n                    WebRequest.Create(Url);\n                //if (AuthRequired())\n                //    request.Credentials = new NetworkCredential(Username, Password);\n                // execute the request\n                HttpWebResponse response = (HttpWebResponse)request.GetResponse();	0
5207354	5207316	Converting from saving in Session to Cookies?	Response.Cookies["userName"].Value = "patrick";\nResponse.Cookies["userName"].Expires = DateTime.Now.AddDays(1);\n\nHttpCookie aCookie = new HttpCookie("lastVisit");\naCookie.Value = DateTime.Now.ToString();\naCookie.Expires = DateTime.Now.AddDays(1);\nResponse.Cookies.Add(aCookie);	0
4761005	4760525	Transparency in FreeImage	dib = FreeImageAPI.FreeImage.LoadEx("C:\\title_selected.png");\n            dib = FreeImage.ConvertColorDepth(dib, FREE_IMAGE_COLOR_DEPTH.FICD_04_BPP);\n            byte[] Transparency = new byte[1];\n            Transparency[0] = 0x00;\n            FreeImage.SetTransparencyTable(dib, Transparency);\n            FreeImage.Save(FREE_IMAGE_FORMAT.FIF_PNG, dib, "C:\\title_selected1.png", FREE_IMAGE_SAVE_FLAGS.DEFAULT);	0
6451592	6451253	C# Custom Comparer with Comparison delegate	lst.OrderBy(t => t.Code_PK_OriginalValue);	0
3915668	3915529	Getting XAML designer to show design in VS2010	Microsoft.FamilyShow	0
19289713	19289610	How to get value from store procedure	param.Direction = ParameterDirection.Output;\n        cmd.Parameters.Add(param);\n\n        cmd.ExecuteNonQuery();\n\n        string budgetnum = (string)cmd.Parameters["@retvalue"].Value;	0
17828642	17828575	Enable\Disable button in gridview	protected void Grid_RowDataBound(object sender, GridViewRowEventArgs e)\n{\n    if(e.Row.RowType != DataControlRowType.DataRow)\n    {\n        return;\n    }\n\n    Button button = (Button)e.Row.FindControl("btnSubmit");\n\n    int Id = (int) ((DataRowView) e.Row.DataItem)["Id"];\n\n    if(Id == Convert.ToInt32(Session["Id"]))\n    {\n        button.Enabled = false;\n    }\n    else\n    {\n        button.Enabled = true;\n    }\n}	0
6608332	6607196	Add File Paths to Add-in/Macros Security Programmatically	Microsoft.Win32.RegistryKey key;\n    key =\n        Microsoft.Win32.Registry.LocalMachine.CreateSubKey(\n            @"SOFTWARE\Microsoft\VisualStudio\10.0\AutomationOptions");\n    if (key != null)\n    {\n        key = key.CreateSubKey(@"LookInFolders");\n        key.SetValue(Name,Path);\n        key.Close();	0
11343757	11341065	How to remove a specific context menu item in Zedgraph	private void zedGraphControl1_ContextMenuBuilder(ZedGraphControl sender, ContextMenuStrip menuStrip, Point mousePt, ZedGraphControl.ContextMenuObjectState objState)\n{\n  foreach (ToolStripMenuItem item in menuStrip.Items)\n  {\n    if ((string)item.Tag == "set_default")\n    {\n      menuStrip.Items.Remove(item);\n      break;\n    }\n  }\n}	0
16202797	16202591	How to call WebService client-side?	function Test() {\n    TestWebService.WebService1.HelloWorld(onS, onF);\n}	0
29140204	29140105	Request WinForm Label Value from Background Worker illegal?	Dispatcher.Invoke(new Action(() =>\n            {\n                counter_O1 = Convert.ToInt32(this.rowcount_O1.Text);\n            }));	0
6633239	6633219	how to check next item in linq 2 sql query	var query = from item1 in db.Items.Where(x => x.title == "t1")\n            from item2 in db.Items.Where(x => x.title == "t1")\n            where item1.position + 1 == item2.position\n            select item1; // Adjust however you want, e.g. new { item1, item2 }	0
15760790	15760533	Save a List<T> not serialisable to a file	List<Tuple<string, ListSortDirection, int, etc.>>	0
23146021	23145836	Setting Control Template Dynamically in WPF	Application.Current.Resources["RightTriangleAnnotations"] as ControlTemplate	0
6568884	6568851	Simplest way to change numbers in localized format in an Xml file to english format	style = NumberStyles.Number | NumberStyles.AllowCurrencySymbol;\nculture = CultureInfo.CreateSpecificCulture("fr-FR");\nif (Double.TryParse(value, style, culture, out number))\n   Console.WriteLine("Converted '{0}' to {1}.", value, number);\nelse\n   Console.WriteLine("Unable to convert '{0}'.", value);	0
15886851	15886617	C# Save image without using Dialog	string filePath = picTeamLogo.ImageLocation;\nFileInfo fi = new FileInfo(filePath);\nImage tempImage = Image.FromFile(fi.FullName);\ntempImage.Save(@"../logo/" + fi.Name);	0
31078130	31078117	Create Exception with a custom constructor in C#	public MyException(IContext context)\n    : base(String.Format("Context is: {0}", context))\n{\n}	0
22158803	22158256	How to access RichTextBox.Select() method while referring to it as a "Control"	private void TextSelectionAtSomePoint() {\n    int selectionStart = 0;\n    int selectionEnd = 6;\n    var temp = tbcPages.Controls[0].Controls[0] as RichTextBox;\n    if(temp != null)\n        temp.Select(selectionStart,selectionEnd);\n}	0
21864934	21863985	C# sqlserver stored procedure parameters	SqlCommand cmd = new SqlCommand("usp_UpdateProc", connection);\ncmd.CommandType = CommandType.StoredProcedure;\n\ncmd.Parameters.AddWithValue("@status", status);\nif(status == -1)\n    cmd.Parameters.AddWithValue("@datenow", DBNull.Value);\nelse\n    cmd.Parameters.AddWithValue("@datenow", DateTime.Now.ToString(@"MM\/dd\/yyyy h\:mm tt"));\n\ncmd.Parameters.AddWithValue("@ID", @ID);\n\ntry\n{\n    rowsAffected = cmd.ExecuteNonQuery();\n}\ncatch (Exception ep)\n{ \n    MessageBox.Show(ep.ToString());\n}	0
6914756	6914686	Building a relative path connection string to access a SQLite database in c#	string baseFolder = AppDomain.CurrentDomain.BaseDirectory;\n\nstring sqlLiteConnectionString = string.Format(\n  "data source=\"{0}\";datetimeformat=Ticks", \n  Path.Combine(baseFolder, "data.db3"));\n\nvar entityConnectionString = new EntityConnectionStringBuilder\n{\n  Metadata = "res://*",\n  Provider = "System.Data.EntityClient",\n  ProviderConnectionString = sqlLiteConnectionString,\n}.ConnectionString;\n\nvar entities = new dataEntities(entityConnectionString);	0
3312078	3311913	How do I format a number in C# with commas and decimals?	"#,##0.################"	0
18529249	18485867	Screens using LongListSelector shared between WP7 and WP8	Solution\n|-- Common Library\n|    |-- Views \n|         |-- Page1\n+-- WP7\n    |-- Views\n      |-- Page1\n          |-- Page1.xaml  (Windows 7 specific markup)\n          |-- Page1.xaml.cs (code behind file)\n          |-- Page1.styles.xaml (common styles shared between wp7 and wp8 apps)\n+-- WP8\n|-- Views\n      |-- Page1\n          |-- Page1.xaml  (Windows 8 specific markup)\n          |-- ->Page1.xaml.cs (linked from the WP7 project)\n          |-- ->Page1.styles.xaml (linked from the WP7 project)	0
16614977	16613998	Running a PowerShell script from C# to Pull Git Repository	git pull	0
5313507	5313455	Winforms DatagridView: Setting a cell ReadOnly has no effect	private void dataGridView1_CellBeginEdit(object sender, \n   DataGridViewCellCancelEventArgs e)\n{\n   if (e.ColumnIndex != 0) \n   { \n      e.Cancel = true;\n   }\n}	0
8588918	8588845	Allow null values to be added to list	var ppl = from p in xyz.new_ppl\n          select new\n          {\n              p == null ? null : p.name\n          };	0
14347740	14338783	Extract group name from DirectoryEntry	string Pattern = @"^CN=(.*?)(?<!\\),.*";\nstring group = Regex.Replace(groupname.ToString(), Pattern, "$1");\ngroups.Add(group);	0
7646262	7646036	Combining arrays of strings together	List<string> CombineWords(params string[][] wordsToCombine)\n{\n     if (wordsToCombine.Length == 0)\n         return new List<string>();\n\n     IEnumerable<string> combinedWords = wordsToCombine[0].ToList();\n     for (int i = 1; i < wordsToCombine.Length; ++i)\n     {\n         var temp = i;\n         combinedWords = (from x in combinedWords from y in wordsToCombine[temp]\n                       select x + " " + y);\n     }\n     return combinedWords.ToList();\n }	0
13845204	13844636	Insert a 'Return' after the 60th char in every line for a WPF RichTextBox	private void richTextBox1_KeyUp(object sender, KeyEventArgs e)\n{\n    TextPointer line = richTextBox1.CaretPosition.GetLineStartPosition(0);\n    if (line.GetOffsetToPosition(richTextBox1.CaretPosition) > 60)\n    {\n        line.GetPositionAtOffset(60, LogicalDirection.Forward).InsertLineBreak();\n    }\n}	0
20548019	20547904	WPF passing string to new window	public myWindow2(string value)\n {\n     InitializeComponent();\n\n     this.myString = value;\n }	0
31689170	31688264	Import DateTime formated cell using Spreadsheetgear	// Need the IWorkbook for which your "worksheet" object belongs to.\nIWorkbook workbook = worksheet.Workbook;\n\n// This code assumes there is *always* a date (double) value in this cell.  You may want \n// to do some additional error checking to ensure B20 actually has a number in it.  \n// Otherwise the cast will give you issues.\nDateTime dateReleased = workbook.NumberToDateTime((double)worksheet.Cells["B20"].Value);\nfileInformation.DateReleased = dateReleased;\n\nDateTime dateRequired = workbook.NumberToDateTime((double)worksheet.Cells["B21"].Value);\nfileInformation.DateRequired = dateRequired	0
16635215	16635176	What is a verbatim string?	string sqlServer = @"SERVER01\SQL";	0
18542165	18542013	My lambda expression isn't producing the result I expected	courses = courses.Where(\n            c => (queryParameters.ShowInActive || c.Flags.Contains((ulong)CourseFlags.Active))\n                 &&\n                 (queryParameters.AuthorId <= 0 ||\n                  (c.Authors != null && c.Authors.Exists(a => a.ID == queryParameters.AuthorId)))\n                 &&\n                 ((queryParameters.CategoryIDs == null || queryParameters.CategoryIDs.Count == 0 ||\n                  (c.Tags != null && c.Tags.Any(t => queryParameters.CategoryIDs.Contains(t.ID))))\n                  &&\n                  (queryParameters.CourseIDs == null || queryParameters.CourseIDs.Count == 0 ||\n                  queryParameters.CourseIDs.Contains(c.ID)))\n            ).ToList();	0
13674734	13674654	Converting to async,await using async targeting package	JDEItemLotAvailability itm = await Task.Factory.StartNew(() => Dal.GetLotAvailabilityF41021(a, b, c));	0
13630619	13630493	return a string value from post data	using (StreamReader reader = new StreamReader(Request.InputStream))\n{\n    String xmlData = reader.ReadToEnd();\n    XmlDocument doc = new XmlDocument();\n    doc.LoadXml(xmlData);\n    Response.Write("MyString");\n}	0
32522185	32521574	Passing a COM method default parameter	object missingValue = System.Reflection.Missing.Value;	0
2061358	2061338	Using LINQ to select a random XML node	static void Main(string[] args)\n{\n    Random rnd = new Random();\n    XDocument galleries = XDocument.Load(@"C:\Users\John Boker\Documents\Visual Studio 2008\Projects\ConsoleApplication1\ConsoleApplication1\Galleries.xml");\n    var image = (from g in galleries.Descendants("Gallery")\n                 where g.Attribute("ID").Value == "10C31804CEDB42693AADD760C854ABD"\n                 select g.Descendants("Images").Descendants("Image").OrderBy(r=>rnd.Next()).First()).First();\n    Console.WriteLine(image);\n    Console.ReadLine();\n}	0
11033227	11033180	How to call a method Asynchronously?	backgroundWorker.RunWorkerAsync();	0
15515078	15489394	Make a good relation between group, users with an owner with entity framework code first	public class User\n{\n    public int Id { get; set; }\n    public int? GroupId { get; set; }\n    [InverseProperty("Users")]\n    public virtual Group group { get; set; }\n}\n\npublic class Group\n{\n    public int Id { get; set; }\n    public int? OwnerId { get; set; }\n    public User Owner { get; set; }\n    public virtual ICollection<User> Users { get; set; } \n}	0
17954669	17954026	getting a select statement column info from combobox	var results = from row in dt.AsEnumerable()\nwhere row.Field<int>("ID") == yourselectedid\nselect row;	0
12214518	12214402	Does every machine generate same result of random number by using the same seed?	Random(int)	0
7219932	7219719	I need to do some pattern matching with more than one pattern as input in C#	static Tuple<string,string> Match(string question)\n{\n   //Do the matching and return the string,string tuple where first \n   //string is for output 1 and second for output 2.\n}\n\nstatic Tuple<List<string>,List<string>> GetOutput(List<string> questions)\n{\n    var r = questions.Select(q => Match(q));\n    return new Tuple<List<string>,List<string>(r.Select(t => t.Item1).ToList(), r.Select(t =>  t.Item2).ToList());\n}	0
3751367	3735412	how to get all html tags from html file in the list using regular expression	var tagList = new List<string>();\n                 string pattern = @"(?<=</?)([^ >/]+)"\n                 var matches = Regex.Matches(file, pattern);\n\nfor (int i = 0; i < matches.Count; i++)\n                 {\n\n                     tagList.Add(matches[i].ToString());\n\n                 }\n                     //to obtain non duplicate list\n                     tagList = tagList.Distinct().ToList();	0
5806680	5806642	Re-use parts of a linq query	public static DateTime GetMostRecentTimestamp (this IQueryable<Document> docs)\n{\n    return docs.Select(r => r.m_Timestamp)\n               .OrderByDescending(r => r)\n               .FirstOrDefault();\n}	0
12329484	12329417	How do I resolve my error  when trying to convert a data type of VarChar to a Numeric type?	int.Parse	0
10560128	10519521	Interface based design and optional method parameters	class MethodAParameters\n{\n    public string Required1 {get;set;} //add validation in setter (nulls are not allowed)\n    public string Required2 {get;set;} //add validation in setter (nulls are not allowed)\n    public int? Optional1 {get;set;} //nulls allowed\n\n    public MethodAParameters(string required1, string required2)\n    {\n        Required1 = required1;\n        Required2 = required2;\n    }\n}	0
29097149	29097071	Split String and add in combobox in c#	DataRow dr = newdt.Rows[i];\nstring TempTr = dr["Trainee"].ToString();\nstring[] result = TempTr.Split(',');\nforeach (string s in result)\n  {\n    if (s.Trim() != "")\n    TraineeCombo.Items.Add(s);\n   }	0
1537264	1537231	Get Xml Files From Website	WebClient Client = new WebClient();\nClient.DownloadFile("http://foo.bar", @"C:\filename.xml");	0
13755053	13755007	C# find highest array value and index	int maxValue = anArray.Max();\n int maxIndex = anArray.ToList().IndexOf(maxValue);	0
2022477	2022458	Good way to translate numeric to string, with decimal point removed?	var numberWithPoint = dbGetNumber();\n\nstring numberWithOutPoint = numberWithPoint.ToString().Replace(".", string.Empty);	0
16382100	16382036	Hiding HTML tag in webbrowser	private void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)\n        {\n            HtmlDocument doc = webBrowser1.Document;\n            HtmlElement HTMLControl = doc.GetElementById("question-header");\n            //HTMLControl.Style = "'display: none;'";\n            if (HTMLControl != null)\n            {\n                HTMLControl.Style = "display: none";\n            }\n        }	0
6584160	6583989	Set up multiple Facebook applications in one solution and fan page tap url problem	private IFacebookApplication GetCurrent()\n        {\n            var url = HttpContext.Current.Request.Url;\n\n            // Get the settings based on the url or whatever\n\n            var simpleApp = new DefaultFacebookApplication();\n\n            // Set the settings\n\n            return simpleApp;\n        }	0
9340013	9339958	How to make C# able to see "template like type" T in structure builtin function like in C++?	static void GetBytes<T>(T obj, byte[] data)\n{\n    unsafe\n    {\n        fixed (byte* pData = data)\n        {\n            Marshal.StructureToPtr(obj, (IntPtr)pData, false /*careful...*/);\n        }\n    }\n}	0
1606405	1606345	Parsing XML in C#	public void CreatePoints(string xml)\n{\n    XPathDocument doc = new XPathDocument(XmlReader.Create(new StringReader(xml)));\n    var xPathNodeIterator = doc.CreateNavigator().Select("/Data/Points/Point");\n    foreach (XPathNavigator node in xPathNodeIterator)\n    {\n        var x = node.SelectSingleNode("@X").ValueAsInt;\n        var y = node.SelectSingleNode("@Y").ValueAsInt;\n\n        new Point(x, y);\n    }\n}	0
6181196	6181153	Value from row with DropDownList on DropDownList Index Changed Event	GridViewRow gRow = (GridViewRow)(sender as Control).Parent.Parent;\n string trying_to_get = string.Empty;\n if (gRow != null) \n {\n    trying_to_get = gRow.Cells[0].Text;\n }	0
13134149	13134009	How to quickly copy a part of binary file?	Stream.Position	0
17950570	17948201	show search results and highlight them in gridview	private void button10_Click(object sender, EventArgs e)\n    {\n        foreach (DataGridViewRow row in dataGridView2.Rows)\n        {\n            if (row.Cells["CardSerial"].Value.ToString().Equals(textBox2.Text))\n            {\n                dataGridView2.Rows[row.Index].DefaultCellStyle.BackColor = Color.Yellow;\n            }\n            else\n            {\n                dataGridView2.Rows[row.Index].Visible = false;\n            }\n        }\n    }	0
6641157	6641125	Assign a DataTable to a DataTable	DataTable dataTable2  = dataTable1.Clone();  \n        dataTable2.Columns.Remove("column1");\n        dataTable2.Columns.Remove("column2");	0
5203066	5197917	ServerTooBusyException on a virtual directory used by one user only	WebRequest.DefaultWebProxy = null;	0
11684499	11684473	Method implied interpretation of parameters	public static DialogResult Show(\n    string text,\n    string caption\n)	0
6120104	6120044	Using ICommand interface	public class Colorizator : IOrganicEnvironment<Cell<YUV>, YUV>>\n{\n   // normal code here\n}\n\npublic class ColorizatorCommand : ICommand\n{\n    private Colorizator _colorizator;\n\n    public ColorizatorCommand(Colorizator colorizator)\n    {\n        _colorizator = colorizator;\n    }\n\n    public void Execute()\n    {\n        //use _colorizator here;\n    }\n}	0
19896384	19896344	Loading a default home page in WebBrowser - Windows Phone	private void WebBrowser_OnLoaded(object sender, RoutedEventArgs e)\n{\n    webBrowser1.Navigate(new Uri("http://www.nokia.ie/"));\n    webBrowser1.Navigating += OnNavigating;\n}\n\nprivate void OnNavigating(object sender, NavigatingEventArgs e)\n{\n    //every navigation to any sites that is not www.nokia.ie will be blocked\n    if(e.Uri.OriginalString != "http://www.nokia.ie/")\n    {\n        e.Cancel=true;\n    }\n}	0
7680426	7583096	How to solve cast issues in ValidationRule classes' properties?	string val = e.WebTest.Context["DS.UserRoles.bDoesntHaveMenuX"].ToString();\n  e.WebTest.Context["DS.UserRoles.bDoesntHaveMenuX"] = (val == "True");	0
498158	498134	How can I make an HtmlTextWriter object use spaces instead of tabs for its Indents?	System.Web.UI.HtmlTextWriter htmlWriter = \n    new System.Web.UI.HtmlTextWriter(yourTextWriter, "    ");	0
24322476	24321995	Extract Date time from the Sentence in c#	string ds = "Posted on Thursday, May 1st, 2014 at 10:07 AM";\n\nstring[] formats = new string[] {\n"MMMM d'st, 'yyyy' at 'hh:mm tt",   // for parsing like "1st"\n"MMMM d'nd, 'yyyy' at 'hh:mm tt",   // for parsing like "2nd"\n"MMMM d'rd, 'yyyy' at 'hh:mm tt",   // for parsing like "3rd"\n"MMMM d'th, 'yyyy' at 'hh:mm tt",   // for parsing like "4th"\n};\n\n// Get rid of the "Posted on Thursday"\nds = ds.Substring(ds.IndexOf(", ") + 2);\nDateTime date = DateTime.ParseExact(ds, formats, null, DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal);\n\n// Once you have a DateTime, you can format it any way you want\nConsole.WriteLine(date.ToString("o"));	0
3351767	3349961	Reading XML template, make a change and display on page	var xml = @"<areas> \n  <area title=""AFGHANISTAN"" mc_name=""AF""></area> \n  <area title=""ALAND ISLANDS"" mc_name=""AX""></area> \n  <area title=""ALBANIA"" mc_name=""AL""></area> \n  <area title=""ALGERIA"" mc_name=""DZ""></area> \n  <area title=""ANDORRA"" mc_name=""AD""></area> \n  <area title=""ANGOLA"" mc_name=""AO""></area> \n  <area title=""ANGUILLA"" mc_name=""AI""></area> \n  <area title=""ANTIGUA AND BARBUDA"" mc_name=""AG""></area> \n</areas>\n";\n\nvar doc = new XmlDocument();\ndoc.LoadXml(xml);\nvar nodes = doc.SelectNodes("areas/area");\n\nforeach (XmlNode node in nodes)\n{\n    // You can view existing attribute values through node.Attributes.\n    var att = doc.CreateAttribute("value");\n    att.Value = "something";\n    node.Attributes.Append(att);\n}\n\nConsole.WriteLine(doc.OuterXml);	0
19094093	19093942	Returning an object of values from grouped LINQ statement	infoList.GroupBy(s => s.Name.Substring(0, s.Name.LastIndexOf("whatever"),\n                (key, g) => new { fieldKey= key,fieldValues = g.ToList() });	0
17871494	17871405	How can I convert date values ??????from the multiple different types that are string to datetime with one method?	CultureInfo ci = CultureInfo.GetCultureInfo("sl-SI");\nstring[] fmts = ci.DateTimeFormat.GetAllDateTimePatterns();\n\nif (DateTime.TryParseExact(date, fmts, ci, DateTimeStyles.AssumeLocal, out dt))\n{\n    DateTime = Convert.ToDateTime(date);\n    Check = true;\n}	0
14346625	14346584	Define a generic class and implement genetic interface	public interface IDummy<TType> where TType : new()\n{\n}\n\npublic class Dummy<TType> : IDummy<TType> where TType : new()\n{\n}	0
1737854	1737823	How to get a set of rows from an array of id's?	where idList.Contains(record.id)	0
16712514	16709675	How to Delete Files and Application Data Container Values in One Go?	await Windows.Storage.ApplicationData.Current.ClearAsync(\n     Windows.Storage.ApplicationDataLocality.Local);	0
12378652	12306866	Scrolling in a flowlayoutpanel while dragging?	private void thumbFlow_DragLeave(object sender, EventArgs e)\n    {\n    int BegY_ThumbFlow = this.thumbFlow.FindForm().PointToClient(this.thumbFlow.Parent.PointToScreen(this.thumbFlow.Location)).Y;\n    int thumbFlowBound_Y = this.thumbFlow.Height + BegY_ThumbFlow;\n    int mouseY = this.thumbFlow.FindForm().PointToClient(MousePosition).Y;\n\n    while (mouseY >= thumbFlowBound_Y)\n    {\n        thumbFlow.VerticalScroll.Value = thumbFlow.VerticalScroll.Value + DRAG_DROP_SCROLL_AMT;\n        mouseY = thumbFlow.FindForm().PointToClient(MousePosition).Y;\n        thumbFlow.Refresh();\n    }\n\n    while (mouseY <= BegY_ThumbFlow)\n    {\n        thumbFlow.VerticalScroll.Value = thumbFlow.VerticalScroll.Value - DRAG_DROP_SCROLL_AMT;\n        mouseY = thumbFlow.FindForm().PointToClient(MousePosition).Y;\n        thumbFlow.Refresh();\n    }	0
25037660	24865570	Executing SSIS packages from the SSIS catalog on SQL Server 2012	var projectBytes = ssisServer.Catalogs["SSISDB"]\n                             .Folders["MasterChild"]\n                             .Projects["MasterChildPackages"].GetProjectBytes();\n\n// note that projectBytes is basically __URFILE__.ispac      \nusing (var existingProject = Project.OpenProject(new MemoryStream(projectBytes)))\n{\n    existingProject.PackageItems["master.dtsx"].Package.Execute(.... todo ....)\n}	0
22231291	22231006	Building a constant hierarchy structure	public static class AgeConstants\n{\n    public class Hotel\n    {\n      public const int MinHotelAge = 0;\n      public const int MaxHotelAge = 10;\n    }\n}	0
7855241	7854225	How to create a User Story in a certain Workspace and Project using Rally Api and .NET	RallyRestApi _restApi = new RallyRestApi("username", "password", "https://rally1.rallydev.com", "1.27");\nDynamicJsonObject toCreate = new DynamicJsonObject();\ntoCreate["Name"] = myUserStory.Name;\ntoCreate["Description"] = myUserStory.Description;\n\n// these are the important ones..\ntoCreate["Workspace"] = "/workspace/456879854";\ntoCreate["Project"] = "/project/4573328835";\ntoCreate["Iteration"] = "/iteration/4459106059";\n\nCreateResult createResult = _restApi.Create("hierarchicalrequirement", toCreate);            \nbool success = createResult.Success;	0
14492101	14489589	Update DATETIME column where said DATETIME < current DATETIME	string sql = "update statuses set stat = @stat, tester = @tester" +\n        ", timestamp_m = getdate()" +\n        " where id IN (" + IDs + ") and timestamp_m < @pageLoadTime";\n\nSQLConnection conn = getMeASqlConnection();\n\nSQLCommand cmd = new SQLCommand(sql, conn);\n\ncmd.Parameters.Add("@stat", System.Data.SqlDbType.NVarChar).Value = UpdaterDD.SelectedValue;\ncmd.Parameters.Add("@tester", System.Data.SqlDbType.NVarChar).Value = Session["Username"].ToString();\n// Here, pageLoadTime is a DateTime object, not a string\ncmd.Parameters.Add("@pageLoadTime", System.Data.SqlDbType.DateTime).Value = pageLoadTime;	0
17544638	17544416	Change List elements from info in Dictionary	// IEnumerable<Info>\nvar items = infoList.Where(i => infoDic.ContainsKey(i.InfoText))\n                    .Select(e => new Info\n                            {\n                                InfoInt = infoDic[e.InfoText],\n                                InfoText = e.InfoText\n                            });	0
2662165	2662130	dropdownlist expect first row	protected void DPBind(ArrayList list)\n     {\n          list.Insert(0, "your First Item");\n          dropdownlist1.datasource = list;\n          dropdownlist1.dataBind();\n     }	0
11536779	11534934	Generate a power multi-set from r elements that has size n	void MultiSet(List<string> elems, int last, int n, ref List<string> set, ref List<List<string>> result)\n{\n    if (set.Count < n)\n    {\n        for (int index = last; index < elems.Count; index++)\n        {\n            set.Add(elems[index]);\n            MultiSet(elems, index, n, ref set, ref result);\n            set.RemoveAt(set.Count - 1);\n        }\n    }\n    else\n    {\n        result.Add(new List<string>(set));\n    }\n}\n\nList<List<string>> PowerMultiSet(List<string> elems, int n)\n{\n    var result = new List<List<string>>();\n    var set = new List<string>();\n    MultiSet(elems, 0, n, ref set, ref result);\n    return result;\n}	0
9835844	9834983	How to Generate an XML/XSD from a SQL Server Table?	DataTable dt = new DataTable();\n    using (System.Data.SqlClient.SqlConnection connection = new System.Data.SqlClient.SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["connection"].ConnectionString))\n    {\n        connection.Open();\n\n        System.Data.SqlClient.SqlCommand command = new System.Data.SqlClient.SqlCommand();\n        command.Connection = connection;\n\n        command.CommandText = @"SELECT * FROM  SalesOrders WHERE STatus = 'Pending'";\n\n        System.Data.SqlClient.SqlDataAdapter adapter = new System.Data.SqlClient.SqlDataAdapter(command);\n        adapter.Fill(dt);\n    }\n    MemoryStream ms = new MemoryStream();\n    dt.WriteXml(ms, XmlWriteMode.IgnoreSchema);\n    ms.Seek(0, SeekOrigin.Begin);\n    StreamReader sr = new StreamReader(ms);\n    string xml = sr.ReadToEnd();\n    ms.Close();\n    return xml;	0
6577356	6560165	How to use webbrowsr control with Httpwebrequest?	webBrowser.Navigate(someUrl);\n\n        ...\n\n        CookieContainer cookies = new CookieContainer();\n        foreach (string cookie in webBrowser.Document.Cookie.Split(';'))\n        {\n            string name = cookie.Split('=')[0];\n            string value = cookie.Substring(name.Length + 1);\n            string path = "/";\n            string domain = "yourdomain.com";\n            cookies.Add(new Cookie(name.Trim(), value.Trim(), path, domain));\n        }\n\n\n        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);\n        request.CookieContainer = cookies;\n        ...	0
20054395	20052705	IIS7 programmatically modify application anonymous access	string webSiteName = "Default Web Site";\nstring applicationName = "MyApp";\n\nusing (ServerManager server = new ServerManager())\n{\n    ConfigurationSection config = server.GetApplicationHostConfiguration()\n                                        .GetSection(@"system.webServer/security/\n                                                     authentication/\n                                                     anonymousAuthentication", \n                                                     webSiteName + "/" + applicationName);\n    config.OverrideMode = OverrideMode.Allow;\n    config["enabled"] = true;\n    server.CommitChanges();\n}	0
2648460	2648379	Concatenate hex numeric updowns to string for a textbox	private void button1_Click(object sender, EventArgs e) {\n  string txt = "";\n  for (int ix = 1; ix <= 4; ++ix) {\n    var nud = Controls["numericUpDown" + ix] as NumericUpDown;\n    int hex = (int)nud.Value;\n    txt += hex.ToString("X2");\n  }\n  textBox1.Text = txt;\n}	0
4002332	4002290	Setting Font of TextBox from code behind	txtEditor.FontFamily = new FontFamily("Consolas"); // the Media namespace	0
28987378	28987276	How to use GetChildAtPoint with PointF	if (poscount > 15)\n{\n    // to see if point is close to an object\n    Point iPoint = new Point((int)point2.X, (int)point2.Y);\n    if (this.GetChildAtPoint(iPoint) != null)\n    {\n        label1.Text = "I found an object";                                      \n    }\n    else\n    {\n        label1.Text = " no object found";\n    }\n}	0
3135810	3134676	ASP.NET: Controls are null when I try to change a property	protected void Page_Init(object sender, EventArgs e)\n{\n   literalGameName.Text = myGame.Name;\n}	0
11529153	11528784	Working with more than 2 dynamically created datagridview	DataGridView dataGridView1 = tabPage1.Controls.OfType<DataGridView>() as DataGridView;\nDataGridView dataGridView2 = tabPage2.Controls.OfType<DataGridView>() as DataGridView;	0
3913727	3913697	How to do a LIKE query with linq?	var results = from c in db.costumers\n              where SqlMethods.Like(c.FullName, "%"+FirstName+"%,"+LastName)\n              select c;	0
22000043	21996317	Wifibot RS232 Serial Communication	using(SerialPort serial = new SerialPort())\n{\n    // do stuff\n}	0
19955916	19955736	Convert decimal currency to comma separated value	var input = "1,200.99";\n\n//Convert to decimal using US culture (or other culture using . as decimal separator)\ndecimal value = decimal.Parse(input, CultureInfo.GetCultureInfo("en-US"));\n\n//Convert to string using DE culture (or other culture using , as decimal separator)\nstring output = value.ToString(CultureInfo.GetCultureInfo("de-DE"));\n\nConsole.WriteLine(output); //1200,99	0
10446243	10446175	How do I write a generic Convert function?	public T ConvertByGenerics<T>(string value, T defaultValue)\n{\n   if (!string.IsNullOrEmpty(value))\n   {\n      return (T)Convert.ChangeType(value, typeof(T));\n   }\n\n   return defaultValue;\n}	0
14319957	14319920	JSON.NET deserialize results in list with default values	public class Change\n        {\n            public string clientId { get; set; }\n            public bool checkbox1Ticked { get; set; }\n            public bool checkbox2Ticked { get; set; }\n        }	0
26383222	26382945	How to change sitecore template of particular item using c# coding?	var template = Sitecore.Context.Database.Templates["/sitecore/templates/common/folder"];\nitem.ChangeTemplate( template );	0
11572134	11571907	Indomitable beast: a 2d char array, inside a structure, in the belly of an unmanaged dll	[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]\npublic struct Beast\n{\n    public BOOL fireBreathing;\n\n    [MarshalAs(UnmanagedType.ByValArray, SizeConst = 1500 )] /* 50x30 */\n    public char [] entrails;\n}\n\npublic class TamedBeast\n{\n    public Beast WildBeast;\n    public char[30][50] entrails\n    {\n      var 2dEntrails = new char[30][50];\n      var position = 0;\n      for (int first = 0; first <30; first++)\n      {\n         for (int second = 0; second <50; second++)\n         {\n             2dEntrails[first][second] = WildBeast.entrails[position++];\n         }\n      }\n      return 2dEntrails;\n    }\n}	0
20329718	20328910	Wait for Excel Interlop to Exit in C#	//Outside main\nprivate static bool isClosed = false;\n\n....\n\n//Let's say your Workbook object is named book\nbook.WorkbookBeforeClose += new Excel.AppEvents_WorkbookBeforeCloseEventHandler(app_WorkbookBeforeClose);\n\nif(isClosed)\nsendMailMethod();\n\n...\n\nprivate static void app_WorkbookBeforeClose(Excel.Workbook wb, ref bool cancel)\n    {\n        closed = !cancel;\n    }	0
6699460	6699410	Saving Particular Node in XML File	XmlDocument item = new XmlDocument();\nitem.PreserveWhitespace = true;\nitem.Load(xmlFileName);	0
30668699	30668342	How can I pass application control to another WPF window?	protected override void OnStartup(StartupEventArgs e)\n{\n    // Decide which window to show here\n    // Add bounds checks etc. \n    if (e.Args[0] == "-s")\n    {\n        var window = new ServerPage();\n        window.Show();\n    }\n    else\n    {\n        var window = new ClientPage();\n        window.Show();\n    }\n\n    Current.ShutdownMode = ShutdownMode.OnExplicitShutdown;\n    base.OnStartup(e);\n}	0
731489	731461	How to check for an Empty Gridview	DataTable data = DAL.getdata();\nif (data.Rows.Count == 0)\n{\n    ShowEmptyData();\n}\nelse\n{\n    Grid.DataSource = dt;\n    Grid.DataBind();\n}	0
1754644	1754615	How to assign a dynamic resource style in code?	tb.Style = (Style)FindResource("FormLabelStyle");	0
23538470	23538167	Most efficient way of evaluating independent variable for a similar outcome	class HandController : MonoBehaviour\n{\n    bool m_Tracked;\n\n    Color NotDetected { get { return Color.red; } }\n    Color Detected { get { return new Color(189/255.0f, 165/255.0f, 134/255.0f); } }\n\n    public bool Tracked\n    {\n        if (m_Tracked == value) return;\n        m_Tracked = value;\n        renderer.material.color = value ? Detected : NotDetected;\n    }\n}\n\n// ...\n\nLeftHand.Tracked = LeftHandTracked;\n\nif (TappedFingers.Length != FINGERS*2)\n{\n    Debug.LogError("Unexpected amount of fingers: " + TappedFingers.Length);\n    return;\n}\n\nfor(int i = 0; i < FINGERS; i++)\n{    \n    LeftHand.SetSide(TappedFingers[i], i);\n}\n\nfor(int i = FINGERS; i < FINGERS*2; i++)\n{    \n    RightHand.SetSide(TappedFingers[i], i-FINGERS);\n}	0
1261107	1261063	wait for a TXT file to be readable c#	using (var stream = new FileStream(@"c:\temp\file.txt", FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) {\n   using (var file = new StreamReader(stream)) {\n      while (!file.EndOfStream) {\n         var line = file.ReadLine();\n         Console.WriteLine(line);\n      }\n   }\n}	0
6722368	6703384	How to get details of all scheduled jobs and triggers in Quartz.NET c#	ISchedulerFactory schedFact = new StdSchedulerFactory();\nforeach (IScheduler scheduler in schedFact.AllSchedulers)\n{\n    var scheduler1 = scheduler;\n    foreach (var jobDetail in from jobGroupName in scheduler1.JobGroupNames\n                              from jobName in scheduler1.GetJobNames(jobGroupName)\n                              select scheduler1.GetJobDetail(jobName, jobGroupName))\n    {\n         //Get props about job from jobDetail\n    }\n\n    foreach (var triggerDetail in from triggerGroupName in scheduler1.TriggerGroupNames\n                                  from triggerName in scheduler1.GetTriggerNames(triggerGroupName)\n                                  select scheduler1.GetTrigger(triggerName, triggerGroupName))\n    {\n         //Get props about trigger from triggerDetail\n    }\n}	0
18704799	18704613	How to implement "retry/abort" mechanism for writing files that may be used by another process?	public static void WriteText(string filename, string text)\n{\n    bool retry = true;\n    while (retry)\n    {\n         try\n         {\n              System.IO.StreamWriter file = new System.IO.StreamWriter(filename);\n              file.Write(text);\n              file.Close();\n          }\n          catch(Exception exc)\n          {\n                MessageBox.Show("File is probably locked by another process.");\n                // change your message box to have a yes or no choice\n                // yes doesn't nothing, no sets retry to false\n          }\n    }\n}	0
23876605	23774949	Application crashes in XFCE using Mono and GTK#	Gtk.Application.Invoke (() => {\n          label.Text = "Done";\n    });	0
2687258	2687151	How can I dynamically set the event handler for a TabItem when it is selected?	Selector.AddSelectedHandler(item, (s,e) =>\n{\n    selectedControl = mcc;\n});	0
16944438	16940270	Click event is not firing when I click a control in dynamic usercontrol	public partial class UserControl2 : UserControl\n{\n\n    public UserControl2()\n    {\n        InitializeComponent();\n        WireAllControls(this);\n    }\n\n    private void WireAllControls(Control cont)\n    {\n        foreach (Control ctl in cont.Controls)\n        {\n            ctl.Click += ctl_Click;\n            if (ctl.HasChildren)\n            {\n                WireAllControls(ctl);\n            }\n        }\n    }\n\n    private void ctl_Click(object sender, EventArgs e)\n    {\n        this.InvokeOnClick(this, EventArgs.Empty); \n    }\n\n}	0
31824548	31824518	Convert byte array to TimeSpan or DateTime	var time = new TimeSpan(myArray[0], myArray[1], myArray[2]);	0
2097688	2097678	C# How can false == true ? See Picture	true = false	0
30486648	30484303	How can i get date from foreach for linq	string DateString = "";\nvar start = DateTime.Now;\nvar Dates = GetBusinessDays(start,-7);\nDates.Reverse();\nforeach (var date in Dates)\n{   \n   DateString  = DateString + "'" + date.ToShortDateString() + "',";\n } \n\nDateString = DateString.TrimEnd(',');\n\nvar book = from m in Connection.Db.Materials \n           where m.TypeId == 1 \n           group m by m.CreationDate into g select g;\n           var results = Dates.Select(d => new { Date = d.Day + "/" + d.Month + "/" + d.Year, Count = book.Where(g => g.Key.Day == d.Day && g.Key.Month == d.Month && g.Key.Year == d.Year).Count() }).ToList(); \n//put day, month and year. Because only dates  equals with ohter dates.(I need only dates not times)\n\nstring Books = "";\nforeach(var r in results)\n{\n  Books = Books + r.Count + ',';\n}	0
19376844	19376578	C# remove attribute from root node	var xml = @"<?xml version=""1.0"" encoding=""utf-8""?>\n<DirectedGraph xmlns=""http://schemas.microsoft.com/vs/2009/dgml"">\n  <Nodes>\n      <Node Id=""@101"" Category=""CodeSchema_ProjectItem"" FilePath=""$(ProgramFiles)\windows kits\8.0\include\um\unknwnbase.h"" Label=""unknwnbase.h"" />\n      <Node Id=""@103"" Category=""CodeSchema_ProjectItem"" FilePath=""$(ProgramFiles)\windows kits\8.0\include\shared\wtypesbase.h"" Label=""wtypesbase.h"" />\n  </Nodes>\n</DirectedGraph>";\n\nvar doc = new XmlDocument();\ndoc.LoadXml(xml);\n\nvar manager = new XmlNamespaceManager(doc.NameTable);\nmanager.AddNamespace("d", "http://schemas.microsoft.com/vs/2009/dgml");\n\nvar nodes = doc.DocumentElement.SelectNodes("/d:DirectedGraph/d:Nodes/d:Node", manager);\nConsole.WriteLine(nodes.Count);	0
1321610	1321248	How do I save/serialize a custom class to the settings file?	public class ReportType : ApplicationSettingsBase\n    {\n        private string displayName;\n        [UserScopedSetting()]\n        [SettingsSerializeAs(System.Configuration.SettingsSerializeAs.Xml)]\n        public string DisplayName\n        {\n            get { return displayName; }\n        }	0
23160405	22213504	Best Practice for kendo UI with MVC wrappers when data binding a detail grid	.Model(model => \n        {\n            model.Id(p => p.NoteId);\n            model.Field(p => p.PinId).DefaultValue("#=PinId#");\n        })	0
15258187	15257818	How to save a richtextbox data to a textfile without using the dialog?	string folder = @"C:\Users\TomJ\Record My Life files\" \nstring fileName = "testFile.txt";  \n\nFile.AppendAllText(folder + fileName, "test text to write to the file");	0
10876307	10876265	Convert 12 bit int to 16 or 32 bits	x = (x >> 11) == 0 ? x : -1 ^ 0xFFF | x;	0
5781141	5781124	Two variable sorting algorithm	using System.Linq;\n\nvar sortedPoints = points.OrderByDescending(p => p.Longitude).ThenBy(p => p.Latitude);	0
18292255	18292076	Characters between two exact characters	string input = "..........1............1...";\nint start = input.IndexOf('1');\nint end = input.LastIndexOf('1');\n\nchar[] content = input.ToCharArray();\nfor (int i = start; i <= end; i++)\n{\n    content[i] = content[i] == '1' ? '.' : '1'; //invert\n}\nstring output = new string(content);	0
6831700	6831159	Find Certificate by hash in Store C#	var cert = store.Certificates.Find(\n                                    X509FindType.FindByThumbprint,\n                                    thumbprint,\n                                    true\n                                  ).OfType<X509Certificate>().FirstOrDefault();	0
34029216	33760676	OWIN - Access External Claims in subsequent requests	public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<User, string> manager, IAuthenticationManager authentication = null)\n    {\n        // Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType\n        var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);\n        // Add custom user claims here\n\n        if (authentication != null)\n        {\n            ExternalLoginInfo info = authentication.GetExternalLoginInfo();\n\n            if (info != null)\n                foreach (Claim claim in info.ExternalIdentity.Claims.Where(claim => !userIdentity.HasClaim(c => c.Type == claim.Type)))\n                {\n                    userIdentity.AddClaim(claim);\n                    await manager.AddClaimAsync(userIdentity.GetUserId(), claim);\n                }\n        }\n\n        return userIdentity;\n    }	0
16328670	16325616	how to use DataGridViewButtonCell in DataGridViewButtonRow?	private void dataGridView1_CellClick(object sender, \n                                         DataGridViewCellEventArgs e)\n    {\n        for (int index = 0; index < dataGridView1.Rows.Count; index++)\n        {\n            DataGridViewRow dr = dataGridView1.Rows[index];\n            if (index == dataGridView1.CurrentCell.RowIndex)\n            {\n                DataGridViewTextBoxCell txtCell = new DataGridViewTextBoxCell();\n                dr.Cells[0] = txtCell;\n            }\n            else\n            {\n                DataGridViewButtonCell buttonCell = new DataGridViewButtonCell();\n                dr.Cells[0] = buttonCell;\n            }\n        }\n    }\n}	0
8381347	8381245	How to set current time to a value	DateTime end = DateTime.Now;\nDateTime start = new DateTime(2011, 12, 5, 12, 6,0);\n\ndouble hours = (end - start).TotalHours;	0
9734482	9734425	Converting binary reading function from C++ to C#	short[] buffer = new short[1024];                \n for (int i = 0; i < 1024; i++) {\n     buffer[i] = reader.ReadInt16();\n }	0
11980640	11980321	String to array	var list = input.Split(':');\nvar outputs = new List<string>();\n\nfor (int index = 0; index < list.Count(); index++)\n{\n     if (index % 4 == 3)\n         outputs.Add(list.ElementAt(index));\n}	0
29563025	29562656	Drag & Drop Shows Circle With Line Through It	public partial class Form1 : Form\n{\n    public Form1()\n    {\n        this.InitializeComponent();\n        this.AllowDrop = true;\n        this.DragDrop += new DragEventHandler(Form1_DragDrop);\n        this.DragEnter += new DragEventHandler(Form1_DragEnter);\n    }\n    private void Form1_DragDrop(object sender, DragEventArgs e)\n    {\n        if (e.Data.GetDataPresent(DataFormats.FileDrop))\n        {\n            string[] files = (string[])e.Data.GetData(DataFormats.FileDrop);\n            foreach (var file in files)\n            {\n                MessageBox.Show(file);\n            }\n        }\n    }\n\n    private void Form1_DragEnter(object sender, DragEventArgs e)\n    {\n        if (e.Data.GetDataPresent(DataFormats.FileDrop))\n        {\n            e.Effect = DragDropEffects.Copy;\n        }\n    }\n}	0
31910805	31887729	File download issue with api controller	using System.Net;\n   using System.Net.Http;\n   using System.Net.Http.Headers;\n   using System.Text;\n   using System.Web.Http;\n\n   namespace WebApplication1.Controllers\n   {\n    public class ValuesController : ApiController\n    {\n        // GET: api/Values\n        public HttpResponseMessage Get()\n        {\n            var xmlString = "<xml><name>Some XML</name></xml>";\n            var result = Request.CreateResponse(HttpStatusCode.OK);\n            result.Content = new StringContent(xmlString, Encoding.UTF8, "application/xml");\n            result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")\n            {\n                FileName = "test.xml"\n            };\n\n            return result;\n        }\n    }\n   }	0
19269593	19269487	How to access a database	using (var sqlConnSource = new SqlConnection(SqlSource))\n        {\n            sqlConnSource.Open();\n            var myProducts = sqlConnSource.Query<Class1>("SELECT * FROM Products").ToList();\n            foreach (var p in myProducts)\n            {\n                //do something more useful here if you want\n              Console.Writeline("The product name is:" + p.Name)\n\n            }\n        }	0
8265744	8265448	c# Override a dependency property of an system control	System.Windows.Controls.GroupBox.HeaderProperty.OverrideMetadata(\n            typeof(CheckableGroupBox), \n            new PropertyMetadata("", OnHeaderChangedCallback)\n            );	0
22392586	22392362	Making a JSON-RPC HTTP call using C#	using (var webClient = new WebClient())\n{\n    var response = webClient.UploadString("http://user:pass@localhost:8080/jsonrpc", "POST", json);\n}	0
33571681	33571564	How to create a Random Unique number in C# using a Recursive Method?	static Random randomObject = new Random();\n\nstatic void Main(string[] args)\n{\n    long[] randomArr = new long[5];\n\n    for (int i = 0; i < randomArr.Length;)\n    {\n        long t = randomObject.Next(1, 11);\n        if(CheckIfUnique(t, randomArr, i))\n        {\n              randomArr[i++] = t;\n        }\n    }\n}\n\nstatic bool CheckIfUnique(long a, long[] b, int length)\n{\n    for (int i = 0; i < length; i++) \n    {\n        if (a == b[i])\n        {\n           return false\n        }\n    }\n    return true;\n}	0
4106512	4106472	How to unhook eventhandlers in C#	protected override void OnClosing(CancelEventArgs e) {\n    SomeClass.MotionCompleted -= new EventHandler(HandlerMethod);\n}	0
15563544	15563069	How to read values separated by semi colon in a sharepoint user profile?	var strUser = up.GetProfileValueCollection(PropertyConstants.Responsibility);	0
424769	424739	Programmatically Accessing SharePoint Style Library from within C#	SPList list = web.Lists["MyLibrary"];\n            if (list != null)\n            {\n                var results = from SPListItem listItem in list.Items\n                              select new \n                              {\n                                  xxx = (string)listItem["FieldName"]),\n                                  yyy  = (string)listItem["AnotherField"],\n                                  zzz = (string)listItem["Field"]\n                              };\n            }	0
20828774	20828678	How can I restrict a delegating handler to a specific route in Web API?	public static class WebApiConfig\n{\n    public static void Register(HttpConfiguration config)\n    {\n        config.Routes.MapHttpRoute(\n            name: "Route1",\n            routeTemplate: "api/{controller}/{id}",\n            defaults: new { id = RouteParameter.Optional }\n        );\n\n        config.Routes.MapHttpRoute(\n            name: "Route2",\n            routeTemplate: "api2/{controller}/{id}",\n            defaults: new { id = RouteParameter.Optional },\n            constraints: null,\n            handler: new MessageHandler2()  // per-route message handler\n        );\n\n        config.MessageHandlers.Add(new MessageHandler1());  // global message handler\n    }\n}	0
15325695	15325391	Want to capture screen shot of minimize window	protected virtual void OnMinimize(EventArgs e)\n{\n    Rectangle r = this.RectangleToScreen(ClientRectangle);\n\n    if (_lastSnapshot == null)\n    {\n        _lastSnapshot = new Bitmap(r.Width, r.Height);\n    }\n\n    using (Image windowImage = new Bitmap(r.Width, r.Height))\n    using (Graphics windowGraphics = Graphics.FromImage(windowImage))\n    using (Graphics tipGraphics = Graphics.FromImage(_lastSnapshot))\n    {\n        windowGraphics.CopyFromScreen(new Point(r.Left, r.Top), new Point(0, 0), new Size(r.Width, r.Height));\n        windowGraphics.Flush();\n\n        tipGraphics.DrawImage(windowImage, 0, 0, r.Width, r.Height);\n    }\n}	0
5726691	5726601	Generic repository lifetime configuration with Windsor	public class RepositoryFactory : IRepositoryFactory\n{\n   protected DataContext dataContext;\n   public RepositoryFactory(IDataContextProvider provider)\n   {\n      dataContext = dataContextProvider.DataContext;\n   }\n\n   public IRepository<T> GetRepository<T>()\n   {\n      return new Repository<T>(dataContext);\n   }\n}\n\npublic class SimpleService : ISimpleService {\n     public SimpleService(IRepositoryFactory factory) {\n         ....\n     }\n}	0
9316625	9316580	Day Rendering Calendar based on "Bookings" from MySQL table ASP.NET C#	while (reader.Read())\n{\n  //do your processing here to check the Calendar stuff \n}	0
6655285	6655246	How to read text file by particular line separator character?	string text = sr.ReadToEnd();\nstring[] lines = text.Split('\r');\nforeach(string s in lines)\n{\n   // Consume\n}	0
17208888	17208554	DeserializeObject with Newtonsoft list in a list	public class Items\n{\n    public string Id { get; set; }\n    public string Name { get; set; }\n    public string Genre { get; set; }\n    public string Description { get; set; }\n    public List<Version> Versions { get; set; }\n}\n\npublic class Version\n{\n    public string Appid { get; set; }\n    public string Version { get; set; }\n    public string Patch_Notes { get; set; }\n    public string Download_Link { get; set; }\n    public int Size { get; set; }\n}	0
502323	502303	How do I programmatically get the GUID of an application in .net2.0	using System.Reflection;\n\nAssembly assembly = Assembly.GetExecutingAssembly();\n\n//The following line (part of the original answer) is misleading.\n//**Do not** use it unless you want to return the System.Reflection.Assembly type's GUID.\nConsole.WriteLine(assembly.GetType().GUID.ToString());\n\n\n// The following is the correct code.\nvar attribute = (GuidAttribute)assembly.GetCustomAttributes(typeof(GuidAttribute),true)[0];\nvar id = attribute.Value;	0
10432863	10432808	Get a comma separated list of entity collection using linq	var r = _rs.Lines.Where(y => y.InvoiceNo == o.InvoiceNo).ToList().Select(x => new\n{\n    ReturnNo = x.Return.ReturnNo,\n    Part = x.Part,\n    Tags = String.Join(", ", x.Tags.Select(t => t.Name))\n});	0
28635481	28635208	Retrieve the Current App version from Package	public static string GetAppVersion()\n{\n\n  Package package = Package.Current;\n  PackageId packageId = package.Id;\n  PackageVersion version = packageId.Version;\n\n  return string.Format("{0}.{1}.{2}.{3}", version.Major, version.Minor, version.Build, version.Revision);\n\n}	0
14911057	14897345	does not contain a definition for 'Form' ? Outlook Add-in	this.TextBoxName.Text;	0
11509306	11509197	Parse Json array into object	public class MyClass\n{\n       [DataMember(Name = "location")]\n       public double[] Location { get; set; }\n\n       public Coordinate Coordinate\n       {\n            get\n            {\n                  if(Location.Lenght > 2)\n                  {\n                        return new Coordinate() { Lat = Location[0], Lang = Location[1] };\n                  }\n\n                  return null;\n            }\n       }\n\n}\n\npublic class Coordinate\n{\n      public double Lat { get; set;}\n      public double Lang { get; set;}\n}	0
30671561	30671489	How to capture type of a local variable inside a lamda expression in linq	public IEnumerable<AbstractFoo> GetMatchingFoos<T>() where T : AbstractFoo\n{\n    return exactMatchList.OfType<T>();\n}	0
8816676	8816577	Custom Membership provider with dependency injection - how to test	var prov = new CableSenseMembershipProvider(new FakeUserRepository());\n        var config = new NameValueCollection();\n        config.Add("applicationName", "ddd");\n        config.Add("name", "CustomMembershipProvider");\n        config.Add("requiresQuestionAndAnswer", "false");\n        config.Add("requiresUniqueEmail", "false");\n        prov.Initialize(config["name"], config);	0
12220916	12220617	How do I find all occurrences of a specific sentence within a string?	string str = "Today is friday! I'm am having trouble programming this. Today is friday! Tomorrow is saturday. Today is friday!";\n\nStringBuilder sb = new StringBuilder();\nint index = 0;\ndo\n{\n    index = str.IndexOf("Today is friday!", index);\n    if (index != -1)\n    {\n        sb.Append("Today is friday!");\n        index++;\n    }\n} while (index != -1);\n\nstring repeats = sb.ToString();	0
6544046	6543984	How can I sort the results of a LINQ query	var _rowData = ...\nvar _rowDataSortedByRowKey = _rowData.OrderBy( u => u.RowKey );\nvar _rowDataSortedByModifiedToString = _rowData.OrderBy( u => u.ModifiedToString );\nvar _rowDataSortedByShortTitle = _rowData.OrderBy( u => u.ShortTitle );\nvar _rowDataSortedByOther = _rowData.OrderBy( ... );	0
29426486	26527520	Stream from IP cam C#	using (webRes = webReq.GetResponse())\n{\n    using (sr = webRes.GetResponseStream())\n    {\n        // continuously read images from the response stream until error\n        while (true)\n        {\n            try\n            {\n                // note: the line below probably won't work, you may need to parse\n                // the next image from the multi-part response stream manually\n                image.Image = Image.FromStream(sr);\n\n\n                // if the above doesn't work, then do something like this:\n                // var imageBytes = ParseNextImage(sr);\n                // var memoryStream = new MemoryStream(imageBytes);\n                // image.Image = Image.FromStream(memoryStream);\n            }\n            catch(Exception e)\n            {\n                Console.WriteLine("Aborting read from response stream due to error {0}", e);\n                break;\n            }\n        }\n    }\n}	0
13972735	13972580	Lambda Expression definition (pedant )?	MySquareDelegate f1 = x => x * x;\nMySquareDelegate f2 = new MySquareDelegate(MySquareMethod);\nMySquareDelegate f3 = MySquareMethod;  // just shorthand for the previous line	0
5025603	5025376	c# preventing inheritance of a method	public class clCardsHeld\n{\n    private List<clCards> _liCards;\n\n    public clCardsHeld GetLoHand()\n    {\n        //Logic here for returning the low hand, using _liCards\n    }\n\n    public clCardsHeld GetHiHand()\n    {\n        //Logic here for returning the high hand, using _liCards\n    }\n}	0
19305798	19131159	Dependency property changed callback - multiple firing	this.Unloaded += CustomControlUnloaded;\n\nprivate void CustomControlUnloaded(object sender, RoutedEventArgs e)\n{\n    this.ClearValue(CustomControl.IsOpenProperty);\n}	0
4901690	4901592	Get Name of Selected ListBoxItem on Button Click	ListBoxItem selItem = (ListBoxItem)dbTables.SelectedValue;\n\n        Console.WriteLine(selItem.Content);	0
15121408	15121218	How to get hidden field value when check box is checked in a repeater controller?	protected void CheckBox1_CheckedChanged(object sender, EventArgs e)\n{\n    var checkBox = (CheckBox) sender;\n    var reminderHiddenField = (HiddenField)checkBox.NamingContainer\n        .FindControl("hf_reminderID");\n}	0
5829420	5828998	handle multiple controls with same name in form collection	foreach (var key in form.AllKeys.Where(k => k.StartsWith("UserName")))\n        {\n            var index = key.Replace("UserName", "");\n            var userName = form[key];\n            var userComment = form["UserComments" + index];\n        }	0
3059792	3059759	Double.ToString with N Number of Decimal Places	public void DisplayNDecimal(double dbValue, int nDecimal)\n {\n   Console.WriteLine(dbValue.ToString("N" + nDecimal));\n }	0
7632022	7631740	Windows phone 7 web browser control user agent	webBrowser.Navigate("http://localhost/run.php", null, "User-Agent: Here Put The User Agent");	0
28761980	28761927	Local variable unused in a using statement	//unused variable will not give warning\nusing (new DialogWindow(Dialogs.MyDialogType))\n{\n   //Some action here\n}	0
28452204	28436097	C# TreeView Programmatically Adding Child Nodes With GrandChildren And So On	//Generate variables for the recursive Method\n    TreeView tree = treeView1;\n    TreeNode treeNode;\n\n    //You set the current Node to be the Parent\n    treeNode = tree.Nodes.Add("rootDevice");\n\n    //Now if the root device has a child\n    treeNode = tree.Nodes.Add("childDevice");\n\n    // If the child has a child\n    treeNode = tree.Nodes.Add("grandChildDevice");	0
28577632	28577292	inheriting a read-only property	[EditorBrowsable(EditorBrowsableState.Never)]\n[BrowsableAttribute(false)]\n[ComVisible(false)]\npublic new Control.ControlCollection Controls { \n    get { return base.Controls; } }	0
5067192	5067141	How to create pages with different permissions' views	public ActionResult Profile()\n{\n    //Based on business logic, set variables \n    if(userProfile)\n    {\n        return View("Profile");\n    }\n    else if(friendProfile)\n    {\n        return View("FriendProfile");\n    }\n}	0
33039014	33036403	Allow Azure services to connect to Azure SQL Server by API	internal string CreateFirewallRule(string serverName)\n{\n    var firewallParameters = new FirewallRuleCreateParameters();\n    firewallParameters.Name = "AllowAll";\n    firewallParameters.StartIPAddress = "0.0.0.0";\n    firewallParameters.EndIPAddress = "0.0.0.0";\n    var response = _sqlMgmtClient.FirewallRules.Create(serverName, firewallParameters);\n    return response.StatusCode.ToString();\n}	0
24142809	24142738	C# sort string of comma separated numbers	using System.Linq; // no include required, just uses the namespace\n\n  ...\n\n  String Input = "1,3,2,5,4";\n\n  String Output = String.Join(",", Input.Split(',')\n    .Select(x => int.Parse(x))\n    .OrderBy(x => x));	0
27806658	27806606	Sub expression that returns a value	7.13.1 Simple assignment	0
6267129	6253906	Excel Jet OLE DB: Inserting a DateTime value	DateTime org = DateTime.UtcNow;\nDateTime truncatedDateTime = new DateTime(org.Year, org.Month, org.Day, org.Hour, org.Minute, org.Second);	0
24272288	24272236	How do I use RegEx to pick longest match?	String pattern = ("(hello world|hello)");	0
430596	430590	Open Source HTML to PDF Renderer with Full CSS Support	htmldoc --webpage -t pdf --size letter --fontsize 10pt index.html > index.pdf	0
3375229	3375221	How to add to a list not yet created. Please help!	class EmployeeManager\n{\n    // Declare this at the class level\n    List<string> employeeList;\n\n    public EmployeeManager()\n    {\n         // Assign, but do not redeclare in the constructor\n         employeeList = new List<string>();\n    }\n\n    public void AddEmployee()\n    {\n         // This now exists in this scope, since it's part of the class\n         employeeList.add("Donald");\n    }\n}	0
8303415	8303392	Access a private variable	namespace Test\n{\n    public class Calculator\n    {\n        public Calculator() { ... }\n        private double _number;\n        public double Number { get { ... } set { ... } }\n        public void Clear() { ... }\n        private void DoClear() { ... }\n        public double Add(double number) { ... }\n        public static double Pi { ... }\n        public static double GetPi() { ... }\n    }\n}\n\nCalculator calc = new Calculator();\n\n// invoke private instance method: private void DoClear()\ncalcType.InvokeMember("DoClear",\n    BindingFlags.InvokeMethod | BindingFlags.Instance | BindingFlags.NonPublic,\n    null, calc, null);	0
17252464	17252279	Custom Wide Tile in Windows Phone 8	FlipTileData TileData = new FlipTileData()\n{\n   Title = "[title]",\n   BackTitle = "[back of Tile title]",\n   BackContent = "[back of medium Tile size content]",\n   WideBackContent = "[back of wide Tile size content]",\n   Count = [count],\n   SmallBackgroundImage = [small Tile size URI],\n   BackgroundImage = [front of medium Tile size URI],\n   BackBackgroundImage = [back of medium Tile size URI],\n   WideBackgroundImage = [front of wide Tile size URI],\n   WideBackBackgroundImage = [back of wide Tile size URI],\n};\n\nShellTile.Create(new Uri("/LiveTimes.xaml?name=" + busStopName.Text, UriKind.Relative), TileData, true);	0
19490297	19490046	Custom visual web part properties sharepoint	[WebBrowsable(true),\n     WebDisplayName("Page Title"),\n     WebDescription("Title displayed on the page"),\n     Category("Test Properties"),\n     Personalizable(PersonalizationScope.Shared)]\n    public string PageTitle\n    {\n        get\n        {\n            return _pageTitle;\n        }\n        set\n        {\n            _pageTitle = value;\n        }\n    }	0
19594344	19593842	how do I convert this code to NOT ask for a printer, just print to default printer?	RawPrinterHelper.SendStringToPrinter(new PrinterSettings().PrinterName, s);	0
772790	772633	Error in Gridview application	protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)\n{\n    GridView1.PageIndex = e.NewPageIndex;\n    DataBind();\n}	0
8624876	8624824	Iterate through files on a certain level	var files = \n    (from dir in Directory.GetDirectories(root)\n     from subdir in Directory.GetDirectories(dir)\n     from f in Directory.GetFiles(subdir)\n     select f).ToList();\n\nvar fileCount = files.Length;\nforeach (var f in files) {\n    ...\n}	0
27782075	27781986	Cut a special char in c#	string[] usuario = identitiname.Split( '\\' );	0
1950772	1950752	Check for value in list	return myList.Any(o => o.ID == idToCheckFor);	0
11881381	11881362	Console.Write() - Where does this write to, and how to get written data back (in a Web Page)	System.Diagnostics.Debug.WriteLine()	0
32042972	32036880	How to restrict touch movement for android on Unity	void Update () {\n\n     if (Input.touchCount == 1) {\n\n         Touch touch = Input.touches[0];\n         if(touch.position.x < Screen.width/2){\n             transform.position += Vector3.left * carSpeed * Time.deltaTime;\n\n\n         }\n         else if(touch.position.x > Screen.width/2){\n             transform.position += Vector3.right * carSpeed * Time.deltaTime;\n\n         }\n         Vector3 position = transform.position;\n         position.x = Mathf.Clamp(position.x, -4.2f, 4.2f);\n         transform.position = position;\n\n     }\n }	0
12335552	12335487	How can I easily convert legacy code to WCF?	public interface ICommandServer\n{\n    void Execute(string command, string[] args);\n}	0
15573052	15572450	datagridview change row color, when date expired or less	foreach (DataGridViewRow row in dataGridView1.Rows)\n        {\n            var now = DateTime.Now;\n            var expirationDate =  DateTime.Parse(row.Cells[0].Value.ToString());\n            var sevenDayBefore = expirationDate.AddDays(-7);\n\n            if (now > sevenDayBefore && now < expirationDate)\n            {\n                row.DefaultCellStyle.BackColor = Color.Yellow;\n            }\n            else if (now > expirationDate)\n            {\n                row.DefaultCellStyle.BackColor = Color.Red;    \n            }\n        }	0
27235842	27235643	read from txt file and get specific text	var dict = Regex\n               .Matches(str, @"\[([^\]]+)\]([^\[]+)")\n               .Cast<Match>()\n               .ToDictionary(match => match.Groups[1].ToString(), \n                             match => match.Groups[2].ToString().Trim());\n\n//dict = { [Product Code, MYPRODUCT-CODE123], [List Price, 28.10], [Price, 20.30] ...}	0
17207842	17207790	Json Converted array is a string?	var array = JSON.parse(myJsonString);	0
6843498	6818595	Access Textbox content that is inside a detailsView cell	TextBox txt = (TextBox)DETAILSVIEW_ID.FindControl("TEXTBOX_ID") as TextBox;\nstring tmp = txt.Text;	0
24056134	24043659	Read a list of dynamic objects into CSV	using (var dt = new DataTable())\n{\n     var keys = responses.SelectMany(x => ((IDictionary<string, object>)x).Keys).Distinct();\n     var columns = keys.Select(x => new DataColumn(x)).ToArray();\n     dt.Columns.AddRange(columns);\n\n     foreach(IDictionary<string, object> response in responses)\n     {\n         var row = dt.NewRow();\n         foreach (var kvp in response)\n         {\n             row[kvp.Key] = kvp.Value;\n         }\n         dt.Rows.Add(row);\n     }\n\n     // write to CSV\n}	0
12973938	12973813	C# display all files from selected folder	public void  selectfolders(string filename)\n{\n    FileInfo_Class fclass;\n    DirectoryInfo dirInfo = new DirectoryInfo(filename);\n\n    FileInfo[] info = dirInfo.GetFiles("*.*");\n    foreach (FileInfo f in info)\n    {\n        fclass = new FileInfo_Class();\n        fclass.Name = f.Name;\n        fclass.length = Convert.ToUInt32(f.Length);\n        fclass.DirectoryName = f.DirectoryName;\n        fclass.FullName = f.FullName;\n        fclass.Extension = f.Extension;\n        obcinfo.Add(fclass);\n    }\n    DirectoryInfo[] subDirectories = dirInfo.GetDirectories();\n    foreach(DirectoryInfo directory in subDirectories)\n    {\n        selectfolders(directory.FullName);\n    }\n}	0
16305098	16304469	How to add new row to excel file in C#	Range Line = (Range)worksheet.Rows[3];\nLine.Insert();	0
3823304	3823050	DLLImport c++ function with default parameters	[DllImport("mydll.dll", EntryPoint = "somefunction")] \nstatic extern int somefunction(int param1, IntPtr param2);\n\nstatic int somefunction(int param1) {\n  someFunction(param1, IntPtr.Zero);\n}	0
30869585	30856317	Recursive Joins with Linq	var craftList = from craft in db.GetTable<Craft>()\n                join craftProduct in db.GetTable<CraftProduct>() on craft.ID equals craftProduct.CraftID into\n                    craftProducts\n                join craftMaterial in db.GetTable<CraftMaterial>() on craft.ID equals craftMaterial.CraftID into\n                    craftMaterials\n                select new\n                {\n                    Craft = craft,\n                    CraftProducts = from craftProduct in craftProducts\n                                    join item in db.GetTable<Item>() on craftProduct.ItemID equals item.ID\n                                    select CraftProduct.Build(craftProduct, item),\n                    CraftMaterials = from craftMaterial in craftMaterials\n                                     join item in db.GetTable<Item>() on craftMaterial.ItemID equals item.ID\n                                     select CraftMaterial.Build(craftMaterial, item)\n                };	0
8199035	8199005	Copy Constructor going to base constructor and overwriting copied values	public SprinklerLineModel()\n{\n    NearCrossMainDimension = new PipeDimensionModel();\n    FarCrossMainDimension = new PipeDimensionModel();\n    Init();\n}\n\npublic SprinklerLineModel(SprinklerLineModel sprinklerLineModel)\n{\n    this.EstimatedFlow = sprinklerLineModel.EstimatedFlow;\n    this.EstimatedPressure = sprinklerLineModel.EstimatedPressure;\n    this.NearCrossMainDimension = new PipeDimensionModel(sprinklerLineModel.NearCrossMainDimension);\n    this.FarCrossMainDimension = new PipeDimensionModel(sprinklerLineModel.FarCrossMainDimension);\n    this.BranchLineDiameter = sprinklerLineModel.BranchLineDiameter;\n    this.LeadLinePipeFittingLength = sprinklerLineModel.LeadLinePipeFittingLength;\n    this.ExbPipeFittingLength = sprinklerLineModel.ExbPipeFittingLength;\n    this.IsDirty = sprinklerLineModel.IsDirty;\n    Init();\n}\n\nvoid Init()\n{\n    this.AddValidationRule(Rule.CreateRule(() => BranchLineDiameter, RuleMessage.GREATER_THAN_ZERO, () => BranchLineDiameter > 0));\n}	0
20887275	20839655	Using Form to dynamically generate buttons/panels for a Rule Engine	int controlHeight = 0;\n    foreach (CNewControl newControl in newControlList)\n      {\n        this.newControlsTab.Controls.Add(newControl );\n        newControl.Dock = DockStyle.Top;\n        newControl.Location = new System.Drawing.Point(40, 3 + controlHeight);\n        controlHeight += newControl .Size.Height;\n      }	0
11867770	11867729	insert into sql db a string that contain special character '	string query = "insert into ACTIVE.dbo.Workspaces_WsToRefile values(@folderID, @newWorkSpace, @createDate)";\n\nusing(SqlCommand cmd = new SqlCommand(query, SqlConnection))\n{\n\n    SqlParameter param = new SqlParameter("@folderID", folderId);\n    param.SqlDbType = SqlDbType.Int;\n    cmd.Parameters.Add(param);\n    .....\n}	0
970134	970017	How do I handle a failed DllImport?	public static string GetKnownFolderPath(Guid guid)\n{\n  try\n  {\n    IntPtr pPath;\n    int result = SHGetKnownFolderPath(guid, 0, IntPtr.Zero, out pPath);\n    if (result == 0)\n    {\n        string s = Marshal.PtrToStringUni(pPath);\n        Marshal.FreeCoTaskMem(pPath);\n        return s;\n    }\n    else\n        throw new System.ComponentModel.Win32Exception(result);\n  }\n  catch(EntryPointNotFoundException ex)\n  {\n    DoAlternativeSolution();\n  }\n}	0
18240965	18240567	How can I use Rx to observe a falling edge?	IObservable<int> source = new[] { 8, 7, 6, 5, 4, 3, 2, 1, 0, 5, 4, 3, 2, 1, 0, 4 }.ToObservable();\nIObservable<int> edges = source.Zip(source.Skip(1), (f, s) => Tuple.Create(f, s))\n    .Where(t => t.Item1 > 0 && t.Item2 == 0)\n    .Select(t => t.Item2);	0
2172419	2171968	Collect all windows handlers	public class WindowFinder\n{\n    private class Helper\n    {\n\n        internal List<IntPtr> Windows = new List<IntPtr>();\n\n        internal bool ProcessWindow(IntPtr handle, IntPtr parameter)\n        {\n            Windows.Add(handle);\n            return true;\n        }\n    }\n\n    private delegate bool EnumWindowProc(IntPtr hWnd, IntPtr parameter);\n\n    [DllImport("user32.dll")]\n    [return: MarshalAs(UnmanagedType.Bool)]\n    private static extern bool EnumChildWindows(IntPtr hwndParent, EnumWindowProc lpEnumFunc, IntPtr lParam);\n\n    public static List<IntPtr> GetChildWindows(IntPtr parentWindow)\n    {\n        var helper = new Helper();\n        EnumChildWindows(parentWindow, helper.ProcessWindow, IntPtr.Zero);\n        return helper.Windows;\n    }\n}	0
7836828	7836722	Accessing dataset schema + data from another class	class A\n{\n   public void OnButtonClick(object sender, Event arg)\n   {\n      DataSet dataSet = ....\n\n      B je = new B();      \n      js.ProcessData(dataSet);\n   }\n}\n\nclass B\n{\n   public void ProcessData(DataSet dataSet)\n   {\n      foreach (DataRow dtrHDR in dataSet.Tables["Header"].Rows)\n   }\n}	0
25655100	25655035	Find all locked users in AD using c#	var lockedUsers = new List<UserPrincipal>();\n        using (var context = new PrincipalContext(ContextType.Domain))\n        {\n            GroupPrincipal grp = GroupPrincipal.FindByIdentity(context, IdentityType.SamAccountName, "Domain Users");\n            foreach (var userPrincipal in grp.GetMembers(false))\n            {\n                var user = UserPrincipal.FindByIdentity(context, IdentityType.SamAccountName, userPrincipal.UserPrincipalName);                        \n                if (user != null)\n                {\n                    if (user.IsAccountLockedOut())\n                    {\n                        lockedUsers.Add(user);\n                    }\n                }\n            }\n        }\n//Deal with list here	0
19763628	19762156	checkbox Event in DataGridViewTemplate WPF	public bool Ins {\n  get { return _ins; }\n  set { _ins = value; CallYourDBHere(); }\n}	0
8246371	8246167	How do I gracefully kill managed applications on shutdown?	Excel.Application xl = new Excel.Application();\nxl.Visible = false;\nxl.DisplayAlerts = false;\n\n//do something\n\nxl.Quit();\nMarshal.ReleaseComObject(xl);\nxl = null;\nGC.Collect();	0
23842930	23833830	Defocusing TextBox by clicking it again	private void txtKey_Enter(object sender, EventArgs e)\n{\n    TextBox textBox = (TextBox)sender;\n    textBox.Tag = null;\n}\n\nprivate void txtKey_Click(object sender, EventArgs e)\n{\n    TextBox textBox = (TextBox)sender;\n    if (textBox.Tag != null) label1.Focus();\n    textBox.Tag = "clicked";\n}	0
3902150	3902125	Stop two controls triggering each other's event	private void MyTreeView_AfterSelect (object sender, EventArgs e) {\n    if (MyTreeView.SelectedNode == node2 && MyTab.SelectedIndex != 1 ) {\n        MyTab.SelectedIndex = 1;\n    }\n}	0
4701183	4694631	How to implement async file download in C# ActiveX	public void Load(int fFullyAvailable, IMoniker pmk, IBindCtx pbc, uint grfMode)\n {\n     if (pmk == null)\n         throw new ArgumentNullException("pmk");\n\n     string url;\n     pmk.GetDisplayName(null, null, out url);\n\n     // Use the moniker to download the persisted data\n     // and obtain an IStream on that data\n     Guid iid = InterfaceID.IID_IStream;\n     object pStream;\n     pmk.BindToStorage(pbc, null, ref iid, out pStream);\n\n     // do whatever you want with the data inside pStream\n     ...\n}	0
4290818	4290311	Conditional visibility of combo box	int roleId \n\nif(int.TryParse(Session["RoleID"].ToString(),out roleId))\n {\n   cmbempList.Visible = ((roleId == 3) && CheckMentorAccess());\n }	0
21710316	21710255	Send Email Support Tickets without entering my email credentials in the source code	Process.Start("mailto:mail@mail.com");	0
14745146	14744628	WPF MouseMove event of listview	private void listView_MouseMove(object sender, MouseEventArgs e)\n    {\n        var item = Mouse.DirectlyOver;\n\n        if (item != null && item is TextBlock)\n            Debug.Print((item as TextBlock).Text);\n    }	0
13109547	13109309	How to define generic class that derivative from some base class?	class A : ICloneable\n    {\n        public object Clone()\n        {\n            throw new NotImplementedException();\n        }\n        public override string ToString()\n        {\n            return "Demo";\n        }\n    }\n    class B<T> where T : A\n    {\n        T myT;\n\n        public B(T value)\n        {\n            this.myT = value;\n        }\n\n        //hack the default indexer to instead allow it to be used to return N clones of myT\n        public IEnumerable<T> this[int index]\n        {\n            get\n            {\n                for (int i = 0; i < index; i++)\n                {\n                    yield return (T)this.myT.Clone();\n                }\n            }\n        }\n    }\n\n    class Program\n    {\n        public static void Main(string[] args)\n        {\n            B<A> myB = new B<A>(new A());\n            Console.WriteLine( myB[1].ToString());\n            Console.ReadKey();\n        }\n    }	0
9505846	9503639	Add toolbox icon from the class I derive	[ToolboxBitmap(typeof(Button), "foo.Resources.Button.bmp")]	0
13130293	13130272	Linq - isolate lambda as a delegate	Func<Object, bool> expression1 = (o => o.propertXyz == otherObj.propertyXyz);\nmyObject.firstOrDefault(expression1);	0
10007865	10007777	Load arraylist into a TextBox	foreach (var item in list1.OfType<string[]>().SelectMany(i => i))\n{\n    textBox1.AppendText(item);\n}	0
27681658	27656597	ExchangeService: connecting without credentials, how to retrieve user information?	Folder chk = Folder.Bind(service, WellKnownFolderName.Inbox);\n        AlternateId aiItem = new AlternateId();\n        aiItem.Mailbox = "Blah@Blah.com";\n        aiItem.UniqueId = chk.Id.UniqueId;\n        aiItem.Format = IdFormat.EwsId;\n        String CasServer = service.Url.Host.ToString();\n        AlternateIdBase caid = service.ConvertId(aiItem, IdFormat.HexEntryId);\n        Console.WriteLine(((AlternateId)caid).Mailbox);	0
25036782	25035332	How runtime knows the exact type of a boxed value type?	int i = 123;                    // A value type\n        object box = i;                 // Boxing\n        long j = Convert.ToInt64(box);  // Conversion + unboxing	0
12159066	12155317	insert dynamic images in a crystal reports page from the image folder	private void getImage()\n    {\n        FileStream fs;\n        fs = new FileStream(AppDomain.CurrentDomain.BaseDirectory + "img\\cube.png", FileMode.Open);\n        BinaryReader BinRed = new BinaryReader(fs);\n        try\n        {\n            CreateTable();\n            DataRow dr = this.DsImages.Tables["images"].NewRow();\n            dr["image"] = BinRed.ReadBytes((int)BinRed.BaseStream.Length);\n            this.DsImages.Tables["images"].Rows.Add(dr);\n\n            //FilStr.Close();\n            BinRed.Close();\n\n            DynamicImageExample DyImg = new DynamicImageExample();\n            DyImg.SetDataSource(this.DsImages);\n            this.crystalReportViewer1.ReportSource = DyImg;\n        }\n        catch (Exception er)\n        {\n            MessageBox.Show(er.Message, "Error");\n        }\n    }	0
21395832	21395102	Returning Tuple with one parameter as generic: Tuple<bool, T>	type SomeClass() =\n    interface IRule with\n        member this.Getrule<'T>(keyfield):bool * 'T =\n            let value = 3\n            (true,unbox box value )	0
23525217	20142185	Auto advancing state machine with Stateless	Task.Start(() => _stateMachine.Fire(trigger));	0
25557964	25557785	Extract username from DOMAIN\Username c#	User.Identity.GetUserName().Split('\\')[1]	0
6993454	6993407	Cannot access a disposed object?	private void Max_FormClosing(object sender, FormClosingEventArgs e)    {        \n   this.Hide();        \n   this.Parent = null;    \n   e.Cancel=true;\n}	0
3284668	3283074	WPF DataBinding: Cancelled property change - Combobox misaligns	protected void SetProperty<T>(String propertyName, ref T property, T value)\n{\n    if (!Object.Equals(property, value))\n    {\n        bool cancelled = OnPropertyChanging<T>(propertyName, property, value);\n\n        if (cancelled)\n        {\n            Application.Current.Dispatcher.BeginInvoke(\n                new Action(() =>\n                {\n                    OnPropertyChanged<T>(propertyName);\n                }),\n                DispatcherPriority.ContextIdle,\n                null\n            );\n\n            return;\n        }\n\n        T originalValue = property;\n        property = value;\n        OnPropertyChanged(propertyName, originalValue, property);\n    }\n}	0
13886723	13879163	Generate URL to Maps application in Windows 8	await Windows.System.Launcher.LaunchUriAsync(new Uri("bingmaps:?cp=40.726966~-74.006076"));	0
17076485	17076451	Returning a List of type from web service	List<T>	0
21423024	21420106	Compare a Part of the date using linq	var updateDateString = "2010-06-11";\nDateTime updateDate;\n\nif (DateTime.TryParse(updateDateString, out updateDate))\n{\n    _adRepository.Query.Where(p => p.DateModified <= updateDate).FirstOrDefault();\n}\nelse\n{\n     // throw an exception or something\n}	0
16360032	16359839	How to find the position of occurrence of character in C#?	string input = "XXXX-NNNN-A/N";\nchar[] seperators = new[] { '/', '-' };\nDictionary<int, char> positions = new Dictionary<int,char>();\nfor (int i = 0; i < input.Length; i++)\n    if (seperators.Contains(input[i]))\n        positions.Add(i + 1, input[i]);\n\nforeach(KeyValuePair<int, char> pair in positions)\n    Console.WriteLine(pair.Key + " \"" + pair.Value + "\"");	0
19446200	19445927	How to get the list of columns of same datatype from datatable	var string_type_columns = dt.Columns.Cast<DataColumn>().Where(c => c.DataType == typeof(String));	0
31271308	31270559	Sending a notification popup in winforms from another thread	void ChatServer_OnDataReceived(object sender, ReceivedArguments e)\n    {\n        string machine = e.Name;\n        string message = e.ReceivedData;\n        popupNotification.TitleText = "New  message";\n        popupNotification.ContentText = machine + " sent a message at " + DateTime.Now.ToShortTimeString() +\n            ", saying  \"" + message + "\"";\n        popupMethod(); //call the method that works cross-thread\n        changeTextBoxContents(e.Name + " sent a message at " + DateTime.Now.ToShortTimeString() +\n            ", saying  \"" + e.ReceivedData + "\"");\n    }\n///This method works cross thread by checking if an invoke is required\n///and if so, then the popup is shown with a delegate across the thread\nvoid popupMethod()\n    {\n        if(InvokeRequired)\n        {\n            this.Invoke(new MethodInvoker(delegate {\n                popupNotification.Popup();\n            }));\n            return;\n        }\n    }	0
8030437	8029166	Send and read result of an At command to a usb modem in c#	sp.ReadExisting()	0
5120436	5120388	How can I get a method handler by its name? (c#)	var obj = new MyClass();\nMyDelegate del = (MyDelegate)Delegate.CreateDelegate(typeof(MyDelegate), obj.GetType().GetMethod("Method1"));\nvar result = del(someobject);	0
10122805	10122194	Modifier key for not coming for shift key in c# WPF	if (Keyboard.IsKeyDown(Key.LeftShift))	0
31934550	31932787	Update Single Item in the ObservableCollection without LINQ	Components.Insert(Components.IndexOf(SourceComp), DestComp);\nComponents.Remove(SourceComp);	0
26403896	26400302	Umbraco 7 Razor - find parent	var root = Model.Content.AncestorsOrSelf().First(\n                 x => x.GetPropertyValue<bool>("resetLeftNav")\n              );	0
33595988	33594515	c# winform datagridview cell click to TabControl Page	private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)\n    {\n        // check if you are clicking on needed column\n        // and focus the tab\n        if (e.ColumnIndex == 1) tabControl1.SelectedTab = tabPage2;\n    }	0
27520502	27520350	How to validate redirect link?	string url = driver.Url; // should return active url	0
25154508	25154133	LINQ to delete a collection from master collection	selected.ForEach(q => master.Remove(master.Single(l => l.Id == q.Id)));	0
22565357	22565268	Reading controls in a panel	PanelControls.Controls.OfType<CheckedListBox>()	0
26736622	26736500	How to map 8 directions to 1D array	a = {(-1, -1),  (-1, 0),  (-1, 1),  (0, -1),  (0, 0),  (0, 1),  (1, -1),  (1, 0),  (1, 1)}\n\n\nZeroBasedIndex(x, y) = (x + 1) * 3 + (y + 1)	0
930971	930962	how to translate javascript getTime() value to C# DateTime	new DateTime(1970, 01, 01).AddMilliseconds(jsGetTimeValue);	0
4529447	4529428	Initializing a List c#	List<Student> liStudent = new List<Student>\n        {\n            new Student("Mohan",1),\n            new Student("Ravi",2)\n        };\npublic class Student\n{\n    public Student(string name,int id)\n    {\n        Name=name;\n        ID=id;\n    }\n    public string Name { get; set; }\n    public int ID { get; set; }\n\n}	0
1196125	1196059	iTextSharp - Sending in-memory pdf in an email attachment	PdfWriter writer = PdfWriter.GetInstance(doc, memoryStream);\n\n// Build pdf code...\n\nwriter.CloseStream = false;\ndoc.Close();\n\n// Build email\n\nmemoryStream.Position = 0;\nmm.Attachments.Add(new Attachment(memoryStream, "test.pdf"));	0
10146373	10146085	CronExpression for every day between 9 AM-10 AM	Trigger trigger = (Trigger) newTrigger().withSchedule(DailyTimeIntervalScheduleBuilder.dailyTimeIntervalSchedule().startingDailyAt(new TimeOfDay(8,0)).endingDailyAt(new TimeOfDay(11,0)).withInterval(5, IntervalUnit.MINUTE));	0
9558058	9558015	Use czech chars in regular expression	var words = Regex.Matches(inputstr, @"[????????????????????????????a-zA-z]{1,20}")\n                .Cast<Match>()\n                .ToArray();	0
17446068	17438554	Reactive Extensions: How can I layer observables?	public IObservable<Message> InterpretProtocol(IObservable<message> stream) {\n\n  return stream.\n         TakeWhile(msg => ProtocolMessageTypeOf(message) != ProtocolMessageType.Complete).\n         Select(msg => {\n             if(ProtocolMessageTypeOf(message) == ProtocolMessageType.Error)\n               throw new InvalidOperationException(message);\n             else\n               return msg;\n        });\n\n}	0
32403538	32403249	C# script to convert first line of txt document into a create table statement for SQL Server	string tableName = "myTable";\nstring delimeter = " ";\nstring line = null;\nusing (Stream stream = File.OpenRead("FilePath"))\nusing (StreamReader sr = new StreamReader(stream))\n{\n    line = sr.ReadLine();\n}\nstring fileHeader = line.Replace("\r", string.Empty).Replace("\n", string.Empty);\nstring[] fileHeaderSegments = fileHeader.Split(new string[] { delimeter }, StringSplitOptions.None);\nStringBuilder sb = new StringBuilder(string.Format("CREATE TABLE {0} (", tableName));\nfor (int i = 0; i < fileHeaderSegments.Length; i++)\n{\n    if (i != 0)\n    {\n        sb.Append(",");\n    }\n    sb.Append(fileHeaderSegments[i]);\n    sb.Append(" varchar(255)");\n}\nsb.Append(");");\nConsole.WriteLine(sb.ToString());\nConsole.ReadKey();	0
4434018	4434004	How to profile C# methods per second?	System.Diagnostics.Stopwatch	0
34514410	34514277	Extracting certain words from a URL string	var url = "https://dhgdev-my.sharepoint.com/personal/john_dough_dhgdev_com";\nvar name = url.Replace("https://dhgdev-my.sharepoint.com/personal/", string.Empty).Replace("_dhgdev_com", string.Empty);	0
31583168	31557325	TripleDES encryption in universal app c# WP 8.1	public static string tripleDESEncryptor(string toEncrypt, string keyString)\n{\n   var crypt = SymmetricKeyAlgorithmProvider.OpenAlgorithm(SymmetricAlgorithmNames.TripleDesEcbPkcs7);\n\n            IBuffer buffer = CryptographicBuffer.ConvertStringToBinary(toEncrypt, BinaryStringEncoding.Utf8);\n            IBuffer keyBuffer = CryptographicBuffer.ConvertStringToBinary(keyString, BinaryStringEncoding.Utf8);\n\n            CryptographicKey key = crypt.CreateSymmetricKey(keyBuffer);\n\n            IBuffer signed = CryptographicEngine.Encrypt(key, buffer, null);\n\n            string signature = CryptographicBuffer.EncodeToBase64String(signed);\n            return signature;\n}	0
2511995	2511843	How do I add two lists in Linq so addedList[x] = listOne[x] + listTwo[x]?	var result = \n   from i in \n        Enumerable.Range(0, Math.Max(firstList.Count, secondList.Count))\n   select firstList.ElementAtOrDefault(i) + secondList.ElementAtOrDefault(i);	0
21128465	21128412	List<string> to List<DateTime>	List<string> strings = new List<string>() { "2014-01-14" };\n\nList<DateTime> dates = strings.Select(date => DateTime.Parse(date)).ToList();	0
18538951	18538859	Entity framework How to prevent duplicate entries into db	if (repository.Get(x => x.Major == newVersion.Major && \n    x.Minor == newVersion.Minor && x.Build == newVersion.Build)\n    .Count() > 0)\n{\n     //notify the user that they are making a duplicate entry\n}\nelse\n{\n     repository.SaveChanges();\n}	0
1540762	1540444	How to report timeout in Asynchronous call?	public static long Calc(CalcHandler fn, int a, int b, int c)\n{\nreturn Run<long>(TimeSpan.FromSeconds(20), delegate { return fn(a, b, c); });\n}\n\npublic static T Run<T>(TimeSpan timeout, Func<T> operation)\n{\nException error = null;\nT result = default(T);\n\nManualResetEvent mre = new ManualResetEvent(false);\nSystem.Threading.ThreadPool.QueueUserWorkItem(\ndelegate(object ignore)\n{\ntry { result = operation(); }\ncatch (Exception e) { error = e; }\nfinally { mre.Set(); }\n}\n);\nif (!mre.WaitOne(timeout, true))\nthrow new TimeoutException();\nif (error != null)\nthrow new TargetInvocationException(error);\nreturn result;\n}	0
32474134	28663115	Mongo C#: Is array field contains element from a given array	var query =\n    from c in collection.AsQueryable<C>()\n    where c.A.ContainsAny(new[] { 1, 2, 3 })\n    select c;\n// or\nvar query =\n    collection.AsQueryable<C>()\n    .Where(c => c.A.ContainsAny(new[] { 1, 2, 3 }));	0
1037948	1037462	How to validate string can be convert to specific type?	public class GenericsManager\n{\n    public static T ChangeType<T>(object data)\n    {\n        T value = default(T);\n\n        if (typeof(T).IsGenericType &&\n          typeof(T).GetGenericTypeDefinition().Equals(typeof(Nullable<>)))\n        {\n            value = (T)Convert.ChangeType(data, Nullable.GetUnderlyingType(typeof(T)));\n\n        }\n        else\n        {\n            if (data != null)\n            {\n                value = (T)Convert.ChangeType(data, typeof(T));\n            }\n        }\n\n        return value;\n    }\n}	0
5905192	5852913	Progamatically closing a WP7 Coding4Fun toolkit MessagePrompt Control	cancelButton.Click += (sender, e) =>\n{\n    messagePrompt.Hide();\n};	0
13470592	13418354	How to get the TEXT of Datagridview Combobox selected item?	string SelectedText = Convert.ToString((DataGridView1.Rows[0].Cells["dgcombocell"] as DataGridViewComboBoxCell).FormattedValue.ToString());\nint SelectedVal = Convert.ToInt32(DataGridView1.Rows[0].Cells["dgcombocell"].Value);	0
19176492	19164446	c# key generation method with String type, and int length arguments used to generate a key for encryption	//Generate a public/private key pair.\nRSACryptoServiceProvider RSA = new RSACryptoServiceProvider();	0
24515740	24508881	Cookie based authentication in C#	client.FollowRedirects = false; // very important in my case\n... request.addParameters ...\n... client.execute(request) ...\n\nif (response.StatusCode == HttpStatusCode.Found)\n{\n      if (response.Cookies.Count == 1)\n      {\n             msg.Cookie = response.Cookies[0].Value;\n             msg.ReturnValue = true;\n      }\n}	0
20749362	20749280	points.addxy from stored procedure	this.chart1.Series ["$Parity"].Points.AddXY (myReader.GetDateTime(2), myReader.GetDouble(3));	0
13289186	13288695	System.Timer as a Singleton	public static class DayManager\n{\n     public static readonly object SyncRoot = new object();\n\n     private static readonly Timer dayTimer;\n\n     static DayManager()\n     {\n         dayTimer = new Timer { AutoReset = true; Enabled = true; Interval = 86400000d };\n         dayTimer.Elapsed += OnDayTimerElapsed;\n     }\n\n     protected void OnDayTimerElapsed(object sender, ElapsedEventArgs e)\n     {\n         if(DayPassedEvent != null)\n         {\n             DayPassedEvent(this, null);\n         }\n     }\n\n     public event EventHandler DayPassedEvent;\n}	0
407364	407337	.NET - Get default value for a reflected PropertyInfo	prop.SetValue(obj,null,null);	0
20091721	20091565	Following a tutorial for web services, hit a wall, cannot figure out what to do	[WebMethod]\n public int Getupdate(int sn, int batch, string year)\n {\n     /***/\n }	0
13942932	13942895	Panel scroll vertically	panel1.AutoScrollMinSize = new Size(0, 1200);	0
5853392	5853378	need to help to convert	String str = string.Format("Failed statistics read, device {0}", device);\nbyte[] dataBuffer = System.Text.Encoding.ASCII.GetBytes(str);\n// for 2-byte unicode\nbyte[] dataBuffer = System.Text.Encoding.Unicode.GetBytes(str);\n// for UTF8 unicode\nbyte[] dataBuffer = System.Text.Encoding.UTF8.GetBytes(str);	0
7931438	7931329	Regex to exclude part of string on split	(\\r\\n)(?!PA42)	0
25093504	25093305	How to get Value of specific cell of datagridview in Winform application	private void btn_Click(object sender, EventArgs e)\n    { \n       int[] employeeIds = (dataGridView1.DataSource as DataTable).Rows.Cast<DataRow>().Where(r => (bool)r["Select"]).Select(r => Convert.ToInt32(r["Employee No"])).ToArray();\n    }	0
21347466	21347438	C# lambda Expression In where clause	s.jobOperaitngsys.Split(',').Contains(student.studentknowOS)	0
18902121	18901987	Click event for button in winform is firing repeatedly for number of values in List	//creating event handler for btnNext\n    btnNext.Click += new EventHandler(btnNext_Click);	0
15190783	15189417	program that read file and extract word without # in C#	TextWriter tw = new StreamWriter("D:\\output.txt");    \n  private void button1_Click(object sender, EventArgs e)\n  {\n        StreamReader reader = new StreamReader(@"C:\Users\Mohsin\Desktop\records.txt");\n        string line;\n        String lines = "";\n        while ((line = reader.ReadLine()) != null)\n        {\n\n            String[] str = line.Split('\t');\n\n            String[] words = str[3].Split(' ');\n            for (int k = 0; k < words.Length; k++)\n            {\n                for (int i = 0; i < 4; i++)\n                {\n                    if (i + 1 != 4)\n                    {\n                        lines = lines + str[i] + "\t";\n                    }\n                    else\n                    {\n                        lines = lines + words[k] + "\r\n";\n\n                    }\n                }\n            }\n        }\n        tw.Write(lines);\n        tw.Close();\n        reader.Close();\n  }	0
2977164	2977131	How to resolve ambigiously named extension method?	DataTable dt;\nSystem.Linq.Enumerable.AsEnumerable(dt);	0
11727143	11727108	convert Visual Basic loop to C# loop	for (int i = IBase36.Length -1; i >=0; i--)\n{\n    //Your Treatment\n}	0
25640465	25640344	How to dynamically create an object based on the name of the enum? Without Switch	public object GetAnimal(Animal animal)\n    {\n        var ns = typeof(Animal).Namespace; //or your classes namespace if different\n        var typeName = ns + "." + animal.ToString();\n\n        return Activator.CreateInstance(Type.GetType(typeName));\n    }	0
7568506	7568224	how to read constants from .h file in C#	string GetConstVal(string line)\n{\n  string[] lineParts = string.Split(line, ' ');\n  if (lineParts[0] == "#define")\n  {\n    return lineParts[2];\n  }\n  return null;\n}	0
4277411	4277392	Need to go under height / 2 with cursor	(int)(windowHeight / 1.5)	0
496725	496704	How to iterate over two arrays at once?	var currentValues = currentRow.Split(separatorChar);\n\nfor(var i=0;i<columnList.Length;i++){\n   // use i to index both (or all) arrays and build your map\n}	0
25077443	25077330	C# : Check if two objects have same data	var haveSameData = false;\n\nforeach(PropertyInfo prop in Obj1.GetType().GetProperties())\n{\n    haveSameData = prop.GetValue(Obj1, null).Equals(prop.GetValue(Obj2, null));\n\n    if(!haveSameData)\n       break;\n}	0
16488565	16424113	Changing Value to DataGrid cell	public void SetContacts(IEnumerable<User> contactList, User reqUser)\n{\n    BoundColumn reqColumn = new BoundColumn();\n    reqColumn.HeaderText = "";\n    dgExistingContacts.Columns.Add(reqColumn);\n    dgExistingContacts.DataSource = contactList;\n    dgExistingContacts.DataBind();\n    foreach (DataGridItem row in dgExistingContacts.Items)\n    {\n        if (row.Cells[0].Text == reqUser.id.ToString())\n            row.Cells[6].Text = "Requestor";\n    }\n}	0
4545040	4545024	How to convert January 1, 2008 in c# datetime	using System;\nusing System.Globalization;\n\nclass Test\n{\n    static void Main()\n    {\n        string text = "January 1, 2008";\n\n        DateTime dt = DateTime.ParseExact(text, "MMMM d, yyyy",\n                                          CultureInfo.InvariantCulture);\n        Console.WriteLine(dt);\n    }\n}	0
9220324	9220224	How Do I make my ProgressBar work?	(int)(e.Percent * 100)	0
7256867	7256659	Getting all files modified within a date range	var directory = new DirectoryInfo(your_dir);\nDateTime from_date = DateTime.Now.AddMonths(-3);\nDateTime to_date = DateTime.Now;\nvar files = directory.GetFiles()\n  .Where(file=>file.LastWriteTime >= from_date && file.LastWriteTime <= to_date);	0
3306419	3306330	Creating a DataTable from CSV File	using System.IO;\nusing LumenWorks.Framework.IO.Csv;\n\nvoid ReadCsv()\n{\n    // open the file "data.csv" which is a CSV file with headers\n    using (CsvReader csv =\n           new CsvReader(new StreamReader("data.csv"), true))\n    {\n        int fieldCount = csv.FieldCount;\n        string[] headers = csv.GetFieldHeaders();\n\n        while (csv.ReadNextRecord())\n        {\n            for (int i = 0; i < fieldCount; i++)\n                Console.Write(string.Format("{0} = {1};",\n                              headers[i], csv[i]));\n\n            Console.WriteLine();\n        }\n    }\n}	0
14075654	14075449	Add An XML Declaration To String Of XML	var myOriginalXml = @"<Root>\n                            <Data>Nack</Data>\n                            <Data>Nelly</Data>\n                          </Root>";\n    var doc = new XmlDocument();\n    doc.LoadXml(myOriginalXml);\n    var ms = new MemoryStream();\n    var tx = XmlWriter.Create(ms, \n                new XmlWriterSettings { \n                             OmitXmlDeclaration = false, \n                             ConformanceLevel= ConformanceLevel.Document,\n                             Encoding = UTF8Encoding.UTF8 });\n    doc.Save(tx);\n    var xmlString = UTF8Encoding.UTF8.GetString(ms.ToArray());	0
16747813	16747725	Invalid length for a Base-64 char array	public class HashProvider\n{\n    /// <summary>\n    /// Computes the SHA1 hash from the given string.\n    /// </summary>\n    /// <param name="stringToHash">The string to hash.</param>\n    /// <returns></returns>\n    public static string GetSHA1Hash(string stringToHash)\n    {\n        var data = Encoding.UTF8.GetBytes(stringToHash);\n        var hashData = new SHA1CryptoServiceProvider().ComputeHash(data);\n\n        return String.Concat(hashData.Select(b => b.ToString("X2")));\n    }\n\n\n    /// <summary>\n    /// Computes the SHA1 hash from the given string, and then encodes the hash as a Base64 string.\n    /// </summary>\n    /// <param name="stringToHash">The string to hash.</param>\n    /// <returns></returns>\n    public static string GetSHA1toBase64Hash(string stringToHash)\n    {\n        var data = Encoding.UTF8.GetBytes(stringToHash);\n        var hashData = new SHA1CryptoServiceProvider().ComputeHash(data);\n\n        return Convert.ToBase64String(hashData);\n    }\n}	0
8114793	8114661	Get a string that will be highest alphabetical order	var items = new System.Collections.Generic.SortedList<string, string>();\n\nitems.Add("01", "01");\nitems.Add("02a", "02a");\nitems.Add("test", "test");\n\nvar nextItem = items.Last().Key;\n\nint pos = nextItem.Length - 1;\nwhile (pos >= 0)\n{\n   if ((nextItem[pos] != 'z') && (nextItem[pos] != 'Z'))\n   {\n      nextItem = nextItem.Substring(0, pos - 1) +  Convert.ToChar(Convert.ToInt32(nextItem[pos]) + 1) + nextItem.Substring(pos + 1);\n      break;\n    }\n    pos--;\n }\n\n if (pos == -1)\n {\n    nextItem += "a";\n }	0
23997629	23997116	split string after every carriage return or after 125 chars	var lines = txt.Split("\r\n".ToCharArray(), StringSplitOptions.RemoveEmptyEntries)\n            .SelectMany(x => Regex.Matches(x, @".{0,125}(\s+|$)")\n                                  .Cast<Match>()\n                                  .Select(m => m.Value).ToList())\n            .ToList();	0
1650484	1644113	Need to provide nhibernate configuration a path to an assembly	public Configuration AddAssembly( string assemblyName )\n{\n      log.Info( "searching for mapped documents in assembly: " + assemblyName );\n      Assembly assembly = null;\n      try\n      {\n            assembly = Assembly.Load( assemblyName );\n      }\n      catch( Exception e )\n      {\n            log.Error( "Could not configure datastore from assembly", e );\n            throw new MappingException( "Could not add assembly named: " + assemblyName, e );\n      }\n      return this.AddAssembly( assembly );\n}	0
2998495	2998474	Formatting Output to Currency	Gtotal.ToString("C0");	0
2082650	2082615	Pass Method as Parameter using C#	public class Class1\n{\n    public int Method1(string input)\n    {\n        //... do something\n        return 0;\n    }\n\n    public int Method2(string input)\n    {\n        //... do something different\n        return 1;\n    }\n\n    public bool RunTheMethod(Func<string, int> myMethodName)\n    {\n        //... do stuff\n        int i = myMethodName("My String");\n        //... do more stuff\n        return true;\n    }\n\n    public bool Test()\n    {\n        return RunTheMethod(Method1);\n    }\n}	0
3146855	3145726	Interface declaration for base class method to support IoC	interface A<T>\n{\n    T Save();\n}\n\ninterface IConcreteInterface : A<IConcreteInterface>\n{\n}\n\nclass BusinessBase<T>\n    where T : BusinessBase<T>\n{\n    public T Save()\n    {\n        return (T)this;\n    }\n}\n\nclass D<T, U> : BusinessBase<T>\n    where T : BusinessBase<T>, A<U>\n    where U : A<U>\n{\n    public new U Save()\n    {\n        return (U)(object)base.Save();\n    }\n}\n\nclass ConcreteClass : D<ConcreteClass, IConcreteInterface>, IConcreteInterface\n{\n}	0
6787519	6787167	ASP.Net C# - need help with recursion, parent/child relationship	void IncrementUrlLevel(UrlCollection collection, UrlEntry entry){\n    if (entry == null)\n        return;\n\n    foreach (UrlEntry childEntry in collection){\n        if (childEntry.Parent == entry.Id){\n            IncrementUrlLeven(collection, childEntry);\n        }\n    }\n\n    entry.Level++;\n}	0
15859173	15859123	Function for setting default values of controls in web browser control	public void WebBrowser_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e) \n{\n   var webBrowser = sender as WebBrowser;\n   webBrowser.DocumentCompleted -= WebBrowser_DocumentCompleted;\n\n  webBrowser1.Document.GetElementById("Name").InnerText = "Hello World";\n\n}    \n\nprivate void btnClick(object sender, EventArgs e)\n{\n     var wbrowser = new WebBrowser(); // or can be existing object\n      // Add web broswer to form or panel here.. \n     wbrowser.DocumentCompleted +=new WebBrowserDocumentCompletedEventHandler(WebBrowser_DocumentCompleted);\n     wbrowser.Navigate("your_page_url_here");\n}	0
1416381	1387364	WebBrowser control in windows form application using C#	String sitePath = null;\n        try\n        {\n            sitePath = Application.StartupPath + @"\Print_Help\help.html";\n            wbHelp.Navigate(sitePath);\n        }\n        catch (Exception exp)\n        {\n            MessageBox.Show(exp.ToString() + "\nSite Path: " + sitePath);\n            return false;\n        }\n        return true;	0
7985990	7985872	splitting a 6 digit integer in C#	int i = 153060;\n\nint a = i / 10000;\nint b = (i - (a * 10000)) / 100;\nint c = (i - ((a * 10000) + (b * 100)));	0
988674	988645	LINQ with generic Predicate constraint	public List<T> FindOpenWindows<T>(Predicate<T> constraint)\n   where T : Form\n{\n    var foundTs = from form in openWindows\n                      where constraint(form)\n                            && form.Created\n                      select form;\n\n    return foundTs.ToList();\n}	0
23473316	23473212	C# Sum of Values in a nested dictionary where value is a class Dictionary<string, Dictionary<Int16, CommonData>>	var result = yourMainDict.OrderBy(x => x.Value.Sum(v => v.Value.Delivered + v.Value.Submitted + v.Value.Failed));	0
4108907	4108828	Generic extension method to see if an enum contains a flag	public static class EnumExt\n{\n    /// <summary>\n    /// Check to see if a flags enumeration has a specific flag set.\n    /// </summary>\n    /// <param name="variable">Flags enumeration to check</param>\n    /// <param name="value">Flag to check for</param>\n    /// <returns></returns>\n    public static bool HasFlag(this Enum variable, Enum value)\n    {\n        if (variable == null)\n            return false;\n\n        if (value == null)\n            throw new ArgumentNullException("value");\n\n        // Not as good as the .NET 4 version of this function, but should be good enough\n        if (!Enum.IsDefined(variable.GetType(), value))\n        {\n            throw new ArgumentException(string.Format(\n                "Enumeration type mismatch.  The flag is of type '{0}', was expecting '{1}'.",\n                value.GetType(), variable.GetType()));\n        }\n\n        ulong num = Convert.ToUInt64(value);\n        return ((Convert.ToUInt64(variable) & num) == num);\n\n    }\n\n}	0
1532710	1525914	ASP.NET Gridview: Get the PageIndex from the selected Row	untested code in vb.net\n\n\n*assuming there are studentid from 1 to 100 in the database\n*assuming pagesize of gridview is 10\n\n\ndim studentid_of_edited_row as integer = 11\n\n\ndim da as new dataadapter(strquery,conn)\ndim dt as new datatable\nda.fill(dt)\n\n\ndim desired_pageindex as integer = 0\n\n\nfor i as integer = 0 to dt.rows.count - 1\n  if dt.rows(i)("studentid") = studentid_of_edited_row then\n    desired_pageindex = i / gridview1.pagesize\n    exit for\n  end if\nnext\n\n\ngridview1.pageindex = desired_pageindex\ngridview1.datasource = dt\ngridview1.databind	0
1341548	1341513	IF Statement multiple conditions, same statement	if (columnname != a \n  && columnname != b \n  && columnname != c\n  && (checkbox.checked || columnname != A2)\n{\n   "statement 1"\n}	0
3888743	3793960	DataSet raises NoNullAllowedException even if a value is passed!	lock ( _db.Messages )\n    {\n        var newRow = _db.Messages.NewMessagesRow();\n        {\n            newRow.Title = title;\n            newRow.Text = text;\n            newRow.ReceiverUID = receiverUID;\n            newRow.Deleted = false;\n        }\n\n        _db.Messages.AddMessagesRow( newRow );\n        _adapterMessages.Connection.Open();\n        _adapterMessages.Update( newRow );\n        newRow.MessageID = (Int64)_adapterMessages.GetIdentity();\n        newRow.AcceptChanges();\n        _adapterMessages.Connection.Close();\n    }	0
26783899	26783640	Is there a way to enter number without showing them immediately?	int num;\nvar nums = new List<int>();\n\nwhile (nums.Count < 10)\n{\n    Console.Write("Enter: ");\n    if (int.TryParse(Console.ReadLine(), out num))\n    {\n        nums.Add(num);\n        Console.Clear();\n    }\n}\n\nConsole.WriteLine(string.Join(", ", nums));	0
3924863	3924231	Business Logic Security in Web Applications	System.Security.Principal	0
6833020	6831825	Remove combobox item from combobox WPF	cbRooms.Items.Remove((ComboBoxItem)item))	0
24890249	24814278	How to implement LessThan, etc., when building expressions on strings	Expression comparison = null;\n\nif (value.Type == typeof (string))\n{\n    if (operation == ExpressionType.GreaterThanOrEqual ||\n        operation == ExpressionType.GreaterThan ||\n        operation == ExpressionType.LessThanOrEqual ||\n        operation == ExpressionType.LessThan)\n    {\n        var method = value.Type.GetMethod("CompareTo", new[] {typeof (string)});\n        var zero = Expression.Constant(0);\n\n        var result = Expression.Call(member, method, converted);\n\n        comparison = Expression.MakeBinary(operation, result, zero);\n    }\n}\n\nif (comparison == null)\n    comparison = Expression.MakeBinary(operation, member, converted);\n\nvar lambda = Expression.Lambda<Func<T, bool>>(comparison, parameter);	0
23825757	23825438	How to count datetimes with same day?	var dateInstances = listOfDates.GroupBy(x => x.Date.Day).Select(x => new {Day = x.Key, Instances = x.Count()}).ToList();	0
31965840	31964898	Asynchronous Thumbnail Converter	private BitmapImage image;\n\npublic ImageSource Image\n{\n    get\n    {\n        if (image == null)\n        {\n            image = new BitmapImage();\n            image.BeginInit();\n            image.DecodePixelWidth = 100;\n            image.CacheOption = BitmapCacheOption.OnLoad;\n            image.UriSource = new Uri(value.ToString());\n            image.EndInit();\n            image.Freeze(); // here\n        }\n        return image;\n    }\n}	0
24339793	24335450	Read message length without deserializing protobuf composite stream	Serializer.TryReadLengthPrefix	0
6033004	6032935	Passing Values in a URL	public ActionResult MyMethod(int Number, string Name, bool Remote)\n{\n    //do stuff.\n}	0
16965266	16965006	Binding value to custom radio button in list box item template (WP8)	public class IndexedRadioButton : RadioButton\n{\n    public static readonly DependencyProperty IndexProperty = DependencyProperty.Register(\n        "Index",\n        typeof(int),\n        typeof(IndexedRadioButton),\n        null);\n\n    public int Index\n    {\n        get { return (int)GetValue(IndexProperty); }\n        set { SetValue(IndexProperty, value); }\n    }\n\n}	0
6864626	6859154	EF Property pointing to a member within a member	class Participant {\n  public PhysicalDetailsType PhysicalDetails { get; set; }\n  public List<PhysicalFeatureType> PhysicalFeatures {\n    get { return PhysicalDetails.PhysicalFeatures; }\n    set { Physicaldetails.PhysicalFeatures = value; }\n  }\n}	0
24076278	24076191	How can I create arbitrary amounts of enum values useable as flags in methods	using System;\n\nnamespace HasAccess\n{\n    [Flags]\n    enum Permission\n    {\n        ACCESS = 1,\n        READ = 2,\n        WRITE = 4\n    }\n\n\n    class Program\n    {\n        static void Main(string[] args)\n        {\n            var permissons = Permission.ACCESS | Permission.READ;\n\n            Console.WriteLine(permissons.HasFlag(Permission.ACCESS | Permission.READ));\n        }\n    }\n}	0
26985739	26985703	Remove every other elements of a list	values.Where((x, n) => n % 2 == 0)	0
23759359	23738980	Create a storyboard link in a TFS Work Item programatically	String ConvertToTfsUri(String inputUncPath)\n{\n    return\n        "vstfs:///Requirements/Storyboard/" + Uri.EscapeUriString(input);\n}	0
21151240	21150999	How to set the generic variable of the type Type in a loop?	var method = typeof(MyProcessor).GetMethod("CreateProcessor", new Type[] { typeof(string) });\nnew List<Type> { typeof(AAA), typeof(BBB) }.ForEach(x =>\n{\n    dynamic processor = method.MakeGenericMethod(x).Invoke(null, new[] { x.Name });\n    processor.process();\n});	0
12030123	12024891	Thread is successful from one button but not from another	private void button11_Click(object sender, EventArgs e)\n{\n    T1 = new Thread((ThreadStart)delegate\n    {\n        UlozHlasovanie();\n    });\n    T1.Name = "asd";\n    T1.Start();\n    while (T1.IsAlive) { Application.DoEvents(); }\n    krok = 4;\n    panel1.Visible = false;\n    panel2.Visible = false;\n    panel3.Visible = false;\n    panel4.Visible = true;\n    panel5.Visible = false;\n    panel6.Visible = false;\n    richTextBox1.Text = "";\n    foreach (DataGridViewRow row in dataGridView2.Rows)\n    {\n        row.Cells["rozhodnutie"].Value = null;\n    }\n}	0
17605446	17605350	Responding to events when data changes	private static ReaderWriterLock lockObject = new ReaderWriterLock();\n\n    public static void Invalidate()\n    {\n        try\n        {\n            lockObject.AcquireWriterLock(LockTimeoutMilliseconds);\n            try\n            {\n                // Invalidate your content and reload here\n            }\n            finally\n            {\n                lockObject.ReleaseLock();\n            }\n        }\n        catch (ApplicationException ex)\n        {\n            // The reader lock request timed out. Log this.\n        }\n    }	0
24772635	24772435	HtmlHelper to create a unordered list with max of 2 list elements	public static MvcHtmlString TaskTableFor<TModel, TValue>(this HtmlHelper<TModel> helper, \n  Expression<Func<TModel, TValue>> expression)\n{\n  // Get the model metadata\n  ModelMetadata metaData = ModelMetadata\n    .FromLambdaExpression(expression, helper.ViewData);\n  IEnumerable<string> items= metaData.Model as IEnumerable<string>;\n  if (items == null || items.Count() != 2)\n  {\n    throw new ArgumentException("Invalid collection");\n  }\n  StringBuilder html = new StringBuilder();\n  TagBuilder first = new TagBuilder("li");\n  first.InnerHtml = items.First();\n  html.Append(first.ToString());\n  TagBuilder second = new TagBuilder("li");\n  second.InnerHtml = items.Last();\n  html.Append(second.ToString());\n  TagBuilder list = new TagBuilder("ul");\n  list.InnerHtml = html.ToString();\n  return MvcHtmlString.Create(list.ToString());\n}	0
11082828	11082085	how to use the N character in my C# command to make my program update Arabic Fields	command.CommandText = @"UPDATE  students SET \nfirst_name = @first_name, \nlast_name = @last_name,\n//... and so on...\nWHERE student_id = @id";\ncommand.Parameters.AddWithValue("@first_name", first_name);\ncommand.Parameters.AddWithValue("@last_name", last_name);\n//... and so no...\ncommand.Parameters.AddWithValue("@id", id);	0
20771862	20771820	How to use sub Query in insert statement	Insert into Product\n(\nProduct_Name,\nProduct_Model,\nPrice,Category_id\n)\nSelect \n'P1',\n'M1' , \n100, \nCategoryID \nFrom \nCategory \nwhere Category_Name='Laptop'	0
21991406	21943396	How to utilise Event aggregator in MEF?	public class MainViewModel\n{\n    private readonly IEventAggregator eventAggregator;\n\n    [ImportingConstructor]\n    public MainViewModel(IEventAggregator eventAggregator)\n    {\n       this.eventAggregator = eventAggregator;\n\n       this.eventAggregator.GetEvent<MyEvent>().Publish("");\n    }\n}	0
9111682	9069136	What is the best way to delay a console application for a few seconds	class XYZ\n{\n  Object syncObj = new Object();\n  ...\n\n  public void RunInPlayBettingControl(int SystemPK,string betfairLogon, string betfairPassword, string systemName, int RacePK)\n  {\n    lock(this.syncObj)\n    { }\n    ...\n\n    switch(...)\n    {\n      ...\n      case 2:\n      // race is in play but not over our marker yet so go back in after a short wait\n      lock(this.syncObj)\n      {\n          Thread.Sleep(1000);\n      }\n      ...\n    }\n  }\n}	0
3478298	3478238	C#. Is is possible to have a static generic class with a base type constraint that has a method with a further base type constraint	public static IEnumerable<T2> GetManyByParentId<T2>(\n    ref List<T2> items, Guid parentId) \n    where T2 : T, HasIdAndParentId { .. }	0
10578880	10578636	remove application icon from the taskbar using .net with c#	Application.ApplicationExit += new EventHandler(this.OnApplicationExit);\n\nprivate void OnApplicationExit(object sender, EventArgs e) {\n     notifyicon.Dispose();\n}	0
25139752	25116870	Binding SQL data to a datagrid	private void Window_Loaded(object sender, RoutedEventArgs e)\n    {\n        ShowData();\n    }\n\n    private void ShowData()\n    {\n        SqlConnection con = new SqlConnection(String.Format(@"Data Source={0};Initial Catalog={1};Persist Security Info=True;User ID={2};Password={3}", SQLSERVER_ID, SQLDatabaseName, SQLServerLoginName, SQLServerPassword));\n        con.Open();\n        SqlCommand comm = new SqlCommand("SELECT * FROM Bags", con);\n        DataTable dt = new DataTable();\n        SqlDataAdapter da = new SqlDataAdapter(comm);\n        da.Fill(dt);\n        listView1.DataContext = dt.DefaultView;\n    }	0
22881916	22881732	C# add roles to user programatically using checklist	if (listItem.Selected)\n    {\n        string role = listItem.Value;\n        Roles.AddUserToRole(userName, role);\n    }\n    else\n    {\n\n    }	0
790299	790233	How to create a WMI filter in a GPO via C#	GPMGMTLib.GPM gPM = new GPMGMTLib.GPM(); \nGPMConstants gPMConstants = gPM.GetConstants(); \nGPMDomain gPMDomain = gPM.GetDomain(domainName, DC, gPMConstants.UseAnyDC); \nGPMGPO obj = gPMDomain.CreateGPO(); \nobj.DisplayName = "New GPO";\n\n\n//replace with the appropiate GUID\nvar strWMIFilterID = "{D715559A-7965-45A6-864D-AEBDD9934415}";\nvar sWMIFilter = string.Format("MSFT_SomFilter.Domain=\"{0}\",ID=\"{1}\"", domainName, strWMIFilterID);\n\nvar oWMIFilter = gPMDomain.GetWMIFilter(sWMIFilter); \nobj.SetWMIFilter(oWMIFilter);	0
12591138	12590969	Determining whether a string is a file name in c#	bool IsValidFilename(string testName)\n{\n Regex containsABadCharacter = new Regex("[" + Regex.Escape(System.IO.Path.InvalidPathChars) + "]");\n if (containsABadCharacter.IsMatch(testName) { return false; };\n\n return true;\n}	0
1787878	1786832	How to instantiate a descendant UserControl?	void foo(string NameOfControl)\n    {\n        MyBaseControl ctl = null;\n        ctl = (MyBaseControl) Assembly.GetExecutingAssembly().CreateInstance(typeof(MyBaseControl).Namespace + "." + NameOfControl);\n    }	0
7404978	6331187	How can I convert a DateTime variable in a LINQ expression?	var test= from e in db.Employees.ToList() select new {Time= e.Date.ToString()};	0
16609533	16608961	how to avoid objects allocations? how to reuse objects instead of allocating them?	public sealed class MicroPool<T> where T : class\n{\n    readonly T[] array;\n    public MicroPool(int length = 10)\n    {\n        if (length <= 0) throw new ArgumentOutOfRangeException("length");\n        array = new T[length];\n    }\n    public T TryGet()\n    {\n        T item;\n        for (int i = 0; i < array.Length; i++)\n        {\n            if ((item = Interlocked.Exchange(ref array[i], null)) != null)\n                return item;\n        }\n        return null;\n    }\n    public void Recycle(T item)\n    {\n        if(item == null) return;\n        for (int i = 0; i < array.Length; i++)\n        {\n            if (Interlocked.CompareExchange(ref array[i], item, null) == null)\n                return;\n        }\n        using (item as IDisposable) { } // cleaup if needed\n    }\n}	0
13122928	13121915	Creating a set of couples made of two rows in Linq	var unflattenedConstraints = constraintsTable.Rows;\nvar constraints = from index in Enumerable.Range(0, unflattenedConstraints.Count / 2)\n                                          .Select(x => x * 2)\n                  let row1 = unflattenedConstraints[index]\n                  let row2 = unflattenedConstraints[index + 1]\n                  // Combine the rows	0
13746290	13736156	How can I implement my own type of extern?	class Program {\n        static void Main(string[] args) {\n            foo();\n        }\n\n        class FooBar : Attribute { }\n\n        [FooBar]\n        static extern void foo();\n    }	0
22014873	22013230	Compare Row of 1st Datatable with Column of 2nd Datatable and build 3rd datatable with matched columns	//dt1 contains Diffusion etc as rows\n//dt2 contains diffusion etc as columns\n//dt3 is the required table\nDataTable dt3 = new DataTable();\nDataRow dr = null;\n\nfor (int i = 0; i < dt1.Rows.Count; i++)\n{\n    string col = dt1.Rows[i]["Par Name"].ToString();\n    if (dt2.Columns.Contains(col))\n    {\n        if (!dt3.Columns.Contains(col))\n        {\n            dt3.Columns.Add(col, typeof(string));\n        }\n\n        if (dt3.Rows.Count == 0)\n        {\n            for (int j = 0; j < dt2.Rows.Count; j++)\n            {\n                dr = dt3.NewRow();\n                dt3.Rows.Add(dr);\n            }\n        }\n\n        for (int j = 0; j < dt2.Rows.Count; j++)\n        {\n            dt3.Rows[j][col] = dt2.Rows[j][col].ToString();\n        }\n    }\n}	0
16223227	16216168	how to copy image from filepiker to app folder windows store apps	[Windows.Storage.AccessCache][2]	0
8199211	8199198	Splitting a string by a space without removing the space? 	StringCollection resultList = new StringCollection();\nRegex regexObj = new Regex(@"(?:\b\w+\b|\s)");\nMatch matchResult = regexObj.Match(subjectString);\nwhile (matchResult.Success) {\n    resultList.Add(matchResult.Value);\n    matchResult = matchResult.NextMatch();\n}	0
2980306	2980287	How to replace the following character with an empty space?	ClientAddress.Replace("\n", "<br>")	0
16031304	16031176	return different linq to sql result sets into single object(json format)?	var somethingJSON = new {\n  list1Data= lst1 ,\n  list2Data= lst2,\nlist3Data= lst3\n};\n\nreturn JSON(somethingJSON,JsonRequestBehavior.AllowGet);	0
34138756	34138727	How do i send enum string values to client	public string[] GetMonths()\n{\n    return Enum.GetNames(typeof(Month));\n}	0
8590300	8589848	Hide child controls in UserControl with another control	private new bool Enabled\n        {\n            get { return _enabled; }\n            set\n            {\n                foreach (System.Windows.Forms.Control c in this.Controls)\n                {\n                    if (c is SomeTypeThatShouldBeExcluded)\n                        continue;\n                    c.Enabled = value;\n                }\n                _enabled = value;\n            }\n        }	0
16917995	16917278	How to ask for connection string in clickonce installer?	try {\n    if (ApplicationDeployment.CurrentDeployment == null ||\n      ApplicationDeployment.CurrentDeployment.ActivationUri == null)\n      return null;\n  } catch {\n    // application was not activated from the web\n    return null;\n  }\n\n  Uri uri = ApplicationDeployment.CurrentDeployment.ActivationUri;\n  string query = uri.Query;\n  if (string.IsNullOrEmpty(uri.Query))\n    throw new UIException("Activation Uri is empty.");\n\n  Regex regex;\n  Match match;\n  regex = new Regex(@".*ConnectionString=(?<ConnectionString>([A-Z0-9\+/=:%\._-]+))", RegexOptions.IgnoreCase);\n  match = regex.Match(uri.Query);\n  if (match == null || !match.Success) {\n    throw new UIException("ConnectionString not recognized as part of activation Uri.");\n  }\n  return HttpUtility.UrlDecode(match.Groups["ConnectionString"].Value);	0
10442079	10441892	How to Add Data Contents to Data Grid in the Same Page without any Database Connectivity?	private List<string> addContent(string content)\n{\n    //create a generic list of string type\n    List<string> s = new List<string>();\n\n    for (int i = 0; i < 10; i++)\n    {\n        s.Add(content);\n    }\n    return s;\n}\n\nprotected void btnAdd_Click(object sender, EventArgs e)\n{\n   //Passed the List<> as DataSource and then bind the content in the list<> in the  DataGrid\n    this.DataGrid1.DataSource = this.addContent(this.txtadd.Text);\n    this.DataGrid1.DataBind();\n\n}	0
14357859	14357053	query with Nullable Values using Linq	object tmp= model.table.FirstOrDefault(t => \n    t.Key1 == newItem.Key1 \n    && ((!t.Key2.HasValue & !newItem.Key2.HasValue) \n        | t.Key2.Value == newItem.Key2.Value)                             \n    && ((!t.Key3.HasValue & !newItem.Key3.HasValue) \n        | t.Key3.Value == newItem.Key3.Value) && t.Value == newItem.Value);	0
28143997	28143954	How to deserialise json data from the World of Warcraft auction API using Json.NET	public class WoWAuctionResponse {\n    public WoWRealmInfo Realm {get; set;}\n    public WoWAuctionsBody Auctions {get; set;}\n}\n\npublic class WoWAuctionsBody {\n   public List<WoWAuction> Auctions {get; set;}\n}\n\n// ...\n\nJsonConvert.DeserializeObject<WoWAuctionResponse>(json);	0
9017251	9016818	Silverlight binding to canvas, element location in list at element?	class CustomCanvas : Canvas\n{\nprivate int mChildsNum = 0;\n...\nCustomCanvas()\n{\n    // Track changes that appear in canvas when new\n    // children are added\n    this.LayoutUpdated += CanvasChangeTracker;\n}\n...\nprivate void CanvasChangeTracker(object source, EventArgs e)\n{\n    if ( this.Children.Count != mChildsNum )\n    {\n        // A new child was added.\n        // Update the coordinates for children\n        mChildsNum = this.Children.Count;\n    }\n}\n...\n}	0
6905635	6894932	Face book Logout for a web site	FB.logout(function(response) {\n  // user is now logged out\n});	0
33971906	33971881	c# WPF selected item from listbox bound to datatable	private void lstDishes_MouseDoubleClick(object sender, MouseButtonEventArgs e)\n{\n   var Selected =  lstDishes.SelectedItem as Dish;\n   MessageBox.Show("You selected: " + Selected.Description));   \n}	0
16272772	16212163	How to select specific images and save from a particular url? (Description Inside)	public System.Drawing.Image DownloadImageFromUrl(string imageUrl)\n{\n    System.Drawing.Image image = null;\n\n    try\n    {\n        System.Net.HttpWebRequest webRequest = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(imageUrl);\n        webRequest.AllowWriteStreamBuffering = true;\n        webRequest.Timeout = 30000;\n        System.Net.WebResponse webResponse = webRequest.GetResponse();\n        System.IO.Stream stream = webResponse.GetResponseStream();\n        image = System.Drawing.Image.FromStream(stream);\n        webResponse.Close();\n    }\n    catch (Exception ex)\n    {\n        return null;\n    }\n\n    return image;\n}	0
983792	983760	Calling the DescendantNodes without repeating each node	Elements()	0
10209991	10209864	C# Anonymous Array of Anonymous Objects from loop	var dupes = list.Select(i => new { FirstName = i.firstname,\n                                   LastName = i.lastname,\n                                   Phone = i.telephone1,\n                                   Owner = i.ownerid.ToString(),\n                                   Address = i.address1_line1,\n                                   City = i.address1_city,\n                                   State = i.address1_stateorprovince,\n                                   Zip = i.address1_postalcode,\n                                   LastModified = i.ctca_lastactivityon.ToString()\n                                    });	0
3069779	3069748	How to remove all the null elements inside a generic list in one go?	List<EmailParameterClass> parameterList = new List<EmailParameterClass>{param1, param2, param3...};\nparameterList.RemoveAll(item => item == null);	0
5735048	5734947	double parsing algorithm in C#	System.Number.ParseNumber	0
5731321	5635927	How to make Dllimport correctly in c#?	cryptedString = "CryptedStringFromDataBase";\nStringBuilder decryptedString = new StringBuilder(300);\nDecrypt(cryptedString, (uint)cryptedString.Length, decryptedString, 300);\n\n[DllImport("Filename.dll", CharSet = CharSet.Ansi, CallingConvention = CallingConvention.Cdecl)]\nstatic extern void Decrypt(string src, UInt32 srcLen, [MarshalAs(UnmanagedType.LPStr)] StringBuilder dst, UInt32 dstLen);	0
7167159	7167140	collect all array items from each object	var all = as.SelectMany(a => a.bs);	0
2865939	2738228	How to stream your images/files with VLC?	cd "C:\program files\videolan\vlc" \nvlc -I dummy fake:// --fake-file c:\1.jpg -vvv --sout #transcode{vcodec=mp4v,vb=1024,scale=1}:duplicate{dst=std{access=udp,mux=ts,dst=localhost:1234}}	0
18444221	18398766	Retrieve DataPoint for Auxilary axis	Point point = chart.View.Axes[2].PointToData(e.GetPosition(chart))	0
10633730	10633632	slicing array based on selection masks	double[] a = new double[]{1.0, 2.0, 3.0}; \nbool[] b = new bool[]{true, false, true}; \nvar result = a.Where((item, index)=>b[index]);	0
4686297	4686210	Uploading an xml direct to ftp	using ( Stream s = request.GetRequestStream() )\n        {\n            doc.Save( s );\n        }\n        MessageBox.Show( "Created SuccesFully!" );	0
4156050	4155910	Setting TreeView ForeColor using C#	private void treeView1_NodeMouseClick(object sender, TreeNodeMouseClickEventArgs e)\n{\n    (sender as TreeView).SelectedNode.ForeColor = Color.Red;\n}\n\nprivate void button1_Click(object sender, EventArgs e)\n{\n    foreach (TreeNode tn in treeView1.Nodes)\n    {\n        tn.ForeColor = Color.Blue;\n        ColorNodes(tn);\n    }\n}\n\nprivate void ColorNodes(TreeNode t)\n{\n    foreach (TreeNode tn in t.Nodes)\n    {\n        tn.ForeColor = Color.Blue;\n        ColorNodes(tn);\n    }\n}	0
15461740	15461580	Sileverlight change value from code behind	Canvas.SetLeft(c1, 25);	0
22428877	22428844	Assign Sql Query Result To Variable	void AssignValue()\n{\n    using(MySqlConnection con =new MySqlConnection("/*connection string here*/"))\n    using(MySqlCommand command = new MySqlCommand("SELECT rol FROM users WHERE \n                                 user = @user",con))\n    {\n      con.Open();\n      command.Parameters.AddWithValue("@user",txtUser.Text);        \n      TextBox2.Text = commad.ExecuteScalar().ToString();        \n    }\n}	0
24252994	24252775	Linq query to get all attributes of an item with a many to one relationship	var selectedId = 1;  // The item ID you are looking for\nvar attrNames = items\n    .Where(i => i.Id == selectedId)\n    .SelectMany(x => x.Attributes)\n    .Where(a => !a.Inactive)\n    .Select(a => a.Name);	0
16712520	16712304	Invalid length for a Base-64 char array	string sQueryString = txtPassword.Text;\nbyte[] buffer = Convert.FromBase64String(sQueryString);	0
8049208	8049193	Create a object in C# without the use of new Keyword?	Type type = typeof(MyClass);\nobject[] parameters = new object[]{1, "hello", "world" };\nobject obj = Activator.CreateInstance(type, parameters);\nMyClass myClass = obj as MyClass;	0
32071718	32066225	How to close only child on click of a button in WPF	MainWindow mainWind = Application.Current.MainWindow as MainWindow;\nmainWind.MainMdiContainer.Children.RemoveAt(0);	0
4390464	4389701	Retrieve cookie values in ASHX 	Response.Cookies["domain"].Domain = ".somedomain.com";	0
2319409	2319397	How to perform this c# instantiation and method usage in 1 line?	new SVNLock(lock_file).Execute();	0
28971358	28971049	How to change drop down list selected index and visibility using another drop down list in asp.net?	if (this.ddlStatus.SelectedItem.Value.Trim() == "-1")\n{\n    ddlStatus.Attributes["style"] = null;\n    string script = "<script type=\"text/javascript\">alert('You must select a status.');</script>";\n    ClientScript.RegisterClientScriptBlock(this.GetType(), "Alert", script);\n}	0
8699735	8699606	convert KOI8-R xml node into unicode in c#	Encoding encoding = Encoding.GetEncoding("KOI8-R");\nXDocument doc;\nusing (var reader = File.OpenText("file.xml", encoding))\n{\n    doc = XDocument.Load(reader);\n}	0
13886868	13886652	How to Get a result from a method on another thread in c#	public int GenerateID(OtherThreadObj oto)\n{\n    int result;\n    this.Invoke((MethodInvoker)delegate { result = GenerateIDSafe(oto); });\n    return result;\n}	0
22860656	22860294	Count the characters in a cookie string using c#	Request.Cookies["GE"].Value.Length	0
7948591	7948068	Dynamic Link, changing a property for every item in a list	string propName = "GPARank";  \nPropertyInfo prop = typeof(Item).GetProperty(propName);\nAction<Item,string> setter = (Action<Item,string>)Delegate.CreateDelegate(\n    typeof(Action<Item,string>), prop.GetSetMethod());\nforeach(Item obj in list) setter(obj,newValue);	0
16066248	16064259	DataTemplate binding grid background through a converter	public object Convert(object value, Type targetType, object parameter, \n                      System.Globalization.CultureInfo culture)\n{\n    return new SolidColorBrush(Colors.Red);\n}\n\npublic object ConvertBack(object value, Type targetType, object parameter, \n                          System.Globalization.CultureInfo culture)\n{\n    return Binding.DoNothing;\n}	0
27868348	27868013	How to timout on this task	var timeoutTask = Task.Delay(1500);\n        //using .ContinueWith(t => /*stuff to do on timeout*/);\n        //will cause the code to execute even if the timeout did not happen.\n        //remember that this task keeps running. we are just not waiting for it\n        //in case the worker task finishes first.\n\n        var workerTask = Task.Run(() => { ThirdPartLibraryAPI.Run() });\n        var taskThatCompletedFirst = await Task.WhenAny(timeoutTask, workerTask);\n\n        //stuff to do on timeout can be done here\n        //if (taskThatCompletedFirst == timeoutTask)	0
4953253	4902006	Submission of a webpage form using WebBrowser control in C#	mshtml.IHTMLDocument2 doc = ((mshtml.HTMLDocumentClass)webBrowser1.Document);\n\n\n         ((mshtml.IHTMLElement)doc.all.item("q")).setAttribute("value", "hello world");\n         MessageBox.Show("Clicking I'm feeling lucky button");\n        ((mshtml.HTMLInputElement)doc.all.item("btnI")).click();	0
12202109	12202066	Adding a picture from a resource to a picture box	using (Stream imgStream = Assembly.GetExecutingAssembly()\n    .GetManifestResourceStream(\n    "MyNamespace.resources.fruitcake.jpg"))\n{\n    var image = new Bitmap(imgStream);\n    pictBox.Image = image;\n    pictBox.Height = image.Height;\n    pictBox.Width = image.Width;\n}	0
32544352	32544248	Filter gridview with pages issue	protected void OnPageIndexChanging(object sender, GridViewPageEventArgs e)\n{\n    gridprod.PageIndex = e.NewPageIndex;\n    gridprod.DataSource = d.Searchprod(lblfield.SelectedValue, txtsearch.Text);\n    gridprod.DataBind()\n}	0
26985529	26985294	Avoid send json property	public class TreeViewModel\n{\n    public string Text { get; set; }\n    public string Cls { get; set; }\n    public bool Expanded { get; set; }\n    [JsonProperty(PropertyName = "checked")]\n    public bool Checked { get; set; }\n    public bool Leaf { get; set; }\n    public List<TreeViewModel> Children { get; set; }\n\n    public bool ShouldSerializeCls()\n    {\n        return Children != null && Children.Count > 0;\n    }\n\n    public bool ShouldSerializeExpanded()\n    {\n        return Children != null && Children.Count > 0;\n    }\n\n    public bool ShouldSerializeChildren()\n    {\n        return Children != null && Children.Count > 0;\n    }\n}	0
10992447	10992389	Attaching a disconnected nHibernate entity to a session and reading from the database	List<EntityBase> attachedEntities = new List<EntityBase>();\n\nforeach(EntityBase entity in entities) \n{\n    attachedEntities.Add(session.Merge(entity));\n}	0
1561573	1561421	Formatting Excel cell with Microsoft Interop	Excel.Worksheet sheet = this.Application.ActiveSheet as Excel.Worksheet;\nExcel.Range range = sheet.get_Range("A1", "A5") as Excel.Range;\n\n //delete previous validation rules \n range.Validation.Delete();\n range.Validation.Add(Excel.XlDVType.xlValidateWholeNumber,\n                                 Excel.XlDVAlertStyle.xlValidAlertStop,\n                                 Excel.XlFormatConditionOperator.xlBetween,\n                                 0, 1);	0
13260742	13259088	Linq redundant db access for related models	OperationsMetricsDataContext db = new OperationsMetricsDataContext();\n\nDataLoadOptions dlo = new DataLoadOptions();\ndlo.LoadWith<Client>(c => c.Vertical);\ndb.LoadOptions = dlo;	0
10755790	10755674	How to add Values to list<valuepair> object 	List<ValuePair> listUserRoleValuePair = new List<ValuePair>();\nvar ixUserList= _mapper1.FindUserRoleLike(sName);\nUser result = null;\n\nforeach (var ixUser in ixUserList)\n{\n    result = new UserMapper(connection).FindById(ixUser);\n    var name = result.SFirstName + " " + result.SLastName;\n    listUserRoleValuePair.Add(new ValuePair(ixUser, name));\n}	0
32070110	32069574	Get certain rows of a treeView and fill another treeview	private void Form1_Load(object sender, EventArgs e)\n    {\n        MoveNodes(treeView1,treeView2,1, 2);\n    }\n    void AddRootNode(TreeView tree, TreeNode node)\n    {\n        var newNode = new TreeNode(node.Text);\n        tree.Nodes.Add(newNode);\n        foreach (TreeNode child in node.Nodes)\n            AddChildNode(newNode, child);\n    }\n    void AddChildNode(TreeNode parent, TreeNode node)\n    {\n        var newNode = new TreeNode(node.Text);\n        parent.Nodes.Add(newNode);\n        foreach (TreeNode child in node.Nodes)\n            AddChildNode(newNode, child);\n    }\n    private void MoveNodes(TreeView source,TreeView destination, params int[] indexes)\n    {\n        foreach (var index in indexes)\n        {\n            if (index < 0 || index >= source.Nodes.Count)\n                continue;\n            AddRootNode(destination, source.Nodes[index]);\n        }\n    }	0
32977990	32977790	WIX Setup, Change install folder selected from another program?	msiexec /i programA.msi INSTALLFOLDER="some\path\where\to\install"	0
1135380	1135165	Does a lambda create a new instance everytime it is invoked?	using System;\n\nclass Program {\n    static void Main(string[] args) {\n        var i1 = test(10);\n        var i2 = test(20);\n        System.Console.WriteLine(object.ReferenceEquals(i1, i2));\n    }\n\n    static Func<int, int> test(int x) {\n        Func<int, int> inc = y => y + 1;\n        Console.WriteLine(inc(x));\n        return inc;\n    }\n}	0
23884090	23833638	ReactiveUI: How to cancel an Observable from a ReactiveCommand?	CancelConversion = this.WhenAnyValue(x => x.ImagesCount, x => x.IsBusy, (count, busy) => count > 0 && busy).ToCommand();\n\nthis.WhenAnyValue(x => x.ImagesCount, x => x > 0).ToCommand();\n\nvar process = Compress.RegisterAsync(x => ConvertImages().TakeUntil(CancelConversion));\nvar subscription = process.Subscribe(x => Images.Remove(x));	0
30600195	30599777	Writing out a specific line of a list	var find = "Savings found:";\n\nforeach(var line in a.Where(w => w.Contains(find))\n{\n  var subStr = line.Substring(0, line.IndexOf(find)+find.Length);\n  var startIndex = subStr.IndexOf('(');\n  var endIndex = subStr.IndexOf(')');\n\n  var savings = double.Parse(subStr.SubString(0, startIndex-1).Trim());\n  var percent = double.Parse(subStr.SubString(startIndex+1, endIndex-startIndex-2).Trim());\n\n  Console.WriteLine("{0}{1}{2}", (percent >= 30) ? "*" : string.Empty,\n                                 (percent >= 30 && savings >= 500) ? "*" : string.Empty,\n                                 line);\n}	0
20541349	20538880	How to change the table name in visual studio 2013 in design mode?	EXEC sp_rename 'Table', 'NewName'	0
33573133	33572961	LINQ dynamic orderby from querystring	var query = ...;\nswitch(yourvar)\n{\n  case "oldest":\n    query=query.OrderBy(x=>x.Age); break;\n  case "alpha":\n    query=query.OrderBy(x=>x.Name); break;\n}	0
16097938	14523859	C# WPF RDP ax control from MSTSCLib for Hyper-V problems	protected override void WndProc(ref Message m)\n         {\n             switch (m.Msg)\n             {\n                 case 0x021:\n                     {\n                         Message mm = new Message();\n                         mm.Msg = 0x007;\n                         base.WndProc(ref mm);\n                     }\n                     break;\n             }\n             base.WndProc(ref m);\n         }	0
25391743	25391517	Insert Multiple Records In One Connection	string emergencyContactInfo = "Insert Into econtactInfo(fname, lname, phone1, phone2)     Values(@fname, @lname, @phone1, @phone2)";\ncmd = new SqlCommand(emergencyContactInfo, con);\ncon.Open();\n\ncmd.Parameters.Add("@fname", SqlDbType.<Type>);\n<Add the other parameters here>\n...\n\ncmd.Parameters["@fname"].Value = txt1fname\n<Add parameters values here>\n...\ncmd.ExecuteNonQuery();\n\ncmd.Parameters["@fname"].Value = txt2fname\n<Add parameters values here>\n...\ncmd.ExecuteNonQuery();\n\nconnection.Close()	0
1982088	1982049	Is it possible to cause a thread to be created in another app domain?	var ad = AppDomain.CreateDomain("mydomain");\nad.DoCallBack(() =>\n  {\n    var t = new System.Threading.Thread(() =>\n    {\n      Console.WriteLine();\n      Console.WriteLine("app domain = " \n           + AppDomain.CurrentDomain.FriendlyName);\n    });\n    t.Start();\n\n   });	0
11689325	11689248	Compare two strings ignoring new line characters and white spaces	string stringOne = "ThE    OlYmpics 2012!";\nstring stringTwo = "THe\r\n        OlympiCs 2012!";\n\nstring fixedStringOne = Regex.Replace(stringOne, @"\s+", String.Empty);\nstring fixedStringTwo = Regex.Replace(stringTwo, @"\s+", String.Empty);\n\nbool isEqual = String.Equals(fixedStringOne, fixedStringTwo,\n                              StringComparison.OrdinalIgnoreCase);\n\nConsole.WriteLine(isEqual);\nConsole.Read();	0
29242462	29242331	c# Split string that contains letters and numbers	var parts = Regex.Matches(yourstring, @"\D+|\d+")\n            .Cast<Match>()\n            .Select(m => m.Value)\n            .ToArray();	0
8059143	8059094	get the html code of a certain div in the render event	DivCliente.Render(my writer)	0
16530263	16530244	Create a list of objects by grouping on multiple properties	group x by new { x.Color, x.Size } into y	0
12956689	12954789	How to change one string from definite position using other string?	public static string RewriteChar(this string input, string replacement, int index)\n{\n  // Get the array implementation\n  var chars = input.ToCharArray();\n  // Copy the replacement into the new array at given index\n  // TODO take care of the case of to long string?\n  replacement.ToCharArray().CopyTo(chars, index);\n  // Wrap the array in a string represenation\n  return new string(chars);\n}	0
18628086	18628022	How do you return a value properly?	public static int CalcProg(int userGoal, int userBalance, int userProg)\n{\n    userProg = userBalance / userGoal;\n    userProg = userProg * 100\n    return userProg;\n\n}\n\nprivate void Form1_Load(object sender, EventArgs e)\n{\n    //Calls the FileVerification Method\n    FileVerification();\n    //Sets the label1 transparency to true\n    label1.Parent = pictureBox1;\n    label1.BackColor = Color.Transparent;\n    LoadData();\n\n    progressBar1.Value = CalcProg(userGoal, userBalance, userProg);\n    progLabel = Convert.ToString(userProg);\n    label3.Text = progLabel;\n\n\n}	0
18674580	18674070	How to conver float to sizeF?	SizeF has a ToSize method\n\nSize size = sizeF.ToSize();\n\nor\n\nmyControl.Size = sizeF.ToSize();	0
5339885	5339782	how do i get TcpListener to accept multiple connections and work with each one individually?	static void Main(string[] args)\n{\n    TcpListener listener = new TcpListener(IPAddress.Any , 8000);\n    TcpClient client;\n    listener.Start();\n\n    while (true) // Add your exit flag here\n    {\n        client = listener.AcceptTcpClient();\n        ThreadPool.QueueUserWorkItem(ThreadProc, client);\n    }\n}\nprivate static void ThreadProc(object obj)\n{\n    var client = (TcpClient)obj;\n    // Do your work here\n}	0
30616250	30574274	Resuming and suspendig WinRT Camera App	await cameraCapture.StopPreview();\ncameraCapture.Dispose();\ncameraCapture = null;	0
13049909	13049732	Automatically rename a file if it already exists in Windows way	int count = 1;\n\nstring fileNameOnly = Path.GetFileNameWithoutExtension(fullPath);\nstring extension = Path.GetExtension(fullPath);\nstring path = Path.GetDirectoryName(fullPath);\nstring newFullPath = fullPath;\n\nwhile(File.Exists(newFullPath)) \n{\n    string tempFileName = string.Format("{0}({1})", fileNameOnly, count++);\n    newFullPath = Path.Combine(path, tempFileName + extension);\n}	0
7133262	7133201	Getting arguments passed to a FakeItEasy-mock without using magic strings?	A.CallTo(() => service.DoSomething(A<int>.That.Matches(x => x == 100)))\n .MustHaveHappened();	0
19496652	19294486	I can't get the custom control to change rendering of a master page control	protected override void OnPreRender(EventArgs e)\n        {\n            var master = this.Page.Master as Site;\n            if (master != null)  // cast failed, your master is a different type\n            {\n                var progressShown = master.FindControl("ProgressShown");\n                if (progressShown != null)\n                {\n                    master.NavBar.Attributes.Add("class", "test");\n                }\n            }\n\n            base.OnPreRender(e);\n        }	0
17248726	17248711	Custom Operation in generic list	Var SingleDigitValues = string.Join(",",list.Distinct().where(x=>x>0 && x<10));	0
1594308	1593218	Adding SSIS Connections Programmatically - Oracle Provider for OLE DB	Package pkg = new Package();\nConnectionManager manager = pkg.Connections.Add("OLEDB");\nmanager.ConnectionString = "Data Source=DEVORA.my.OracleDB;User ID=oracleUser;Provider=MSDAORA.1;Persist Security Info=True;";\nmanager.Name = "OracleDev";	0
34233907	34233714	How to replace encoding=utf-8 in the xml header with an empty string using XmlTextWriter?	public XmlTextWriter(\n  Stream w,\n  Encoding encoding\n)	0
13497298	13497243	Reading bytes from file	while (w != -1)	0
7074678	7074344	How to change extension of string path in C#?	string strFile = @"http://login.contentraven.com/Uploads/g05fgxeto4dvsf5531yb3l45_16_8_2011_1_25_37.DOC";\n\nstring strTemp = Path.GetExtension(strFile).ToLower();\n\nif (strTemp==".doc")\n{\n    strFile = Path.ChangeExtension(strFile, "pdf");\n}	0
11210236	11210096	Linq Query for Top 10 with Group BY	var top = lookupDictionary\n    .Select(dict => new { dict.Key, InnerCount = dict.Value.Values.Sum() })\n    .OrderByDescending(dict => dict.InnerCount)\n    .Take(10);	0
33769982	33769897	How to access a property in a derived class from a base class	public class Derived : Test\n{\n    public Derived()\n    {\n        _test = 5;\n    }\n}\n\npublic class Test\n{\n    public int _test;\n\n    public int GetTest()\n    {\n         return _test;\n    }\n}\n\nvar obj = new Derived();\nvar test = obj.GetTest(); // returns 5	0
24153267	24152760	Lazy Singleton with property that references parent in constructor	public Providers AllProviders\n{\n    get\n    {\n        if (this.allProviders == null) this.allProviders = Providers.Instance; // alternatively, do what Providers.Instance is actually doing\n        return this.allProviders;\n    }\n}	0
8429161	8429142	How to convert a string (red,blue,black) to a string array?	string[] splitString = myString.Split(",");	0
7600369	7600292	High performance "contains" search in list of strings in C#	var matches = list.AsParallel().Where(s => s.Contains(searchTerm)).ToList();	0
8224186	8223674	How to allow registry modification and drive C: modification in Windows 7?	System.IO.Path.GetTempPath()	0
2881709	2873739	Persisting details in Master Detail relation EF4 POCO	context.SaveChanges(SaveOptions.DetectChangesBeforeSave);	0
4281669	4279376	How to display C# source code from external file?	xmlns:avalonEdit="http://icsharpcode.net/sharpdevelop/avalonedit"\n\n<avalonEdit:TextEditor Name="textEditor"\n                       Loaded="textEditor_Loaded"\n                       FontFamily="Consolas"\n                       FontSize="10pt"/>\n\nprivate void textEditor_Loaded(object sender, RoutedEventArgs e)\n{\n    textEditor.Load(@"C:\MainWindow.xaml.cs");\n    textEditor.SyntaxHighlighting =\n        HighlightingManager.Instance.GetDefinition("C#");\n}	0
22681073	22680834	Cannot Update Row In Oracle DB Using C# Library	'yyyy/MM/dd'	0
7672507	7672482	asp.net: Read data from uploaded Excel document	Microsoft.Office.Interop.Excel	0
25672331	25672129	Using LINQ to turn XML into Dictionary when XML file entries vary in format	var dict = XDocument.Load(filename)\n           .XPathSelectElements("/Offsets/*[offset]")\n           .ToDictionary(x => x.Name.LocalName, \n                         x => x.Elements("offset").Select(o=>o.Value).ToList());	0
6714837	6714823	how to replace multiple chars from a string?	contact.name = Regex.Replace(contact.name, @"[\(\)\- ]", String.Empty);	0
29485914	29485847	Save a file with a dynamic name C#	string[] lines = { textBox2.ToString(), textBox3.ToString() }; \nFile.WriteAllLines(string.Format(@"C:\resultats\{0}-{1:dd:MM.yyyy}.txt", textBox1.ID, DateTime.Now), lines);	0
6569473	6569422	How can I randomly ordering an IEnumerable<>?	List<MyObject> list = new List<MyObject>( my_enumerable );\nRandom rnd = new Random(/* Eventually provide some random seed here. */);\nfor (int i = list.Count - 1; i > 0; --i)\n{\n    int j = rnd.Next(i + 1);\n    MyObject tmp = list[i];\n    list[i] = list[j];\n    list[j] = tmp;\n}\nmy_enumerable = list;	0
1093079	1093056	How to "clone" an object into a subclass object?	B newB = new B(myA);	0
23025450	23025386	Make HttpRequest cache work	Pragma: no-cache	0
9510289	9510143	LINQ - get results where a certain property is in this other result set of the property's type	var prices = db.BuildingPrices.Where\n            (\n                p => db.ShedStyles\n                    .Where( s => s.Name.Contains("text"))\n                    .Contains(p.ShedStyle)\n\n            );	0
13856095	13856044	How to handle data between two function call one after other	using (var Conn = new SqlConnection(_ConnectionString))\n{\n    SqlTransaction trans = null;\n    try\n    {\n        Conn.Open();\n        trans = Conn.BeginTransaction();\n\n        using (SqlCommand Com = new SqlCommand(ComText, Conn, trans))\n        {\n                    // delete comment\n                    // update score\n         }\n         trans.Commit();\n      }\n    catch (Exception Ex)\n    {\n        if (trans != null) trans.Rollback();\n        return -1;\n    }\n\n}	0
7500562	7500483	Preventing user from uncheking a checkbox	if (!checkBox1.Checked)\n {\n     checkBox1.Checked = true;\n }	0
28027084	28024957	Set Content-Transfer-Encoding to Quoted-printable with .NET MailMessage	AlternateView plainTextView = AlternateView.CreateAlternateViewFromString(body.Trim(), new ContentType("text/html; charset=UTF-8"));\nplainTextView.TransferEncoding = System.Net.Mime.TransferEncoding.QuotedPrintable;\nmessage.AlternateViews.Add(plainTextView);	0
18468505	18468470	C# how to create a custom xml document	XmlDocument xDoc = new XmlDocument();\n\nxDoc.AppendChild( xDoc.CreateElement("root"));\n\nstring[] NodeArray = { "Fruits|Fruit", "Vegetables|Veggie" };\nforeach (string node in NodeArray)\n{\n    XmlNode xmlNode = xDoc.CreateNode(XmlNodeType.Element, node.Split('|')[0], null);\n    //xmlNode.Value = node.Split('|')[0];\n    xmlNode.InnerText = node.Split('|')[1];\n    xDoc.DocumentElement.AppendChild(xmlNode);\n\n}	0
10654551	10654292	Get random element from hashset?	Random randomizer = new Random();\nstring[] asArray = hashs.ToArray()\nstring randomLine = asArray[randomizer.Next(asArray.length)];	0
11162966	11162459	Set Default Value Of WCF DataMember Property	[DataMember] \npublic bool IsValid { get; set; }	0
16578625	16578437	How to put the result of executing a query into ViewData and pass to a view	public ActionResult Create()\n{\n    var Status = (from s in _db.ReservationsStatus where s.defaultStatus == true select  s.Id).First();\n\n    ViewData["Status"] = Status;\n    return View();\n}	0
3176103	3176051	LINQ method to group collection into subgroups with specified number of elements	Int64[] aValues = new Int64[] { 1, 2, 3, 4, 5, 6 };\n  var result = aValues\n          .Select( ( x, y ) => new KeyValuePair<Int64, Int32>( x, y ) )\n          .GroupBy( x => x.Value / 2 )\n          .Select( x => x.Select( y => y.Key ).ToList() ).ToList();	0
651747	651716	How to display an error message in an ASP.NET Web Application	try\n{\n    //do something\n}\ncatch (Exception ex)\n{\n    string script = "<script>alert('" + ex.Message + "');</script>";\n    if (!Page.IsStartupScriptRegistered("myErrorScript"))\n    {\n         Page.ClientScript.RegisterStartupScript("myErrorScript", script);\n    }\n}	0
26651886	26640975	Data binding directly to a store query (DbSet, DbQuery, DbSqlQuery, DbRawSqlQuery) is not supported	public IEnumerable<MovieDTO> GetAllMovies()\n    {\n        var data = this.Data.Movies.All().Select(x => new MovieDTO\n        {\n            Id = x.Id,\n            Name = x.Name,\n            ReleaseDate = x.ReleaseDate,\n            Rating = x.Rating,\n            Duration = x.Duration,\n            Director = x.Director,\n            Writer = x.Writer,\n            Cost = x.Cost,\n            Type = x.Type\n        }).OrderBy(x => x.Id).ToList();\n\n        return data;\n    }	0
24661904	24661818	Modifying a line in my XML file	XmlDocument doc = new XmlDocument();\ndoc.Load(@"file.xml");//the location of the file\nforeach (XmlNode node in doc.SelectNodes("/Following/Assembly")) {//or another path\n   XmlAttribute nameAttribute = node.Attributes["Name"];//check for the name\n   XmlAttribute enabledAttribute = node.Attributes["Enabled"];//or another attribute\n   if (nameAttribute != null && nameAttribute.Value == "MyRole.dll" && enabledAttribute != null) {//better than an exception\n       idAttribute.Value = "false";//set new value\n   }\n}   \ndoc.Save(@"file.xml");//save the file	0
15893162	15879026	CheckBox for Windows Phone	if (Convert.ToBoolean(cricket.IsChecked))\n            {\n                hobid.Add(1);\n            }\n if (Convert.ToBoolean(football.IsChecked))\n            {\n                hobid.Add(2);\n            }\n if (Convert.ToBoolean(music.IsChecked))\n            {\n                hobid.Add(3);\n            }\n if (Convert.ToBoolean(reading.IsChecked))\n            {\n                hobid.Add(4);\n            }	0
14215656	14214457	Sql server session mode in asp.net	Session.Abandon()	0
12286334	12286242	How to change starting index of rows in datagridview	DataGridView1.Rows[(myIndex + 8)].DoSomething();	0
27360182	27355057	Webservice ignores cultureinfo settings of application	// No exponent, may or may not have a decimal (if it doesn't it couldn't be parsed into Int32/64)\n            decimal dec;\n            if (decimal.TryParse(input, NumberStyles.Number, CultureInfo.InvariantCulture, out dec)) {\n                // NumberStyles.Number: AllowLeadingWhite, AllowTrailingWhite, AllowLeadingSign,\n                //                      AllowTrailingSign, AllowDecimalPoint, AllowThousands\n                return dec;\n            }	0
11808433	11808369	How do i Handle right click mouse in richTextBox in c#	private void richTextBox1_MouseDown(object sender, MouseEventArgs e)\n    {\n        if (e.Button == System.Windows.Forms.MouseButtons.Right)\n        {\n            MessageBox.Show("you got it!");\n        }\n\n    }	0
20583821	20583386	Method that gets index and returns an object in a specified index	List <Shape> _shapes;\n\npublic Shape GetShape(int index)\n{\n  return _shape[index]\n}	0
3739601	3739537	How to programmatically get session cookie name?	SessionStateSection sessionStateSection =\n  (System.Web.Configuration.SessionStateSection)\n  ConfigurationManager.GetSection("system.web/sessionState");\n\nstring cookieName =  sessionStateSection.CookieName;	0
23743351	23741503	Calling a Javascript function from .cs	ScriptManager.RegisterStartupScrip(this.Page, this.Page.GetType(), "GetSelectedItems", "GetSelectedItems();", true);	0
3296699	3296682	How do I get a list of the reports available on a reporting services instance	// Create a Web service proxy object and set credentials\n   ReportingService2005 rs = new ReportingService2005();\n   rs.Credentials = System.Net.CredentialCache.DefaultCredentials;\n\n   // Return a list of catalog items in the report server database\n   CatalogItem[] items = rs.ListChildren("/", true);\n\n   // For each report, display the path of the report in a Listbox\n   foreach(CatalogItem ci in items)\n   {\n      if (ci.Type == ItemTypeEnum.Report)\n         catalogListBox.Items.Add(ci.Path);\n   }	0
1960969	1958951	iText(sharp) side margins width	PdfPTable bTable = new PdfPTable(2);\nbTable.HorizontalAlignment = Element.ALIGN_LEFT;	0
14870401	14869454	Is it safe to read massive "count" of bytes from Stream then copy them to a new array?	return crypt.TransformFinalBlock(data, 0, data.Length);	0
19956112	19955985	Design pattern suggestion needed	Class A\n{\n    public void Print()\n    { \n        StartingProcedure();\n        SpecificPrint();\n        EndingProcedure();\n    }\n    protected void StartingProcedure()\n    {\n        /// something \n    }\n    protected void EndingProcedure()\n    {\n        /// something \n    }\n    protected virtual SpecificPrint() // could possibly be abstract\n    {\n    }\n}\n\nClass A_1 : A\n{\n    public override void SpecificPrint()\n    {\n        /// class specific print operation\n    }\n}\n\nClass A_2 : A\n{\n    public override void SpecificPrint()\n    {\n        /// class specific print operation\n    }\n}	0
21468432	21468293	Lambda expression - select single object with a IEnumerable<> property	var someViewModel = _repository.Table.Where(x => x.Id == someId)\n                    .Select(new ListViewModel()\n                            {\n                                GroupId = x.Group.Id,\n                                GroupTitle = x.Group.Title\n                                List = new List<SubViewModel> { new SubViewModel(x) }\n                            });	0
8382976	8382912	How to check if a string is made of repeating of the same characters?	string input = ...\nbool notAllSame = input.Distinct().Skip(1).Any();	0
22088140	22087467	Soft Reset in handyTerminal device with WindowsCE	using OpenNETCF.WindowsCE;   \n// ... \nPowerManagement.SoftReset();	0
5814284	5814188	How to implement MyMethod() with Format("blah {0}", someValue) signature like string.format	static string MyMethod( string format, params object[] paramList )\n{\n    return string.Format(format, paramList);\n}	0
10099055	10099020	Using an HTML file as template for creating PDFs with ABCpdf	Doc theDoc = new Doc();\ntheDoc.AddImageUrl("http://www.google.com/");\ntheDoc.Save(Server.MapPath("htmlimport.pdf"));\ntheDoc.Clear();	0
4257450	4257359	Regular Expression to get the SRC of images in C#	string matchString = Regex.Match(original_text, "<img.+?src=[\"'](.+?)[\"'].*?>", RegexOptions.IgnoreCase).Groups[1].Value;	0
3428655	3428622	Building a reversible StackPanel in WPF	double x = 0;\n    double y = 0;\n\n    var children = ReverseOrder ? InternalChildren.Reverse() : InternalChildren;\n    foreach (UIElement child in children)\n    {\n        var size = child.DesiredSize;\n        child.Arrange(new Rect(new Point(x, y), size));\n\n        if (Orientation == Horizontal)\n            x += size.Width;\n        else\n            y += size.Height;\n    }	0
7044499	7044437	Post method data in Page_load	Request.Params["data_key"]	0
27357893	27357817	keep only forward slashes and numbers with regex replace	urlReferrer = Regex.Replace(urlReferrer, @"/[^/\d]+", string.Empty);\n//=> /45/47	0
25962413	25962148	Tricky regular expression, lots of newlines and whitespaces	(?sx)\n(?<=\n   <span class="bold">Life:</span> \s* </div> \s*\n)\n[^<]+	0
31645104	31645063	How to Zip up a ZipFile using DotNetZip?	stream.Position = 0;	0
17413337	17413218	Can't set value of DeleteParameter using C#	SqlDataSource4.DeleteParameters["test"].DefaultValue = "test";	0
19663798	19641102	How to use Rx Throttle throttleDurationSelector in a complex grouping setting	var alarms = events\n    .GroupBy(e => e.Id)\n    .SelectMany(grp =>\n    {\n        // Determine light color based on delay between events\n\n        // go black if event arrives that is not stale\n        var black = grp\n            .Where(ev => (Date.Now - ev.TimeStamp) < TimeSpan.FromSeconds(2))\n            .Select(ev => "black");\n\n        // go yellow if no events after 1 second\n        var yellow = black\n            .Select(b => Observable.Timer(TimeSpan.FromSeconds(1)))\n            .SwitchLatest()\n            .Select(t => "yellow");\n\n        // go red if no events after 2 seconds\n        var red = black\n            .Select(b => Observable.Timer(TimeSpan.FromSeconds(2)))\n            .SwitchLatest()\n            .Select(t => "red");\n\n        return Observable\n            .Merge(black, yellow, red)\n            .Select(color => new { Id = grp.Key, Color = color });\n    });	0
6384862	6384789	Negate a string in C#	If(!e.FullPath.EndsWith("temp.temp"))	0
2291999	2291981	How to filter a listbox using a combobox	//Clear your listBox before filtering if it contains items\nif(yourListBox.Items.Count > 0)\n   yourListBox.Items.Clear();\nDirectoryInfo dInfo = new DirectoryInfo(<string yourDirectory>);                                 \nFileInfo[] fileInfo = dInfo.GetFiles("*" + <string yourChosenFileExtension>);\nforeach (FileInfo file in fileInfo)\n{  \n   yourListBox.Items.Add(file.Name);\n}	0
28923243	28923059	Linq - select N-level childs from hierarchy parents	--Variable to hold input value\nDECLARE @inputSourceID INT = 1;\n\n--Recursive CTE that finds all children of input SourceID\nWITH MyCTE\nAS\n(\nSELECT SourceID,\n        SourceParentID\nFROM table1\nWHERE SourceID = @inputSourceID\nUNION ALL\nSELECT  table1.SourceID, \n        table1.SourceParentID\nFROM table1\nINNER JOIN MyCTE \n    ON table1.SourceParentID = MyCTE.SourceID \n)\n\n--Join the CTE with the table2 to find all id\nSELECT table2.ID\nFROM MyCTE\nINNER JOIN table2\nON MyCTE.SourceID = table2.SourceID	0
18089625	18089603	Listview items to list(Of string)	list.AddRange(listView.Items.Cast<ListViewItem>().Select(lvi => lvi.Text));	0
13321489	13321421	Deserialize iTunes rss xml	[XmlElementAttribute(AttributeName = "duration", Namespace = "itunes")]	0
8251537	8251396	C# Oracle transactions	using (TransactionScope scope = new TransactionScope())\n{\n    // Save Requisition and get IdRequisition \n    // Save RequisitionRequirements \n}	0
9539743	9532039	How to clear ObjectDataSource cache manually	Cache["MyCacheDependency"] = DateTime.Now; -- invalidates cache.	0
17161464	17161336	Cant search users in LDAP with name containing *	searchFilter = searchFilter.replace("*","\\2a");	0
13015397	12774030	WCF - How do I return a success or failure message using Message Contracts	MemoryStream stream = new MemoryStream(Encoding.ASCII.GetBytes("<Success xmlns=\"http://tempuri.org\"></Success>"));\n\nXmlDictionaryReader xdr = XmlDictionaryReader.CreateTextReader(stream,new XmlDictionaryReaderQuotas());\n\nreturn Message.CreateMessage(MessageVersion.Soap11, "xxx/xxx/xxxResponse", xdr);	0
3436926	3436850	How to disable child form controls?	childForm.ControlToHide.Visible = false	0
4233958	4233663	Generate random RSA keys with RSACryptoServiceProvider	var rsaAlgo1 = new RSACryptoServiceProvider();\nvar rsaAlgo2 = new RSACryptoServiceProvider();\n\nvar xml1 = rsaAlgo1.ToXmlString(true);\nvar xml2 = rsaAlgo2.ToXmlString(true);\n\nif (xml1 != xml2)\n{\n   // it always goes here...\n}	0
926480	926400	How can I covert a binary file into a set of ascii charecters	string result = System.Convert.ToBase64String(yourByteArray);	0
17929351	17929125	Base class used as an abstract method's parameter?	public class Dinosaur : AnimalDefaultClass;\nDinosaur defaultDinosaur;\n\npublic void makeDinosaur(AnimalDefaultClass adc)\n{\n    adc.CopyFrom(defaultDinosaur);\n}\n\nMammalDefaultClass m;\nmakeDinosaur(m);	0
18775371	18775328	Finally dispose of WebSphere MQ connection	using(qmgr){\n    //do stuff\n}	0
9373602	9371441	How can I control the attempted value for a custom model binder?	var valueProviderResult = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);	0
7106928	7106880	Extension Methods - Changing the Namespace	ThirdPartyNamespace.Fetch(queryable, selector)	0
5976852	5976745	C# DateTime to W3CDTF	AnyValidDateTime.ToUniversalTime().ToString("u").Replace(" ", "T");	0
11951960	11951475	Adding an arc to a rectangle using GraphicsPath	p.AddLine(size.Width, 0, (size.Width / 2) + 10, 0);\n        p.AddArc(size.Width / 2 - 10, -10, 20, 20, 0, 180);\n        p.AddLine((size.Width / 2) - 10, 0, 0, 0);	0
20048224	20048128	How to Get Data from Stored Procedure in SQL Server	var rdr = command.ExecuteReader();\nwhile(rdr.Read()) \n{\n  var obj = new MyClass();\n  obj.Id = (int)rdr["Id"];\n  if (rdr["Name"] != DBNull.Value)\n  {\n    obj.name = (string)rdr["Name"];\n  }\n}\nrdr.Close();	0
16939150	16935826	How to draw images in a click event?	panel1.Invalidate();	0
23576752	23147708	What are the steps to create a PDF using C# in a Dynamics CRM plugin	templateReference.RoleAssignments = finalRoleAssignments;\n        var dataFieldValues = new TemplateReferenceFieldDataDataValue[3];\n        dataFieldValues[0] = new TemplateReferenceFieldDataDataValue();\n        dataFieldValues[0].TabLabel = "RoutingNumber";\n        dataFieldValues[0].Value = "R12345678";\n        dataFieldValues[1] = new TemplateReferenceFieldDataDataValue();\n        dataFieldValues[1].TabLabel = "AccountNumber";\n        dataFieldValues[1].Value = "A87654321";\n        dataFieldValues[2] = new TemplateReferenceFieldDataDataValue();\n        dataFieldValues[2].TabLabel = "Escrow";\n        dataFieldValues[2].Value = "E777333";\n\n        templateReference.FieldData = new TemplateReferenceFieldData();\n        templateReference.FieldData.DataValues = dataFieldValues;	0
3563765	3563745	Write to XML using c#	XDocument doc = new XDocument(\n    new XDeclaration("1.0", "utf-8", "yes"),\n    new XElement("wrap",\n        new XElement("content",\n            new XElement("title", "WHAT ARE ROLES?"),\n            new XElement("text", "Roles are security based permissions that can be assigned to registered user of the site. Users can have any number of role based security permissions that the administrator deems appropriate. Certain parts of the application may have security permissions assigned to them to make the information they contain available only to those users with the required permisions")\n        ) // continue with other content tags\n    ) \n);\ndoc.Save("test.xml");	0
18307033	18306909	delete specific lines from richTextBox?	List<string> finalLines = richTextBox1.Lines.ToList();\nfinalLines.RemoveAll(x => x.StartsWith("ALTER TABLE") && x.Contains("MOVE STORAGE"));\nrichTextBox1.Lines = finalLines.ToArray();	0
27977944	27977788	Create DLL without building project	MyDll.dll	0
16054364	16054284	How can I dynamically add Include to ObjectSet<Entity> using C#?	IQueryable<Work> query = null;  \n\nquery = this.ObjectContext.Works;\nforeach (var param in params)\n{\n    query = query.Include(param);\n}\nvar result = query.ToList();	0
29296634	29296379	Search for value in combobox (use of backspace)	private bool _isCheckedActivated = true;\n\nprivate void BestelIndexSearch(object sender, EventArgs e)\n{\n   if (! _isCheckedActivated)\n   {\n       _isCheckedActivated = true;\n       return;\n   }\n   [...]\n}\n\nprivate void comboBox1_KeyDown(object sender, KeyEventArgs e)\n{\n\n    if (e.KeyCode == Keys.Back)\n        _isCheckedActivated = false;\n}	0
17687045	17625460	Using Generics to Create a New Object	IDictionary list = source.GetType().GetProperty(dictionaryName).GetValue(source, null) as IDictionary;\nif (!list.Contains(property))\n{\n    Type[] arguments = list.GetType().GetGenericArguments();\n    list.Add(property, Activator.CreateInstance(arguments[1]));\n}	0
15791930	15790322	FindControl of a Formview which is inside an user control	protected void FormView1_DataBound(object sender, EventArgs e)\n    {\n        DropDownList ddlType = null;\n        if (FormView1.Row != null)\n        {\n            ddlType = (DropDownList)FormView1.Row.FindControl("ddlType");\n        }\n     }	0
5532078	5532059	How can I pass a collection of delegates to be run into a method	public delegate retType MyDelegate(param1type param1, param2type param2,...)\n\nList<MyDelegate> listToPass = new List<MyDelegate>();	0
12838930	12838850	Finding a xml config file	return File.Exists(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile)	0
15650402	15650349	How can I convert my LINQ query to use the lambda syntax and is there any advantage to doing this?	objectiveNames.Select(o => new Objective\n                         {\n                             Name = o,\n                             Description = o + " Description",\n                             ModifiedDate = DateTime.Now\n                         }).ToList();	0
5311911	5311841	Moq expectations on the same method twice in a row	IExpect.Returns	0
25027703	25026626	How to draw a PDF page into a System.Drawing.Image using iTextSharp?	string sDLLPath = Path.Combine(Path.GetDirectoryName(Application.ExecutablePath),\n    "gsdll32.dll");\nGhostscriptVersionInfo gvi = new GhostscriptVersionInfo(sDLLPath);\nusing (GhostscriptRasterizer rasterizer = new GhostscriptRasterizer())\n{\n    rasterizer.Open("sample.pdf", gvi, false);\n\n    int dpi_x = 96;\n    int dpi_y = 96;\n    for (int i = 1; i <= rasterizer.PageCount; i++)\n    {\n        Image img = rasterizer.GetPage(dpi_x, dpi_y, i);\n        // System.Drawing.Image obtained. Now it can be used at will.\n        // Simply save it to storage as an example.\n        img.Save(Path.Combine("C:\\Temp", "page_" + i + ".png")),\n            System.Drawing.Imaging.ImageFormat.Png);\n    }\n}	0
16295107	16295086	Accessing nth element of IEnumerable	var items = ReadTransactions(file_name).Skip(40).Take(10);	0
13276030	13273012	How to combine two model list to one model	var query1 = db.CtArticleDetail\n    .Where(a => a.tagNames.Equals(tagNames))\n    .Select(a => new NewsFilterModel() { ArticleDetail = a, Page = null });\nvar query2 = db.PcPage\n    .Where(a => a.tagNames.Equals(tagNames))\n    .Select(a => new NewsFilterModel() { ArticleDetail = null, Page = a });\nvar query3 = query1.Union(query2)\n    //.OrderBy(a => a.Date); -- Order here\n    ;	0
14178348	14177187	How to get the number of elements with value less than a particular limit in Azure Mobile Services	function read(query, user, request) {\n   mssql("SELECT COUNT(id) FROM table WHERE VALUE < 100", [], {\n      success: function(results) {\n         request.respond(200, results);\n      }\n   }    \n}	0
31296063	31254214	Report Column Based On Previous Column	ReportItems!cellname.Value	0
1047608	1044057	Getting image names from DLL as a List?	public static List<string> GetImageList()\n            {\n                System.Reflection.Assembly asm = System.Reflection.Assembly.GetExecutingAssembly();\n                System.Globalization.CultureInfo culture = Thread.CurrentThread.CurrentCulture;\n                string resourceName = asm.GetName().Name + ".g";\n                System.Resources.ResourceManager rm = new System.Resources.ResourceManager(resourceName, asm);\n                System.Resources.ResourceSet resourceSet = rm.GetResourceSet(culture, true, true);\n                List<string> resources = new List<string>();\n                foreach (DictionaryEntry resource in resourceSet)\n                {\n                    resources.Add((string)resource.Key);\n                }\n                rm.ReleaseAllResources();\n                return resources;\n            }	0
12397703	12396686	XML Serializer not serializing property which has public getter but no setter	[Serializable]\n[XmlRoot("Task"), SoapType("Task")]\npublic class TaskDto : IDto\n{\n    public int ID { get; set; }\n    public int TaskSequence { get; set; }\n}	0
24183772	24059076	Change VisualState of ListBox element	Storyboard.Targetproperty ="(Fill).(SolidColorBrush.Color)"	0
19125369	18218701	Using DataAnnotations with Regular Expressions to not Match	public class MyModel\n{\n    [RegularExpression(@"^((?!apt).)*$", ErrorMessage = "You can not have that")]\n    public string MyValue { get; set; }\n}	0
30644010	30643863	Detect if On Screen Keyboard is open	var arrProcs = Process.GetProcessesByName("osk");\nif (arrProcs.Length == 0)\n{\n   Process.Start("C:\\Windows\\System32\\osk.exe");\n}	0
1715468	1715434	Is there a way to test if a string is an MD5 hash?	[0-9a-f]{32}	0
11240917	11240853	How to Add/Remove items to ComboBox Collection?	cb01.Items.Remove(cb01.SelectedItem);	0
23220914	23220181	Reading a text file: 'If' character store information after character	var test = line.substring("W")	0
7720905	7720747	How do I select the value that occurs most frequently in queue via LINQ?	Queue<int> queue = new Queue<int>();\n\n        queue.Enqueue(1);\n        queue.Enqueue(2);\n        queue.Enqueue(3);\n        queue.Enqueue(4);\n        queue.Enqueue(5);\n        queue.Enqueue(2);\n        queue.Enqueue(3);\n        queue.Enqueue(2);\n        queue.Enqueue(4);\n\n        int number =(from c in queue\n                     group c by c into g\n                     orderby g.Count() descending\n                     select g.Key).FirstOrDefault();	0
4368359	4368299	Set timer in asp.net page	System.Threading.Thread.Sleep(5000);	0
16579015	16557133	Adding Slider values from DataTemplate in ListView	int total = 0;\n\n\n    private void _slidScore(object sender, RangeBaseValueChangedEventArgs e)\n    {\n        total -= (int)e.OldValue;\n        total += (int)e.NewValue;\n        _result.Text = total.ToString();\n    }	0
10143543	10143241	ValueInjecter - Joins multiple result sets into 1 collection LINQ?	var combined = from result in results.DeferredItems\n               join errorsAndWarning in errorsAndWarnings.DeferredItems\n                on result.MeetingID equals errorsAndWarning.MeetingID\n               select new CombinedResult().InjectFrom(result)\n                                          .InjectFrom(errorsAndWarning)\n                                          as CombinedResult;	0
19205476	18964275	How can I dynamically set the TransactionTimeout for a WCF service?	var transactionTimeout = TimeSpan.FromSeconds(...);\nvar behavior = serviceHost.Description.Behaviors.Find<ServiceBehaviorAttribute>();\nbehavior.TransactionTimeout = transactionTimeout.ToString();\nserviceHost.Open();	0
14195572	14190427	Sql server session mode in asp.net web applications	protected void Page_Init(object sender, EventArgs e)\n    {\n        if (Context.Session != null)\n        {\n            if (Session.IsNewSession)\n            {\n                HttpCookie newSessionIdCookie = Request.Cookies["ASP.NET_SessionId"];\n                if (newSessionIdCookie != null)\n                {\n                    string newSessionIdCookieValue = newSessionIdCookie.Value;\n                    if (newSessionIdCookieValue != string.Empty)\n                    {\n                        // This means Session was timed Out and New Session was started\n                        // Do whatever you want\n                    }\n                }\n            }\n        }\n    }	0
27351671	27349145	Get value from asp:RadioButton on mouseover	var myval = label[for='" + $(this).find("input:radio").attr("id") + "']").text();	0
759597	759551	Calculate total hours using DateTime columns in DataGridView	var minutes = listOfLogins.Sum(l => l.LogOutTime.Subtract(l.LoginTime).TotalMinutes);\nConsole.WriteLine("{0}h, {1}m", (int)(minutes / 60), minutes % 60);	0
4422954	4422900	Show only client-side validation with client and server validators in asp.net	protected void btnSubmit_Click(object sender, EventArgs e)\n{\n    if(!Page.IsValid)\n    {\n        return;\n    }\n}	0
18090423	17990072	Converting different object lists into a DataTable using FastMember	interface ICustomObject\n{\n    public string RequiredProperty { get; }\n\n    public void RequiredMethod();\n}\n\npublic class CustomObjectA : ICustomObject\n{\n    public string RequiredProperty\n    {\n        get\n        {\n            return "I'm CustomObjectA";\n        }\n    }\n\n    public void RequiredMethod()\n    {\n        // do anything\n    }\n}\n\npublic class CustomObjectB : ICustomObject\n{\n    public string RequiredProperty\n    {\n        get\n        {\n            return "I'm CustomObjectB";\n        }\n    }\n\n    public void RequiredMethod()\n    {\n        // do anything\n    }\n}\n\npublic void AcceptsAllCustomObjects(List<ICustomObject> Cookies)\n{\n    Console.WriteLine(Cookies[0].RequiredProperty);\n}	0
13006831	13006600	Group by two properties as one in Linq	var query = from b in Bookings\n    group b by new\n    {\n        b.Group, \n        b.Type, \n        b.Status,\n        InvType = String.Format({0}-{1},b.InvoicingFrequency, b.InvoicingLevel)\n    } into bookingGroup\n    select new BookingSummaryLine()\n    {\n        Group = bookingGroup.Key.UserGroup,\n        Type = bookingGroup.Key.UserGroup,\n        Status = bookingGroup.Key.FinancialStatus,\n        InvType = bookingGroup.Key.InvType\n    };	0
21464042	21463233	Unable to capture CMD output from RedirectStandardOutput	ProcessStartInfo startInfo = new ProcessStartInfo();\n        startInfo.WindowStyle = ProcessWindowStyle.Hidden;\n        startInfo.FileName = "cmd.exe";\n        string contentType = "\"Content-Type:text/xml\"";\n\n        string command = @"C:\blackboard\apps\sis-controller\sis-data\curl -s -k -H " + contentType + " -u " + txtBoxIntgrName.Text + ":" + txtBoxIntgrPass.Text + " -g https://" + txtBoxDomain.Text + "/webapps/bb-data-integration-flatfile-BBLEARN/endpoint/dataSetStatus/" + txtBoxReferenceID.Text;\n        startInfo.Arguments = "/user:Administrator \"cmd /c " + command + "\"";\n        startInfo.UseShellExecute = false;\n        startInfo.RedirectStandardOutput = true;\n        using (Process process = Process.Start(startInfo))\n        {\n            using (StreamReader reader = process.StandardOutput)\n            {\n                string result = reader.ReadToEnd();\n                rchTxtBoxDataSetStatus.Text = result;\n            }\n        }	0
27376447	27376403	Array is returning all values instead of 1 (Schoolwork)	foreach (string value in array)\n        {\n            Console.WriteLine("Dina nya namn ?r " +value);\n        }	0
34427925	34427887	Representing an n number of objects in one object	public T Ref<T>(){\n    return (T)Objs[typeof(T)];\n}	0
18466779	18466197	listview box not displaying data in details view	listView1.Columns.Add("myColumnHeader");	0
22832069	22830775	Run a Program on a Window Service with Logindata c# WinServices	Environment.UserName	0
2656194	2656116	Replace named group in regex with value	string result = Regex.Replace(input, @"(?<=abc_)\d+(?=_def)", "999");	0
6785044	6783686	How do I set the Where clause of an EntityDataSource in the code-behind	PaymentsDueEntityDataSource.Where = "it.UserName = @UserID";\nPaymentsDueEntityDataSource.WhereParameters.Add(new Parameter("UserID", TypeCode.Int32,  + HttpContext.Current.User.Identity.Name.ToString()));	0
9680550	9680506	check for valid number input - console application	string line = Console.ReadLine(); \nint value;\nif (int.TryParse(line, out value)) \n{\n    Console.WriteLine("Integer here!");\n}\nelse\n{\n    Console.WriteLine("Not an integer!");\n}	0
1610268	783131	How do I specify the name of my application's App.config file in WPF?	using System.Configuration;\n\npublic class TryThis\n{\n    Configuration config = ConfigurationManager.OpenExeConfiguration("C:\PathTo\app.exe");\n\n    public static void Main()\n    {\n        // Get something from the config to test.\n        string test = config.AppSettings.Settings["TestSetting"].Value;\n\n        // Set a value in the config file.\n        config.AppSettings.Settings["TestSetting"].Value = test;\n\n        // Save the changes to disk.\n        config.Save(ConfigurationSaveMode.Modified);\n    }\n}	0
17453330	17452852	Insert String into String C#	string xmlContent = "Your xml string content";\n   //parse the string as xml\n   XDocument xmlDoc = XDocument.Parse(xmlContent);\n   //get the element which matches your need.\n   XElement areaElement = \n       (from el in xmlDoc.Descendants("area") where el.Attribute("id").Value=="workplace"\n       select el).FirstOrDefault();\n   //create a new group element\n   XElement newGroup = new XElement("i added this group");\n   //add a value for this element or add attributes what ever is needed to this group here\n   //add the new group this will by default add it at the end of all other child elements.\n   areaElement.Add(newGroup);	0
10368720	10368685	XML-serializing a nested class including a list	public List<MessageEvent> Events;	0
14632642	14631911	Insert into string based on Regex Match Index	cleanFileContents = regex.Replace(\n    cleanFileContents,\n    Environment.NewLine + "$0");	0
33126586	33126320	set range of date to display in calendar	protected void DateRange(object sender, DayRenderEventArgs e)\n{\n    DateTime rangeStart = new DateTime(2015, 7, 4);\n    DateTime rangeEnd   = new DateTime(2016, 3, 15);\n\n    if (e.Day.Date < rangeStart || e.Day.Date > rangeEnd)\n    {\n        e.Day.IsSelectable = false;\n        e.Cell.ForeColor = System.Drawing.Color.Gray;\n    }\n}	0
3218923	3218910	Rename a file in C#	System.IO.File.Move("oldfilename", "newfilename");	0
11817705	11815783	display data on gridview accordingly to current login user not working	string strConnectionString = ConfigurationManager.ConnectionStrings["ASPNETDBConnectionString1"].ConnectionString;\n\n    SqlConnection myConnect = new SqlConnection(strConnectionString);\n\n    string strCommandText = "SELECT date, starttime, endtime, planner FROM bookings WHERE UserId =@UserId";\n    SqlCommand cmd = new SqlCommand(strCommandText, myConnect);\n  cmd.Parameters.AddWithValue("@UserId", UserId);\n\n    myConnect.Open();\n    SqlDataReader reader = cmd.ExecuteReader();  \n    myGridView.DataSource = reader;\n    myGridView.DataBind();\n\n    reader.Close();\n    myConnect.Close();	0
13560664	12860359	Retrieve Linkedin email address	Dim request = New RestRequest With {.Path = "requestToken"}\nrequest.AddParameter("scope", "r_emailaddress")	0
18824577	18824462	How to get all properties in a method of same base class?	foreach(PropertyInfo prop in this.GetType().GetProperties())\n{\n    prop.SetValue(this, newValue);\n}	0
7175311	7175170	How to extract unique characters from a string?	static string extract(string original)\n        {\n            List<char> characters = new List<char>();\n            string unique = string.Empty;\n\n            foreach (char letter in original.ToCharArray())\n            {\n                if (!characters.Contains(letter))\n                {\n                    characters.Add(letter);\n                }\n            }\n\n            foreach (char letter in characters)\n            {\n                unique += letter;\n            }\n\n            return unique;\n}	0
28709107	28702107	Access objects that haven't been created via Blend	var name = selectedItem.Name;\nvar expander = new Expander {Header = name};\n\nvar converter = new System.Windows.Media.BrushConverter();\nvar brush = (System.Windows.Media.Brush)converter.ConvertFromString("#00ff1e");\nexpander.Background = brush;	0
4045471	4043863	How to use reflection on a property of type ICollection?	using System;\nusing System.Collections;\nusing System.Collections.Generic;\nusing System.Data;\nusing System.Diagnostics;\n\n\npublic class testMain : ICloneable\n{\n\n    private string m_TestProp;\n\n    private List<Record> m_Items = new List<Record>();\n    public string TestProp\n    {\n        get { return m_TestProp; }\n        set { m_TestProp = value; }\n    }\n\n    public List<Record> Items\n    {\n        get { return m_Items; }\n    }\n\n\n    public object Clone()\n    {\n\n        testMain cpy =(testMain) this.MemberwiseClone();\n\n        foreach (Record rec in this.Items)\n        {\n            Record recCpy = (Record)rec.Clone();\n            cpy.Items.Add(recCpy);\n        }\n\n        return cpy;\n    }\n\n}\n\npublic class Record : ICloneable\n{\n\n    private string m_TestProp;\n\n    public string TestProp\n    {\n        get { return m_TestProp; }\n        set { m_TestProp = value; }\n    }\n\n    public object Clone()\n    {\n        return this.MemberwiseClone();\n    }\n}	0
5394027	5393953	creating  a dynamic "recently opened files" menu	private void menuItem_Click(object sender, EventArgs e)\n    {\n        ToolStripMenuItem item = new ToolStripMenuItem();\n        item.Text = "your file name";\n        item.Click += new EventHandler(yourEventHandler);\n        menuItem.DropDownItems.Add(item);\n    }	0
21271719	21271692	Best way to return a list of a particular property from a list with objects	return dlist.Select(x => x.Name).ToList();	0
8478545	8478318	How can I get a control inside my EditItemTemplate?	void DetailsView1_ModeChanged(object sender, EventArgs e)\n{\n    if (DetailsView1.CurrentMode != DetailsViewMode.Edit)\n        return;\n\n    foreach (DetailsViewRow row in DetailsView1.Rows)\n    {\n       var textbox = row.FindControl("txtName");\n    }\n}	0
31816310	31816049	Calling stored procedure values into the console application C#	//Adding values to the stored procedure\n                Console.WriteLine("Please enter project title and press Enter");\n\n                string projectTitle = Console.ReadLine();\n                while (String.IsNullOrWhiteSpace(projectTitle))\n                {\n                    Console.WriteLine("Please enter project title and press Enter");\n                    projectTitle = Console.ReadLine();\n                }\n\n\n                string outCsvFile = string.Format(@"D:\\test\\{0}.csv", projectTitle);\n                if (System.IO.File.Exists(outCsvFile))\n                {\n                    throw new ApplicationException("File already exist Name " + outCsvFile);\n                }\n                sqlCmd.Parameters.AddWithValue("@ProjectTitle", projectTitle); //this value I would like to add it when the console application is executed when I will hit on enter.	0
31805791	31631803	Get Integer as a string so I can parse it to integer?	(int)(long)SendSQLExecScalar(C);	0
3023548	3023520	Using DirectoryInfo in C#	newFileName = Path.Combine(@"c:\", "MyFile.Txt");	0
3864743	3864678	How to cut specified words from string	var bannedWords = @"\b(this|is|the|list|of|banned|words)\b";\n\nforeach(mail in mailList)\n    var clean = Regex.Replace(mail, bannedWords, "", RegexOptions.IgnoreCase);	0
8723741	8723656	Regex to return only first result from multiple matches	Regex regex = new Regex("(?<=Tax Invoice No[\s\r\n]+INV)(?'InvNo'[^\s\r\n]+)?");\nregex.Match(myString);	0
24269396	24269295	How to RemoveAll from list where any object property is null or empty?	theList.RemoveAll(x => x.GetType().GetProperties()\n                                  .Select(p => p.GetValue(x, null))\n                                  .Any(p => p == null));	0
15496171	15496068	Out of range exception in a dynamic list in C#	RxString = serialPort1.ReadExisting();	0
23258414	23258266	How to open a database in asp.net web forms?	string yourSQL = "SELECT FirstName FROM Employees";	0
8013688	8013480	c# Regex to modify all matching hrefs	resultString = Regex.Replace(subjectString, @"(?<=<a[^>]*?\bhref\s*=\s*(['""]))(.*)(?=\1.*?>)", "$2.html");	0
7575685	7575562	Is there a way to create a null value for .NET outside C#?	System.IntPtr.Zero	0
9241997	9241968	NHibernate - create order	var result = Session.CreateCriteria(typeof(Users))\n                    .AddOrder(Order.Desc("FirstName"))\n                    .AddOrder(Order.Desc("LastName"))\n                    .List<Users>();	0
18212585	18212449	Add parameter with no value	if (comboBox1.Text == "EmploueeID")\n{\n   mySqlCommand1.Parameters.AddWithValue("@EmployeeID", textBox1.Text);\n   mySqlCommand1.Parameters.AddWithValue("@EmployeeName",DbNull.Value);\n   mySqlCommand1.Parameters.AddWithValue("@Address", DbNull.Value);\n}	0
28381837	28381781	C#:How can I compare between the sum of every row in 2D array?	for( int i = 1; ...	0
6684078	6684052	How to error check for more than a certain amount of Command Parameters	if (args.Length != 2)\n{\n    // Display error\n}	0
25787411	25757177	No response in AG-Softwate MatriX	Config.NowXmppClient.StartTls = false;	0
5860772	5860233	Problem with multithreading concurrency in file download in web service	private static object padlock = new object();\n\npublic byte[] DownloadFile(int id) {\n  lock(padlock) {\n      // code here\n  }\n}	0
24208839	24208423	Looping through an List to select an Element in Selenium	selectLink(String title) {\n    driver.findElement(By.cssSelector("ul li a[title='" + title + "']").click();\n}	0
21921302	21909196	MSDN charts changing point values realtime?	chart1.Refresh()	0
30445404	30445221	Converting a number from a string to an int with decimals separated by comma or dot	private static int ConvertStringValue(string value)\n{\n  decimal valDouble;\n\n  var comma = (NumberFormatInfo)CultureInfo.InstalledUICulture.NumberFormat.Clone();\n  comma.NumberDecimalSeparator = ",";\n  comma.NumberGroupSeparator = ".";\n\n  var dot = (NumberFormatInfo)CultureInfo.InstalledUICulture.NumberFormat.Clone();\n  dot.NumberDecimalSeparator = ".";\n  dot.NumberGroupSeparator = ".";\n\n  if (decimal.TryParse(value, NumberStyles.Currency, comma, out valDouble))\n  {\n    return Convert.ToInt32(valDouble * 100); \n  }\n  else if (decimal.TryParse(value, NumberStyles.Currency, dot, out valDouble))\n  {\n    return Convert.ToInt32(valDouble * 100);\n  }\n  else\n  {\n    return Convert.ToInt32(value);\n  }\n}	0
24122347	24122053	Is it possible to let only a user selection trigger a SelectionChanged event on a DataGridView?	private bool _programmaticChange;\n\nprivate void SomeMethod()\n{\n    _programmaticChange = true;\n    dataGridView.ClearSelection();\n    _programmaticChange = false;\n}\n\n\nprivate void dataGridView_SelectionChanged(object sender, EventArgs e)\n{\n    if (_programmaticChange) return;\n    // some code\n}	0
10509338	10509284	RegEx Replace Facebook url	string subjectString = @"http://www.facebook.com/pages/somepagename/139629086070406";    \nstring resultString = Regex.Replace(subjectString, @"http://www.facebook.com/pages/.+?/(\d+)", "https://graph.facebook.com/$1/picture", RegexOptions.IgnoreCase);	0
23202559	23201703	Read another section of XML without creating new rows in table	var matchingElements = documentNode.Elements().Where(e => e.Name.LocalName == "DocumentSequenceID");\n\nvar firstSequenceNode = matchingElements.FirstOrDefault();\nvar secondSequenceNode = matchingElements.ElementAtOrDefault(1);	0
6704133	6688663	How to call onclick event on confirm message alert box?	if (document.getElementById("<%=isDirty.ClientID %>").value != document.getElementById("<%=txbText.ClientID %>").value) \n{ \n  var ssave = window.confirm('Your changes are not saved. Do you want to save your changes before you exit.') \nif (ssave == true) \n{ \n  document.getElementById('<%=btnSave.ClientID%>').click(); \n  return false; \n} \n  else return true; \n}	0
560945	560842	Creating an XML Element object from an XML Writer in C#	XmlDocument doc = new XmlDocument();\nXmlWriter xw = doc.CreateNavigator().AppendChild();	0
7380132	7380117	my first WCF server - works with "string" but doesn't work with custom interface?	[DataContract]\npublic class ConsoleData\n{\n    [DataMember]\n    public double CurrentIndicator\n    {\n        get { return 22; }\n        set { /* whatever */ }\n    }\n}\n\n[ServiceContract]\npublic interface IMBClientConsole\n{\n    [OperationContract]\n    ConsoleData GetData();\n}	0
22305786	22305682	Compare DateTime Lists, c# linq	yourList.Where(x=> x.Start <= endToCheck && x.End >= startToCheck)	0
850654	850586	force get/set access of private variables for private properties	// Non mutable Angle class with a normalized, integer angle-value\npublic struct Angle\n{\n  public Angle(int value)\n  {\n    Value = value;\n  } \n\n  private angle;\n  public Value \n  { \n    get { return angle; } \n    private set { angle = Normalize(value); } \n  }\n\n  public static int Normalize(int value)\n  {\n     if (value < 0) return 360 - (value % 360);\n     return value % 360;\n  }\n}\n\npublic class SomeClass\n{\n  public Angle EyeOrientation { get; set; }\n}	0
10009874	10009761	C# create table from datagrid (only 2 fields)	foreach( DataGridViewRow row in myDataGridView.Rows)\n{\n      DataRow tableRow = myDataTable.NewRow();\n      tableRow.Cells["part"].value = row["part"].value;\n      tableRow.Cells["pareto"].value = row["pareto"].value;\n      myDataTable.Rows.Add(tableRow);\n}	0
6820830	6820804	How to sum the columns and add it to the last row of column in a datagridview?	CellEndEdit event	0
6193115	6193070	subject line of email message	NotifyHtml("coe-RoomReservations@coe.berkeley.edu", string.format("#{0} Your event registration", registrationId), body);	0
28190037	28189241	Get expected Action Parameter type in OnActionExecuting	public class TestCustomAttr : System.Web.Mvc.ActionFilterAttribute\n{\n    public override void OnActionExecuting(ActionExecutingContext filterContext)\n    {\n        var ActionInfo = filterContext.ActionDescriptor;\n        var pars = ActionInfo.GetParameters();\n        foreach (var p in pars)\n        {\n\n           var type = p.ParameterType; //get type expected\n        }\n\n    }\n}	0
2107391	2107320	Function waits for response from other app	using System;\nusing System.Threading;\n\nclass Program\n{\n    static void Main(string[] args)\n    {\n        //    create the reset event -- initially unsignalled\n        var resetEvent = new ManualResetEvent(false);\n        //    information will be filled by another thread\n        string information = null;\n\n        //    the other thread to run\n        Action infoGet = delegate\n        {\n            //    get the information\n            information = Console.ReadLine();\n            //    signal the event because we're done\n            resetEvent.Set();\n        };\n\n        //    call the action in a seperate thread\n        infoGet.BeginInvoke(null, null);\n        //    wait for completion\n        resetEvent.WaitOne();\n        //    write out the information\n        Console.WriteLine(information);\n    }\n}	0
32388961	32386903	Is it possible to create a C#/Skype application that displays one of my selected windows?	Skype4COM.dll	0
1630297	1630277	Is there a Linq operation to determine whether there are items in a collection who have the same values for a pair of properties?	int totalCount = items.Count();\nint distinctCount = items.Select(x => new { x.Name, x.Other })\n                         .Distinct()\n                         .Count();	0
31718687	31703279	How to append key value to existing JToken	foreach (var a in ((Newtonsoft.Json.Linq.JProperty)(el)))\n            {\n                int i = 0;\n                foreach (var value in ((Newtonsoft.Json.Linq.JObject)(a)))\n                {\n                    i = i + Convert.ToInt32(value.Value);\n                    Console.WriteLine(value.Value);\n                }\n                if (i != 0)\n                {\n                    el.Parent["count"] = i;\n                }\n                else {\n                    el.Parent["count"] = 0;\n                }\n            }	0
12113915	12113838	using an .xsd file in a validation method	string schema;\nusing(StreamReader file = new StreamReader(path)\n{\n    schema = file.ReadToEnd();\n}	0
4431745	4431715	Trouble calling stored procedure with parameters	MyParameter.DbType = System.Data.DbType.Byte;	0
2655051	2654743	Cancel outlook meeting requests via MailMessage in C#	STATUS:CANCELLED	0
3476717	3476583	Data Binding in WPF control doesn't pick the new data from IPropertyChangedNotify call	public int Age\n{\n    get { return _age; }\n    set\n    {\n        var init = _age;\n\n        //You still need to change the _age to the value\n        _age = value;\n\n        this.CheckPropertyChanged<int>("Age", ref init, ref value);\n    }\n}	0
17813378	17813177	I need a drop down list to display a list of active cases, but I keep getting an error when there is more than one returned	masterCaseList.DataSource = MasterCasesBLL.GetAllMasterCases(false)\n    .Where(x => x.MainContact != null && x.MainContact.MainContact == true)\n    .Select(x => new { MainContact = x.MainContact.MainContactLabel, index = x.ID })\n    .ToList();	0
12718703	12718655	Split a string of number and words c#	var str = "1010 Firstname Midname LastName";              \nstring[] parts = str.Split(' ');             \nif (parts != null)             \n{                 \n    int idpart = Convert.ToInt32(parts[0]);\n    string firstpart = parts[1];             \n    string midpart = parts[2];\n    string lastpart = parts[3];\n}	0
30249367	30249346	convert to double cutting off zeroes	var s = price[i].ToString("#,##0.00");	0
14020984	13603521	Error while using agsXMPP in Windows 8 Metro App	client.OnMessageReceived = (msg, user) => appendLog(user.name + ":" + msg);	0
31721085	31720586	How to check if an element is actually holding some data	var ulElements = driver.FindElements(By.XPath("your xpath"));\nforeach (var ulElement in ulElements)\n{\n    var contentElements = ulElement.FindElements(By.CssSelector("your css"));\n    if (...) {}\n}	0
18617439	18617206	How can I add extra column in datagridview when I fetch data from database	DataGridView dgv = new DataGridView();\ndgv.DataSource = dtusers;\n\nDataGridViewColumn amount = new DataGridViewColumn();\namount.HeaderText = "Amount";\namount.Name = "Amount";\ndgv.Columns.Insert(0, amount);\n\nDataGridViewColumn narration = new DataGridViewColumn();\nnarration.HeaderText = "Narration";\nnarration.Name = "Narration";\ndgv.Columns.Insert(0, narration);	0
20065905	20065248	C# PCAP.NET how to send a valid TCP request?	PacketBuilder builder = new PacketBuilder(ethernetLayer, ipV4Layer, tcpLayer, payloadLayer);	0
6941508	6941366	Displaying Swedish charaters in aspx page	Encoding.UTF8.GetString(Encoding.GetEncoding(1252).GetBytes(garbledString))	0
5603508	5603480	How to get more than one column in Linq	var firstAnswer = p.Answers.FirstOrDefault().Select(new { VountCount = z.vountcount, IsSelected = z.isSelected });	0
26194070	26193955	Construct a LINQ query to return an item from a List that is related by one property to other members but which differs by a second property	List<Elephant> herd = new List<Elephant>{\n    new Elephant(), new Elephant(), new Elephant(), new Elephant()\n};\nherd[0].HasTrunk = true;\nherd[1].HasTrunk = true;\nherd[2].HasTrunk = false;\nherd[3].HasTrunk = false; \nherd[0].ClonedFrom = herd[0];\nherd[1].ClonedFrom = new Elephant();\nherd[2].ClonedFrom = herd[0];\nherd[3].ClonedFrom = new Elephant();\nherd.Where(elephant => !elephant.HasTrunk && herd.Where(elephant2 => \nelephant2.HasTrunk).Any(elephant2 => elephant2.ClonedFrom == elephant.ClonedFrom)); //One item - elephant number 2	0
14076830	14076449	ClearType in WPF when using AeroGlass	RenderOptions.ClearTypeHintProperty.OverrideMetadata(typeof(FrameworkElement), new FrameworkPropertyMetadata { DefaultValue = ClearTypeHint.Enabled });\nTextOptions.TextFormattingModeProperty.OverrideMetadata(typeof(FrameworkElement), new FrameworkPropertyMetadata { DefaultValue = TextFormattingMode.Display });	0
24785440	24785241	Multiple Early Bound Files in Web Service	Microsoft.Xrm.Sdk.Client.EntityLogicalNameAttribute(string)	0
20104818	19752954	Retrieve taxonomy terms from ContentItem in Orchard	//Note that I didn't try this code\n    public SomeController(ITaxonomyService taxonomyService){\n         var product = Services.ContentManager.Get<ContentItem>(33);\n         var terms = taxonomyService.GetTermsForContentItem(product.Id); //Or just 33\n\n   }	0
26392104	26391756	Does changing SSL Cert on a server break code?	System.Net.ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };	0
258876	258762	Serialize in a human readable text format	public static string ToJson(IEnumerable collection)\n        {\n            DataContractJsonSerializer ser = new DataContractJsonSerializer(collection.GetType());\n            string json;\n            using (MemoryStream m = new MemoryStream())\n            {\n                XmlDictionaryWriter writer = JsonReaderWriterFactory.CreateJsonWriter(m);\n                ser.WriteObject(m, collection);\n                writer.Flush();\n\n                json = Encoding.Default.GetString(m.ToArray());\n            }\n            return json;\n        }	0
11751343	11751255	How to find Black Pixel locations	for(int i = 0; i < img.width; i++){\n       for(int j = 0; j < img.height; j++){\n          // 20 is an arbitrary value and subject to your opinion and need.\n          if(img[i][j].color <= 20)\n             //store i and j, those are your pixel location\n       }\n     }	0
20716898	20716859	Unbox value of type object to long	long id = Convert.ToInt64(ObjectToConvert)	0
19788447	19788159	How to know if the asp.net site is accessed from a mobile device or from a system/laptop/machine(windows,mac etc)	Request.Browser.IsMobileDevice\nRequest.Browser.MobileDeviceManufacturer\nRequest.Browser.MobileDeviceModel\nRequest.Browser.ScreenPixelsWidth\nRequest.Browser.SupportsXmlHttp	0
29257963	29256164	Linq to EF - populate a (fairly simple) hierarchical object from EDM C#	var attributes =\n                                (from attr in model.CategoryAttributes.Include(c => c.Children)\n                                 where attr.ParentID == null\n//Edited Here\n                                 select new\n            {\n                Name = attr.Value,\n                ID = attr.ID,\n                Children = attr.Children\n                .Select(c => new AttributeObject() { Name = c.Value, ID = c.ID })\n                        .ToList()\n            })\n   //and Here execute the query with LINQ to Entities\n    .AsEnumerable()\n   //correctly cast to AttributeObject with LINQ to Object\n                .Select(n => \n                    new AttributeObject() {\n                Name=n.Name,\n                ID=n.ID,\n                Children=n.Children\n\n            }).ToList();	0
7985346	7985306	How can i automatically have a page save the current time to the DB in 5 minute intervals w/o postback?	window.setInterval('SaveUserInput()', 10000);	0
7830479	7830344	Linq - Dynamic GroupBy with IEnumerable<T>	static IEnumerable<IGrouping<object,Transaction>> GroupBy(string propName) \n{ \n    List<Transaction> transactions = new List<Transaction>  \n    { \n        new Transaction{ PaymentMethod="AA", SomeDateTime=DateTime.Now.AddDays(-1), SomeDecimal=1.2M, SomeInt64=1000}, \n        new Transaction{ PaymentMethod="BB", SomeDateTime=DateTime.Now.AddDays(-2), SomeDecimal=3.4M, SomeInt64=2000}, \n        new Transaction{ PaymentMethod="AA", SomeDateTime=DateTime.Now.AddDays(-1), SomeDecimal=3.4M, SomeInt64=3000}, \n        new Transaction{ PaymentMethod="CC", SomeDateTime=DateTime.Now.AddDays(2), SomeDecimal=5.6M, SomeInt64=1000}, \n    }; \n    var arg = Expression.Parameter(typeof(Transaction), "transaction"); \n    var body = Expression.Convert(Expression.Property(arg, propName), typeof(object)); \n    var lambda = Expression.Lambda<Func<Transaction, object>>(body, arg); \n    var keySelector = lambda.Compile(); \n\n    var groups = transactions.GroupBy(keySelector); \n    return groups; \n}	0
26103829	26095546	convert CDO.Message object to string using asp classic	dim myMail:set myMail= CreateObject("CDO.Message")\nmyMail.Subject="test subject"\nmyMail.to="test@test.com"\nmyMail.TextBody="testing Body message "\nmyMail.From="test2@test.com"\n\nDim Stream      \nSet Stream = myMail.GetStream()    \n'read the encoded data As a string\nmessageString = Stream.ReadText	0
26506438	26506275	How to tell if it's British Summer Time in C#	var info = TimeZoneInfo.FindSystemTimeZoneById("Greenwich Standard Time");\nDateTimeOffset localServerTime = DateTimeOffset.Now;\nbool isDaylightSaving = info.IsDaylightSavingTime(localServerTime);	0
9571868	9571775	How can i add DataID and password in an HTTP header?	var url = "http://myServiceCall_URL";\nvar serializer = new JavaScriptSerializer();\nvar request = WebRequest.Create(url);\nrequest.Method = "POST";\nrequest.ContentType = "application/json";\nrequest.Headers["DataID"] = "25";\nrequest.Headers["Password"] = "t123456";\nvar requestJson = serializer.Serialize(new\n{\n    Foo = "bar"\n});\nrequest.ContentLength = requestJson.Length;\n\nusing (var stream = request.GetRequestStream())\nusing (var writer = new StreamWriter(stream))\n{\n    writer.Write(requestJson);\n}\n\nusing (var response = request.GetResponse())\nusing (var stream = response.GetResponseStream())\nusing (var reader = new StreamReader(stream))\n{\n    var responseJson = reader.ReadToEnd();\n    var responseObj = serializer.DeserializeObject(responseJson);\n    // do something with the response\n}	0
1753122	1753099	Implementing 'belongs' with LINQ queries	var results = from a in myEntities.thing1 where MyList.Contains(a) select a;	0
12753367	12707939	How to write a custom serializer by using DataContractSerializer for generic type?	public sealed class CustomSerializer<T> : IDataCacheObjectSerializer\n{\n    object IDataCacheObjectSerializer.Deserialize(System.IO.Stream stream)\n    {       \n        DataContractSerializer dcs = new DataContractSerializer(typeof(T));\n        return dcs.ReadObject(stream);\n    }\n\n    void IDataCacheObjectSerializer.Serialize(System.IO.Stream stream, object value)\n    {\n        if (!(value is T)) \n        {\n            throw new AgrumentException();\n        }\n        DataContractSerializer dcs = new DataContractSerializer(typeof(T));\n        dcs.WriteObject(stream, value);\n    }\n}	0
22359364	22359207	Find sum of 2 largest numbers in a list of integers	arr.OrderByDescending(z=>z).Take(2).Sum()	0
7936960	7885848	c# Windows Form Application adding data to tables with relationship	private void buttonCreateSubmit_Click(object sender, EventArgs e)\n    {\n        Body body = new Body\n        {\n            body_content = richTextBoxBody.Text\n        };\n\n        tnDBase.AddToBodies(body);\n        tnDBase.SaveChanges();\n\n        var genid = tnDBase.Genres.Single(g => g.genre_name == comboBoxGenre.Text);\n\n        Article article = new Article()\n        {\n            article_name = textBoxTitle.Text,\n            genre_id = genid.genre_id,\n            status_id = 3,\n            body_id = body.body_id\n        };\n\n        tnDBase.AddToArticles(article);\n        tnDBase.SaveChanges();\n     }	0
18060750	18060665	Inline lambda in a linq expression?	Array result = someList.Select(t => new SelectListItem\n               {\n                   Text = t.Text,\n                   Value = t =>\n                   {\n                       /* some transformation logic */\n                   }\n               }).ToArray();	0
18699774	18678178	Unit testing plugins in an application with plugin architecture	public interface IPluginComponent\n{\n}\n\n[TestClass]\npublic abstract class BaseTests\n{\n    protected abstract IPluginComponent CreateComponent();\n\n    [TestMethod]\n    public void SomeTest()\n    {\n        IPluginComponent component = this.CreateComponent();\n\n        // execute test\n    }\n}\n\npublic class MyPluginComponent : IPluginComponent\n{\n}\n\n[TestClass]\npublic class MyPluginTests : BaseTests\n{\n    protected IPluginComponent CreateComponent()\n    {\n        return new MyPluginComponent();\n    }\n\n    [TestMethod]\n    public void CustomTest()\n    {\n        // custom test\n    }\n}	0
32538861	32538532	Chart Control Inside datalist	obj.openDataset()	0
23643031	23642913	Having trouble copying files that are beyond the root level while maintaining folder structure	static void Main(string[] args)\n{\n\n    string source = @"C:\Users\Yaron.Fainstein\Desktop\z1";\n\n    string target = @"C:\Users\Yaron.Fainstein\Desktop\z1-out";\n\n    CopyFolder(new DirectoryInfo(source), new DirectoryInfo(target));\n\n/*foreach (var file in System.IO.Directory.GetFiles(source, "*", SearchOption.AllDirectories))\n{\n\nFile.Copy(file, System.IO.Path.Combine(target, Path.GetFileName(file)), true);\n}*/\n} \n\npublic static void CopyFolder(DirectoryInfo source, DirectoryInfo target) {\n    foreach (DirectoryInfo dir in source.GetDirectories())\n    CopyFolder(dir, target.CreateSubdirectory(dir.Name));\n    foreach (FileInfo file in source.GetFiles())\n    file.CopyTo(Path.Combine(target.FullName, file.Name));\n}	0
4766080	4762470	error using type converter for application setting	[TypeConverter(typeof(TimeQuantityTypeConverter))]\npublic class TimeQuantity\n{	0
33513054	33512997	How to read csv file and store each cell value into a list (C#)	public void ReadCSV()\n{\n    var reader = new StreamReader(File.OpenRead(@"C:\data.csv"));    \n    while (!reader.EndOfStream)\n    {\n        var line = reader.ReadLine();\n        string[] values = line.Split('your separator');\n\n        foreach(string item in values)\n        {\n            Console.WriteLine(item);\n        }\n    }\n}	0
22413192	19233736	How to read an irregular xml string after change it to stream in C#	switch (Token)\n{\n\n   case "modoEntrada":\n\n      Regex exp_01 = new Regex("<descripcion>(?<arg>[A-Z]+)?</descripcion>");             \n      m = exp_01.Match(InputText);\n      break;\n\n   case "descripcionRechazo":\n\n      Regex exp_02 = new Regex("<descripcionRechazo>(?<arg>[A-Z ]+)?</descripcionRechazo>");\n      m = exp_02.Match(InputText);\n      break;\n   ...\n}\n\nif (m.Success)\n   ret = m.Groups["arg"].Value;\nelse\n   ret = "";\n\nreturn ret;	0
11679368	11679341	How to sort XDocument elements by attribute numerically?	XDocument input = XDocument.Load( Server.MapPath("~/App_Data/data.xml"));\n    XDocument data =\n        new XDocument(\n            new XElement("POSTBACK",\n                from node in input.Root.Elements()\n                orderby Convert.ToInt32( node.Attribute("id").Value)  ascending\n                select node));	0
18913463	16815119	Task Scheduler with C# DateTimePicker	dateTimePicker1.Format = DateTimePickerFormat.Time;\n        TaskService ts = new TaskService();\n        TaskDefinition td = ts.NewTask();\n        Trigger t = new TimeTrigger();\n        t.StartBoundary = System.DateTime.Now.Date +this.dateTimePicker1.Value.TimeOfDay;\n        td.Triggers.Add(t);\n        //string path1 = Path.GetDirectoryName(Application.ExecutablePath);\n        string path1 = Desktop + @"\Desktop\Release\ITWBackup.exe";\n        td.Actions.Add(new ExecAction(path1, null, null));\n        ts.RootFolder.RegisterTaskDefinition("ITWBackup", td);\n        ts.BeginInit();	0
14124078	14123887	add more value on chart in vs 2010	chart1.Series.Clear();\n\n    List<string> years = new List<string> { "1994", "1995", "1996", "1997" };\n    List<double> yearSales = new List<double> { 10000.23, 98000, 95876, 78097 };\n\n\n    Series yearSeries = chart1.Series.Add("sales");\n    yearSeries.Points.DataBindXY(years, yearSales);\n    yearSeries.ChartType = SeriesChartType.Line;\n\n    // do stuff....\n\n    // add one more value\n\n    years.Add("1998");\n    yearSales.Add(12345.67);\n    yearSeries.Points.DataBindXY(years, yearSales);	0
12067262	12067255	How to compare properties between two objects	if (!Object.Equals(\n     item.GetValue(person, null),\n     dto.GetType().GetProperty(item.Name).GetValue(dto, null)))\n { \n   diffProperties.Add(item);\n }	0
25953652	23369052	Reading JSON as a config, returns value null and crashes	public string Server = ConfigurationSettings.AppSettings["Server"].ToString();\n    public string Port = ConfigurationSettings.AppSettings["Port"].ToString();\n    public string Channel = ConfigurationSettings.AppSettings["Channel"].ToString();\n    public string OAuth = ConfigurationSettings.AppSettings["OAuth"].ToString();\n    public string Interval = ConfigurationSettings.AppSettings["Interval"].ToString();\n    public string Currency = ConfigurationSettings.AppSettings["Currency"].ToString();\n    public string Nick = ConfigurationSettings.AppSettings["Nick"].ToString();\n    public string BaseAdmin = ConfigurationSettings.AppSettings["BaseAdmin"].ToString();	0
2248422	2248411	Get all links on html page?	HtmlWeb hw = new HtmlWeb();\n HtmlDocument doc = hw.Load(/* url */);\n foreach(HtmlNode link in doc.DocumentElement.SelectNodes("//a[@href]"))\n {\n\n }	0
21182031	21181441	Getting xml node values try using SelectSingleNode and SelectNodes using c#	var expression = String.Format("//Customers[CustNo/text() = {0}]/", CustNos);\n\nvar SurnameNode = xmlDoc.SelectNodes(expression + "Surname");\nvar ForenameNode = xmlDoc.SelectNodes(expression +"Forename");	0
25171403	25171357	How can I convert my datetime to a string?	Stream stream = File.Open(date.ToString()+".txt"); FileMode.Open);	0
9856985	9856955	Where did the overload of DbQuery.Include() go that takes a lambda?	using System.Data.Entity;//ftw	0
2349707	2349653	Efficient way to analyze large amounts of data?	var query = from foo in List<Foo>\n            where foo.Prop = criteriaVar\n            select foo;	0
9500919	9499130	Forcing single-thread access to a resource	static BlockingCollection<Action<StringBuilder>> queue = new BlockingCollection<Action<StringBuilder>>();\n\n//Your thread unsafe resource...\nstatic StringBuilder resource = new StringBuilder();\n\nstatic void Main(string[] args)\n{\n    Task.Factory.StartNew(() =>\n    {\n        while (true)\n        {\n            var action = queue.Take();\n            action(resource);\n        }\n    });\n\n    //Now to do some work you simply add something to the queue...\n    queue.Add((sb) => sb.Append("Hello"));\n    queue.Add((sb) => sb.Append(" World"));\n\n    queue.Add((sb) => Console.WriteLine("Content: {0}", sb.ToString()));\n\n    Console.ReadLine();\n}	0
17568000	17566368	JSON.Net Convert inner object to C# Model	var json = @"\n                    {\n                        'APITicket': {\n                            'location': 'SOMEVALUE',\n                            'ticket': 'SOMEVALUE'\n                        }\n                    }";\n\n        //Parse the JSON:\n        var jObject = JObject.Parse(json);\n\n        //Select the nested property (we expect only one):\n        var jProperty = (JProperty)jObject.Children().Single();\n\n        //Deserialize it's value to a TicketModel instance:\n        var ticket = jProperty.Value.ToObject<TicketModel>();	0
1192452	1192447	C# newbie: find out the index in a foreach block	for(int i = 0; i < y.Count; i++)\n{\n}	0
21408587	21408148	Dealing with RGBA with decimal values	var regex = new Regex(@"([0-9]+\.[0-9]+)");\nstring colorData = "RGBA(1.000, 0.000, 0.000, 0.090)";\n\nvar matches = regex.Matches(colorData);\nint r = GetColorValue(matches[0].Value);\nint g = GetColorValue(matches[1].Value);\nint b = GetColorValue(matches[2].Value);\nint a = GetColorValue(matches[3].Value);\n\nvar color = Color.FromArgb(a,r,g,b);\n\n\nprivate static int GetColorValue(string match)\n{\n    return (int)Math.Round(double.Parse(match, CultureInfo.InvariantCulture) * 255);\n}	0
2016755	2016719	How to create a constructor that is only usable by a specific class. (C++ Friend equivalent in c#)	public interface IMyObject\n{\n     void DoSomething();\n}\n\npublic class MyFriendClass\n{\n     IMyObject GetObject() { return new MyObject(); }\n\n     class MyObject : IMyObject\n     {\n          public void DoSomething() { // ... Do something here\n          }\n     }\n}	0
12451049	12450238	Set multiple properties with one method	// using a generic method, you can specify the name of the property you want to set, \n    // the instance you want it set on, and the value to set it to...\n    private T SetProperty<T>(T instance, string propertyName, object value)\n    {\n        Type t = typeof(T);\n        PropertyInfo prop = t.GetProperty(propertyName);\n        prop.SetValue(instance, value, null);\n        return instance;\n    }	0
11623062	11623039	How to make objects Threadsafe on c#?	class Account\n{\n    decimal balance;\n    private Object thisLock = new Object();\n\n    public void Withdraw(decimal amount)\n    {\n        lock (thisLock)\n        {\n            if (amount > balance)\n            {\n                throw new Exception("Insufficient funds");\n            }\n            balance -= amount;\n        }\n    }\n}	0
19708468	19621133	Setting DistinguishedName using UserPrincipal	using (var ctx = new PrincipalContext(ContextType.Domain, null, "ou=TechWriters,dc=fabrikam,dc=com"))\n        {\n            using (var user = new UserPrincipal(ctx, "User1Acct", "pwd", true))\n            {\n                user.Save();\n            }\n\n            using (var entry = new DirectoryEntry("LDAP://cn=User1Acct;ou=TechWriters,dc=fabrikam,dc=com",null,null,AuthenticationTypes.Secure))\n            {\n                entry.Rename("cn=user1Acct");\n            }\n        }	0
3638823	3638738	C# - string to keywords	new RegEx(@"\b(\w)+\b").Matches(text);	0
15320765	15320735	for loop - highscore array	int prev = playerScore;\nfor (int i = 0; i < 10; i++)\n{\n    if (playerScore > scoreList[i])\n    {\n        int temp = scoreList[i];\n        scoreList[i] = prev;\n        prev = temp;\n    }\n}	0
5191023	5190881	Using SetParent to steal the main window of another process but keeping the message loops separate	Application.Run	0
13340041	13285491	How to Determine Which Printers are Connected using WMI	private string[] GetAvailablePrinters()\n{\n    var installedPrinters = new string[PrinterSettings.InstalledPrinters.Count];\n    PrinterSettings.InstalledPrinters.CopyTo(installedPrinters, 0);\n\n    var printers = new List<string>();\n    var printServers = new List<string>();\n    var searcher = new ManagementObjectSearcher("SELECT * FROM Win32_Printer");\n\n    foreach (var printer in searcher.Get())\n    {\n        var serverName = @"\\" + printer["SystemName"].ToString().TrimStart('\\');\n        if (!printServers.Contains(serverName))\n            printServers.Add(serverName);\n    }\n\n    foreach (var printServer in printServers)\n    {\n        var server = new PrintServer(printServer);\n        try\n        {\n            var queues = server.GetPrintQueues();\n            printers.AddRange(queues.Select(q => q.Name));\n        }\n        catch (Exception)\n        {\n            // Handle exception correctly\n        }\n    }\n\n    return printers.ToArray();\n}	0
3901883	3901844	Casting IEnumberable<T> back to original type with lambda expression	return CustomerList.Single(i => i.Id == id);	0
16722431	16722269	Algorithm to update average transfer rate on-the-go with C#	// somewhere outside: \nint lastdonetime = 0;\nint numprocessed = 0;\n\nbool processingMethod()\n{\n    DateTime dtNow = DateTime.Now;   //Time now\n    if (lastdonetime == 0) lastdonetime = dtNow;\n    if (dtNow - lastdonetime > 1) {\n       fAverageTransferRate = numprocessed / (dtNow - lastdonetime);\n       // Do what you want with fAverageTransferRate\n       lastdonetime = dtNow;\n       numprocessed = 0;\n    }\n }	0
656719	656715	Trying to pass in a boolean C# variable to a javascript variable and set it to true	myjavascript( <%= MyBooleanVariableInCSharp.ToString().ToLower() %> );	0
22635514	22634308	How to hide Data in Crystal Report if data does not meet	stringvar nameofvar:="";\nif(....)="H" then nameofvar:="Habbits" \nelse if(.....)="I" then nameofvar:="Indoor"\n\n//If there is a problem in this formula then specify	0
3512382	3512229	way to get exact below format of current date	DateTime.Now.ToString("dd MMM yyyy", CultureInfo.InvariantCulture)	0
30669969	30669910	How to return View() to another action without losing data of @Html.DropDownListFor()	public ActionResult Index()\n{\n    //do index action related stuff\n   BuildDataForDDL();\n   return View("index");\n}\n\npublic ActionResult AnotherAction(YourModel yourModel)\n{\n    //do another action related stuff\n   BuildDataForDDL();\n   ViewBag.Add(SelectedValue, yourModel.DropDownSelectedValue);\n   return View("index");\n}\n\nprivate void BuildDataForDDL()\n{\n   // build ddl\n   //ViewBag.Add(etc,etc);\n}	0
19859956	19858741	How do I handle modifier keys on the keydown event in a Windows Store / Modern UI App?	if ((state & CoreVirtualKeyStates.Down) == CoreVirtualKeyStates.Down) {\n        console.Text += "^";\n    }	0
16743374	16743276	calculate week number from date	DateTime dt=DateTime.Parse(MyTextBlock.Text);\nint weeknumber=weekNumber(dt);\nDateValue.Text=weeknumber.ToString();	0
3986081	3986050	Message box on server side in asp.net	ClientScript.RegisterStartupScript(GetType(), "someKey", "alert('oops');", true);	0
14980377	14980243	Converting a list of Points to an Array in C#	if (myPointList.Count >= 2)\n{\n    e.Graphics.DrawLines(Pens.Black, myPointList.ToArray());\n}	0
24679108	24656667	How to upload only a folder to Google Drive	File body = new File();\n        body.Title = "document title";\n        body.Description = "document description";\n        body.MimeType = "application/vnd.google-apps.folder";\n\n        // service is an authorized Drive API service instance\n        File file = service.Files.Insert(body).Execute();\n\n        //File body = new File();\n        //body.Title = "My document";\n        //body.Description = "A test document";\n        //body.MimeType = "text/plain";\n\n        //byte[] byteArray = System.IO.File.ReadAllBytes("document.txt");\n        //System.IO.MemoryStream stream = new System.IO.MemoryStream(byteArray);\n\n        //FilesResource.InsertMediaUpload request = service.Files.Insert(body, stream, "text/plain");\n        //request.Upload();\n\n        //File file = request.ResponseBody;	0
15910543	15910106	Setting up SendGrid with Windows Store Apps	Install-Package Sendgrid -Version 1.0.1	0
6850869	6850850	Reading file content to string in .Net Compact Framework	StringBuilder sb = new StringBuilder();\nusing (StreamReader sr = new StreamReader("TestFile.txt")) \n{\n    String line;\n    // Read and display lines from the file until the end of \n    // the file is reached.\n    while ((line = sr.ReadLine()) != null) \n    {\n        sb.AppendLine(line);\n    }\n}\nstring allines = sb.ToString();	0
26217697	26217556	Read specified line from external text file	string line54 = File.ReadLines(FileName).Skip(53).Take(1).First();	0
19136690	19136668	Wrong number of indices inside, expected 2	Temphighscores[counter, 0] = TempScoresToSplit[1];\nTemphighscores[counter, 1] = TempScoresToSplit[1];	0
7779225	7778909	How to DataBind to Combined Data from Multiple Objects?	public class Car\n{\n  public int CarID { get; set; }\n  public string CarName { get; set; }\n  public CarType CarType { get; set; }\n  public Make CarMake { get; set; }\n  // Expose CarTypeName as first-level property\n  public string CarTypeName { get {return CarType.CarTypeName; }}\n}\n\npublic class CarType\n{\n  public int CarTypeID { get; set; }\n  public string CarTypeName { get; set; }\n}	0
17823119	17821828	Calculating heat map colours	public string ConvertTotalToRgb(int low, int high, int cell)\n{\n    int range = high - low;\n    float h= cell/ (float)range;\n    rgb = HSVtoRGB(h,1.0f,1.0f);\n    return "#" + rgb.R.ToString("X2") + rgb.G.ToString("X2") + rgb.B.ToString("X2");\n}	0
28192471	28191147	Put selected rows from a GridView to a Listbox	foreach (DataGridViewRow  row in dataGridView1.SelectedRows)\n        {\n            listBox1.Items.Add(row.Cells[0].Value.ToString() +"  "+row.Cells[1].Value.ToString() +"  "+ row.Cells[2].Value.ToString());\n        }	0
6872142	6872044	Example of hooking a window?	LRESULT CALLBACK CallWndProc( int nCode, WPARAM wParam, LPARAM lParam ) {\n  if( nCode < 0 ) {\n    return CallNextHookEx( NULL, nCode, wParam, lParam );\n  }\n\n  CWPSTRUCT* pCWP = ( CWPSTRUCT* )lParam;\n\n  switch( pCWP -> message ) {\n  case WM_NCHITTEST: {\n    ...\n    return CallNextHookEx( NULL, nCode, wParam, lParam );\n  }\n  default:\n    return CallNextHookEx( NULL, nCode, wParam, lParam );\n  }\n}	0
9280931	9280722	how to create datatable with known numbers of columns and unknown numbers of rows in C#	//create an instance of a table\nSystem.Data.DataTable DT = new System.Data.DataTable();\n//dynamically add columns\nDT.Columns.Add("Column1");\nDT.Columns.Add("Column2");\nDT.Columns.Add("Column3");\n.\n.\n.\nDT.Columns.Add("Column60");\n\n//this is how you add rows to it\nDT.Rows.Add("val1", "val2", "val3",...."val60");\n\n//this is how you retrieve it\nforeach (DataRow row in DT.Rows)\n{\n   Console.Writeline(row[0].toString()); //returns the first column for each iteration\n}	0
19945886	19944336	Add Image to Xaml with C#	image.Source = new BitmapImage(new Uri("/MyNameSpace;images/someimage.png", UriKind.Relative));	0
28672737	28654117	How to bind NSObject <CBCentralManagerDelegate, CBPeripheralDelegate> in Monotouch?	[BaseType (typeof (NSObject))]\npublic interface OSWristBand2 : ICBCentralManagerDelegate, ICBPeripheralDelegate\n{\n}	0
6746343	6746082	How to Marshal a void* function return type and parameter in C#?	[DllImport("test.dll")]\npublic static extern unsafe void* VoidPointer(void* AValue);\n\npublic unsafe void Test()\n{\n    int* a;\n    int b = 0;\n\n    a = (int*)VoidPointer(&b);\n}	0
29099433	29099348	Serialize a custom List to JSON and deserialize the same to that custom list using Newtonsoft	var obj1 = JsonConvert.DeserializeObject<List<BookDetailsItem>>(tempstr)	0
15156462	15142213	converting a Texture2d circle to Farseer circleBody	batch.Draw(Body.Texture, ConvertUnits.ToDisplayUnits(Body.Position), null, Color.White, Body.Rotation, Body.Origin, 1f, SpriteEffects.None, 0f);	0
8482930	8482525	Put something around a block of text using regular expressions	static string Yellow(this string body, string match)\n{\n    string result = body;\n    foreach (Match m in Regex.Matches(body, match.Replace(" ", "(\\s*|(<[^>]+>)*)+")))                \n        result = result.Replace(m.Value, \n            string.Concat("<span class=yellow>", m.Value, "</span>"));\n    return result;\n}\n\nstring s = "Now x is y the time z for all <bold>quick</bold> brown foxes to jump over the lazy dogs back";\nstring m = "all quick brown foxes";\nConsole.WriteLine(s.Yellow(m));	0
30700872	30700766	An attempt to attach an autonamed database for file failed	Data Source=localhost\sqlexpress;Initial Catalog=MMABooks;Integrated Security=True	0
1718740	1718696	Replace first word with last word in C#	string newString = Regex.Replace(oldString, @"^(\w+)(.+) \[(\w+)\]$", "$3$2");	0
27398078	27398037	How to check if Datarow value is null	if (!row.IsNull("Int64_id"))\n{\n  // here you can use it safety\n   long someValue = (long)row["Int64_id"];\n}	0
1172227	1172212	dynamics crm 4 newlines in sdk	this.textBox.Text = myOpportunity.new_detail.ToString().Replace("\n", "\r\n");	0
2371843	2371677	Matching paragraphs with regex	RegexOptions.Singleline	0
14748621	12300025	How to handle WPF WebBrowser control navigation exception	private void Navigated(object sender, NavigationEventArgs navigationEventArgs)\n{\n    var browser = sender as WebBrowser;\n    if(browser != null)\n    {\n        var doc = AssociatedObject.Document as HTMLDocument;\n        if (doc != null)\n        {\n            if (doc.url.StartsWith("res://ieframe.dll"))\n            {\n                // Do stuff to handle error navigation\n            }\n        }\n    }\n}	0
2747825	2747812	How do I combine similar method calls into a delegate pattern?	private void ExecuteInTransaction<T>(Action<T> action, T entity)\n{\n    using (new Transaction())\n    {\n        action(entity);\n    }\n}\n\npublic void Save<T>(T entity)\n{\n    ExecuteInTransaction(Session.Save, entity);\n}	0
24967086	24966191	Deep loading data with EF6 and LINQ	_dataContext.UserRoles.Include("Role").Include("User").Where(where).AsQueryable();	0
29803689	29789999	Can I sort the data in DocumentDB by any attribute?	var rangeDefault = new DocumentCollection { Id = "rangeCollection" };                                                              \nrangeDefault.IndexingPolicy.IncludedPaths.Add(\nnew IndexingPath {\n    IndexType = IndexType.Range, \n        Path = "/",\n        NumericPrecision = 7 });\n\nrangeDefault = await client.CreateDocumentCollectionAsync(\n database.SelfLink, \nrangeDefault);	0
27888504	27888393	Insert ignored route first in the route table	RouteTable.Routes.Insert(\n 0, \n new Route(VirtualPathUtility.MakeRelative("~/", virtualPathRoot) + "{*pathInfo}", \n new StopRoutingHandler()));	0
19254689	19254255	SQL CE Not entering information to DB	if (checkPasswordsMatch() == "B")\n        {\n            SqlCeConnection myConnection = new SqlCeConnection("Data Source = pwdb.sdf");\n                    try\n                    {\n                        myConnection.Open();\n                    }\n                    catch (Exception ex)\n                    {\n                        MessageBox.Show(ex.ToString());\n                    }\n                    SqlCeCommand myCommand = myConnection.CreateCommand();\n                    myCommand.CommandType = CommandType.Text;\nmyCommand.CommandText = "INSERT INTO PW Values ('Master', '" + saltedcryps + "', '" + hashedResult + "');"\n                    myCommand.ExecuteNonQuery();\n                    myConnection.Close();\n                    this.Hide();\n\n        }	0
7108846	7108791	Validate date that is in three separate input fields for Month, Day, and Year	delegate(object sender, EventArgs args) {\n    if (!box1.Text.IsNullOrEmpty() &&\n        !box2.Text.IsNullOrEmpty() &&\n        !box3.Text.IsNullOrEmpty()) {\n        // Validate the user is at least 13\n    }\n}	0
17936700	17936679	Save image from resource file to computer - c#	static void ExtractFileResource(string resource_name, string file_name)\n    {\n        try\n        {\n            if (File.Exists(file_name))\n                File.Delete(file_name);\n\n            if (!Directory.Exists(Path.GetDirectoryName(file_name)))\n                Directory.CreateDirectory(Path.GetDirectoryName(file_name));\n\n            using (Stream sfile = Assembly.GetExecutingAssembly().GetManifestResourceStream(resource_name))\n            {\n                byte[] buf = new byte[sfile.Length];\n                sfile.Read(buf, 0, Convert.ToInt32(sfile.Length));\n\n                using (FileStream fs = File.Create(file_name))\n                {\n                    fs.Write(buf, 0, Convert.ToInt32(sfile.Length));\n                    fs.Close();\n                }\n            }\n        }\n        catch (Exception ex)\n        {\n            throw new Exception(string.Format("Can't extract resource '{0}' to file '{1}': {2}", resource_name, file_name, ex.Message), ex);\n        }\n    }	0
10237561	10237453	MVC 3 deserialization of jquery $.ajax request json into object populates nulls instead of blank strings	... = default(string);	0
10399440	10398672	How to use Regular expressions to replace a part of string in C#?	string temp = Regex.Replace(input, @"[fbs]", "a");	0
8624690	8624138	Sub report in crystal report	{MyTable.MyField} = TheConditionalValue	0
10049875	5843537	Filtering DataGridView without changing datasource	(dataGridViewFields.DataSource as DataTable).DefaultView.RowFilter = string.Format("Field = '{0}'", textBoxFilter.Text);	0
12116048	12113790	IComparer sort on databound Datagridview	RowComparer comp = new RowComparer();\n var query = northwindDataSet.Customers.AsEnumerable().OrderBy(q => q, comp);\n DataView dv = query.AsDataView();\n\n customersBindingSource.DataSource = dv;	0
29398667	29356848	How to wrap a hyperlink around each dynamically created ImageButton? Visual Studio	private void uploadImage()\n        {\n            string thumbnails = "<div id=\"photoThumbnailContainer\">";\n            foreach (string strFileName in Directory.GetFiles(Server.MapPath("~/Data/")))\n            {            \n                FileInfo fileInfo = new FileInfo(strFileName);\n                thumbnails += "<a href=\"Data/" + fileInfo.Name + "\" class=\"group1\"><div class=\"thumbnails\"><img src=\"Data/" + fileInfo.Name + "\" height=\"200px\" width=\"200px\" /></div></a>";   \n            }\n            thumbnails += "</div>";\n            lblImageThumbnails.Text = thumbnails;\n        }	0
7648358	7403211	WCF RIA authorization via local Windows groups	RequiresRole[]	0
590901	590871	Effect of casting to int in C#	// SomeList is not empty before the loop\nfor (int i = 0; i < myObject.SomeList.Count; i++)\n{\n    myObject.SomeList.Add(bar);\n}	0
5676860	5676791	F# Equivalent of Destructor	override x.Finalize() = ...	0
5011692	5011243	Zooming a UIScrollView in MonoTouch	var sv = new UIScrollView (window.Frame);\nvar iv = new UIImageView (UIImage.FromFile ("pat.jpg"));\n\nsv.AddSubview (iv);\nsv.ContentSize = iv.Frame.Size;\nsv.MinimumZoomScale = 1.0f;\nsv.MaximumZoomScale = 3.0f;\nsv.MultipleTouchEnabled = true;\nsv.ViewForZoomingInScrollView = delegate(UIScrollView scrollView) {\n    return iv;\n};      \n\nwindow.AddSubview (sv);\nwindow.MakeKeyAndVisible ();	0
25491487	25454765	DNN DAL2 Normalized Tables One to Many Relationship	public int MappingId { get; set; }\npublic int CategoryId { get; set; }\npublic int OptionId { get; set; }\n[ReadOnlyColumn]\npublic string CategoryName { get; set; }	0
23389520	23389335	SQL Server 2012 Date datatype contains 12:00:00AM	public string DateRequestedShortDate \n{ \n    get \n    {\n        return Date_Requested == null ? "" : Date_Requested.ToShortDateString();\n    }\n}	0
31010036	31009911	Force a class to use a constructor	class MyClass\n{\n\n    private void InitializeStuff()\n    {\n        //do some stuff.. set _val1,_val2,_val3\n    }\n\n    string _val1 = null;\n\n    public string Val1\n    {\n        get { return _val1; } \n        set \n        {\n           InitializeStuff();\n           _val1 = value; // Unless InitializeStuff sets this, in which case pass value in to it.\n        }\n    }  \n\n    public MyClass()\n    {\n        // If needed:\n        InitializeStuff();\n    }\n\n    public MyClass(string val_id1, string val_id2 = null, string val_id3 = null)\n    {\n        InitializeStuff();\n    }\n}	0
4477621	4477616	How would I read into a 'nested' Json file with 'DataContractJsonSerializer' in C# .NET (win7 phone)?	[DataContract]\npublic class Wrapper\n{\n    [DataMember]\n    public myInfo Main { get; set; }\n\n    [DataMember]\n    public myInfo Something { get; set; }\n}	0
17574319	17573544	Connecting to a SQL server using ADODB from a C# dll	Provider=SQLOLEDB	0
24021478	24021069	Converting possible null value to a default in a time conversion inside of Linq	var data = (from c in dbContext.Contacts\n                      select new\n                        {\n                            c.Id,\n                            TheirTime =EntityFunctions.AddHours(DateTime.UtcNow,c.TimezoneOffset)\n                     })	0
1019443	1019388	Adding a select all shortcut (Ctrl + A) to a .net listview?	private void listView1_KeyDown(object sender, KeyEventArgs e)\n{\n    if (e.KeyCode == Keys.A && e.Control)\n    {\n        listView1.MultiSelect = true;\n        foreach (ListViewItem item in listView1.Items)\n        {\n            item.Selected = true;\n        }\n    }\n}	0
22513273	22512993	How to notice if the app is being debugged	if (System.Diagnostics.Debugger.IsAttached)\n{\n  //Debug stuff\n}	0
19144807	19144459	Efficient method for converting text to phone keypad	var allValues = new List<KeyValuePair<string,char>>()\n\nallValues.Add(new KeyValuePair("abc2","2"));\nallValues.Add(new KeyValuePair("def3","3"));\netc, etc\n\nStringBuilder sb = new StringBuilder();\nforeach (var c in text)\n{\n    var matched = allValues.FirstOrDefault(kvp=> kvp.Key.Contains(c));\n    if(matched != null)\n    {\n       sb.Append(matched.Value);\n    }\n    else\n    {\n       sb.Append(" ");\n    }\n}\n\nConsole.WriteLine(sb.ToString());	0
31636859	31636201	How to store user's Location into the database?	navigator.geolocation.getCurrentPosition(show_map);\n\nfunction show_map(position) {\n  var latitude = position.coords.latitude;\n  var longitude = position.coords.longitude;\n  // show pushpin on map\n}	0
12418126	12417536	I want to learn how to network to add functionality to my XNA game	System.Net	0
34330954	34069759	Implementing a central 'manager' class for instances of a specific type across multiple assemblies	var cache = CacheManager.GetCache<DagCapaciteitCache>();	0
8894852	8894799	Converting a string to Date 	DateTime.ParseExact(date + hour, "ddMMyyyyHHmmss", CultureInfo.InvariantCulture);	0
7707512	7669490	WPF RichTextBox as a text queue for logging purposes	if (this.MaxLines > 0)\n{\n    this.lineCount++;\n    if (this.lineCount > this.MaxLines)\n    {\n        tr = new TextRange(rtbx.Document.ContentStart, rtbx.Document.ContentEnd);\n        tr.Text = tr.Text.Remove(0, tr.Text.IndexOf('\n'));\n        this.lineCount--;\n    }\n}\n\n//And for auto scrolling\nif (this.AutoScroll)\n{\n    rtbx.ScrollToEnd();\n}	0
5114239	472202	Looking for C# equivalent of scanf	sscanf()	0
27528855	27528729	Can I safely track unmanaged resources with a managed List?	_myUnmanagedResources.Clear();	0
29909383	29909352	DataGridView selected row to display in text boxes	if(dataGridView1.SelectedRows.Count > 0) // make sure user select at least 1 row \n{\n   string jobId = dataGridView1.SelectedRows[0].Cells[0].Value + string.Empty;\n   string userId = dataGridView1.SelectedRows[0].Cells[2].Value + string.Empty;\n\n   txtJobId.Text = jobId;\n   txtUserId.Text = userId;\n}	0
986507	986333	How to capture screen with timer using C#?	private Int32 pictureCount = 0;\n\n    public Form1()\n    {\n        timer1.Tick += new EventHandler(this.timer1_Tick);\n        timer1.Interval = (100) * (50);\n        timer1.Enabled = true;\n        timer1.Start();\n    }\n\n    private void timer1_Tick(object sender, EventArgs e)\n    {\n        /* Screen capture logic here */\n        sc.pictureBox1.Image.Save(pictureCount.ToString() + ".jpg", ImageFormat.Jpeg);\n        pictureCount++;\n    }	0
3932233	3932059	Limiting access to a public setter to specific objects (C#)	class MyClass\n{\n    public int MyProperty { get; set; }\n}\n\nclass MyProxyClass\n{\n    public MyProxyClass(MyClass myClass)\n    {\n        _myClass = myClass;\n    }\n\n    private MyClass _myClass;\n\n    public int MyProperty\n    {\n        get { return _myClass.MyProperty; }\n    }\n}	0
9547320	9546985	Show excel like data in c#	DataTable dt = new DataTable();\n//generate your data\ndataGridView1.DataSource = dt;	0
15558714	15558670	Writing to file using values from an object in C#	public void doStuff()\n{\n  AverageValues AVS = new AverageValues();\n  AVS.Bull = "Woof";\n  string path = "C:\\users\\kjenks11\\Averages.txt";\n  using (var NewFile = File.Create(path))\n  {\n    using (var writeIt = new StreamWriter(NewFile))\n    {\n      List<AverageValues> AV = new List<AverageValues> {AVS};\n      foreach (var value in AV)\n      {\n        writeIt.Write(value.Bull);\n      }\n    }\n  }\n}	0
3816485	3816434	Tutorial on displaying datasets from a SQL Server database using C#	using (var db = new MyDbDataContext())\n{\n    var myRecord= db.MyTable.FirstOrDefault();\n    Console.WriteLine(myRecord.MyColumn.ToString());\n}	0
11031341	11031293	How to Abort Current task in windows form application c#	bool abort = false;\n\nprivate void CaptureSignal()\n{\n    while (!abort) {\n    {\n        // Capture Signal Code ......\n    }\n}\n\nprivate void OnButtonClick(.............)\n{\n    abort = true;\n}	0
4555250	4554766	How to use XmlSerializer to deserialize a simple collection into an instance of List<string>	// add 'using System.Xml.Linq' to your code file\nstring file = @"C:\Temp\myconfig.xml";\nXDocument document = XDocument.Load(file);\nList<string> list = (from item in document.Root.Elements("item")\n                     select item.Value)\n                    .ToList();	0
9405489	9405458	Casting a custom collection type in C#	var catalog = (Course)ViewData["catalog"]	0
18819778	18819627	What datatype should I use for saving a file in a SQL Azure database?	binary, varbinary, image	0
23259530	23259090	How to create separate list for each property in class	dynamic myDynamicClass = new ExpandoObject();\n\n        foreach (var prop in typeof (Foo).GetProperties()) {\n            Type[] typeArgs = {prop.GetType()};\n            var listImplementationType = typeof (List<>).MakeGenericType(typeArgs);\n            var myList = Activator.CreateInstance(listImplementationType);\n            myDynamicClass[prop.Name] = myList;    \n        }	0
8798497	8798474	Get LastWriteTime of a decimal value	DateTime.FromOADate(347681594.3)	0
21827785	21827039	Add Sub child Nodes in TreeView	{\n        TreeNode treeNode = new TreeNode("Windows");\n        TreeNode node2 = new TreeNode("C#");\n        TreeNode node3 = new TreeNode("VB.NET");\n        node2.Nodes.Add("whatever");\n        treeNode.Nodes.Add(node2);\n        treeNode.Nodes.Add(node3);\n        treeView1.Nodes.Add(treeNode);\n        treeNode = new TreeNode("Linux");\n        treeView1.Nodes.Add(treeNode);\n       }	0
21958073	21958010	How to get the string from start of line to first openning bracket?	.+?(?=\()	0
27171253	27170820	DispatcherTimer will increasing Interval for every time it's used	timer.Tick += timer_Tick;	0
17148663	17148583	asp.net bind a list to a gridview	Text="<%# ((MasterBook) Container.DataItem).Name %>">	0
15112639	15111344	Change selected DataGridView row given an entity	private void SelectDataGridItem(Model.MyEntityType selectedItem)\n{\n    foreach (DataGridViewRow row in MyDataGrid.Rows)\n    {\n        var boundItem = (Model.MyEntityType) row.DataBoundItem;\n        if (boundItem.Id == selectedItem.Id)\n        {\n            row.Selected = true;\n            break;\n        }\n    }\n}	0
17670987	17670898	How to create an object of class from his string name?	// Depending on where you call it, it may require full class name: "MyNameSpace.MainClass"\n  var b = Activator.CreateInstance(Type.GetType("MainClass"));	0
31212828	31171034	Dispatcher.Run generates Win32Exception only when application is run as published application in RDS	public static IntPtr MessageReader(IntPtr hwnd, int message, IntPtr lParam, IntPtr wParam, ref bool result)\n    {\n        _log.Error(string.Format("MessageReader - {0}, {1}, {2}, {3}", hwnd, message, lParam, wParam));\n        return IntPtr.Zero;\n    }\n    public static IntPtr MessageReader(IntPtr hwnd, int message, IntPtr lParam, IntPtr wParam, ref bool result)\n    ....\n        FieldInfo ArgsField = typeof(DispatcherOperation).GetField("_args", BindingFlags.NonPublic | BindingFlags.Instance);\n        Dispatcher.CurrentDispatcher.Hooks.OperationStarted += new DispatcherHookEventHandler((obj, args) =>\n        {\n            System.Windows.Interop.HwndSource source = ArgsField.GetValue(args.Operation) as System.Windows.Interop.HwndSource;\n            if (source != null)\n            {\n                source.AddHook(new System.Windows.Interop.HwndSourceHook(MessageReader));\n            }\n        });\n        Dispatcher.Run();	0
34401927	34401427	How to route Optional URI parameters to API Controller functions	public string GetTradable(string item)\n{\n    ....\n}	0
4767375	4767360	Tracing instantiation in a base class	this.GetType().Name	0
31741628	31602748	Using GMAP.NET for c#, how do I use a marker OnMarkerClick without calling map MouseClick?	void map_Click(object sender, EventArgs e)\n{\n     Console.WriteLine("Marker hit? " + ((GMapControl)sender).IsMouseOverMarker);\n     Console.WriteLine("Polygon hit? " + ((GMapControl)sender).IsMouseOverPolygon);\n     Console.WriteLine("Route hit? " + ((GMapControl)sender).IsMouseOverRoute);\n}	0
19580224	19579798	Custom ValidationAttribute Data Annotation: return NO rules from GetClientValidationRules	return Enumerable.Empty<ModelClientValidationRule>()	0
5937548	5913274	C# telerik grid cell value from template column	foreach (GridDataItem item in grdHeader.EditItems)\n            {\n                // if in editing mode\n                GridEditableItem edititem = (GridEditableItem)item.EditFormItem;\n                RadTextBox txtHeaderName = (RadTextBox)edititem.FindControl("txbId");\n                //otherwise\n                Label lbl= (Label)edititem.FindControl("lblId");\n                string id = lbl.Text;\n            }	0
13724383	13724051	Fluent NHibernate One to One Save	public class WorkMap : ClassMap<WorkEntity>\n{\n    public WorkMap()\n    {\n        Id(x => x.WorkId).Column("ID_ZLECENIE").GeneratedBy.Sequence("SEQ_TAE_ZLECENIE");\n        HasOne(x => x.OrderExtension)\n            .Cascade.All();\n     }\n}\n\npublic class OrderExtensionMap : ClassMap<OrderExtensionEntity>\n{\n    public OrderExtensionMap()\n    {\n        LazyLoad();\n\n        Id(x => x.Id).Column("ID_ZLECENIE").GeneratedBy.Foreign("Work");\n        HasOne(x => x.Work).Constrained();\n        HasMany(x => x.IssueInformation).KeyColumn("FK_ZLECENIE");\n    }\n}	0
22017557	22014943	how to Upload Choosed Image To Parse object?	byte[] postData = new byte[(int)e.ChosenPhoto.Length];\ne.ChosenPhoto.Read(postData, 0, (int)e.ChosenPhoto.Length);	0
27524737	27524020	Something similar to SelectedItem but for menu items?	private void myList_Click(object sender, RoutedEventArgs e)\n    {\n        MessageBox.Show((e.OriginalSource as MenuItem).Header.ToString());\n    }	0
23867154	23782918	MVC4 Localization with DisplayName in Database	public override string DisplayName\n{\n   get\n   {\n        var culture = Thread.CurrentThread.CurrentUICulture; \n        var displayName = db.sp_getValueFromDatabase(id, culture.Name).firstOrDefault();\n   }\n}	0
12565190	12564327	Entity Framework v4 - Simple Stored Procedure Select Statement from Linked Server (Open Query) Returning -1	declare @t table(ID int, value nvarchar(50))\ninsert @t (ID, value)\nselect Id,Value FROM OPENQUERY(SERVER, 'SELECT * FROM db.table')\n\nselect ID, Value from @t	0
33263614	33263605	How to not open multiple windows in WPF	LoginDialog _dialog;\n\nprivate void LoginBtn_Click(object sender, RoutedEventArgs e)\n{\n    if(_dialog == null)\n    {\n        _dialog = new LoginDialog();\n     }\n    _dialog.Show();    \n}	0
33119703	33105221	How do determine if drop was exactly with right mouse button up?	e.KeyStates == DragDropKeyStates.RightMouseButton	0
5301319	5301164	How to find point between two keys in sorted dictionary	dic.Keys.Zip(dic.Keys.Skip(1), \n              (a, b) => new { a, b })\n         .Where(x => x.a <= datapoint && x.b >= datapoint)\n         .FirstOrDefault();	0
1657405	1657381	How to make doubles always contain a . character?	double d = 3.47;\nConsole.WriteLine(d.ToString(CultureInfo.InvariantCulture));	0
26194331	26194288	Displaying values from a database on different rows in a textbox C#	nsTextBox1.Text += sUsername + ":" + sPasswords + Enviroment.NewLine;	0
9887803	9887769	array of strings as property in C#	public class FormatterUI\n{\n      string[] args;\n\n      public string[] CmdLineParams // HERE!!!!\n      {\n          set\n          {\n              args=value;\n          }\n      }	0
9077187	9062550	Call a C++ DLL method from a C# application	[DllImport("HPRDH.dll", CallingConvention = CallingConvention.Cdecl)]\npublic static extern UInt32 PrtRead(IntPtr hPrt, UInt32 dwTimeout, ref UInt32 pdwType, out UInt32 pdwParArray, ref UInt32 pdwArraySize, ref byte[] pbReadData, ref UInt32 pdwReadDataLen);	0
20776058	20775815	Any way to access to a variable of type "var", defined in code behind, from aspx file?	public IQueryable<Organization> query;	0
9381861	9381559	UTF-8 to C# string from a DataReader	var dbEnc = Encoding.UTF8;\nvar uniEnc = Encoding.Unicode;\nbyte[] dbBytes = dbEnc.GetBytes(dbString);\nbyte[] uniBytes = Encoding.Convert(dbEnc, uniEnc, dbBytes);\nstring msg = uniEnc.GetString(uniBytes);	0
19454445	19454397	Store BitmapImage in a text file (and back again)	string bitmapImageAsString=Convert.ToBase64String(binaryData);	0
5000059	4966358	How to check the datatype of a property in an entity in a T4 template file	if (((PrimitiveType)edmProperty.TypeUsage.EdmType).\n        PrimitiveTypeKind == PrimitiveTypeKind.DateTime && edmProperty.Nullable)	0
26198990	26198904	Way To Use Setter When Setting Element Within Array	ObservableCollection<T>	0
19953890	19953818	Use two models in 1 view?	public class CompositeModel\n{\n    public ICollection Collection {get; set; }\n\n    public SignInModel SignInModel {get; set; }\n}	0
